blob: 34465f5a2b2d500037d598665e8da7efa4c926d2 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
GregFcd1f1692017-09-21 18:40:22 -060055#ifdef ENABLE_OPT
56 #include "spirv-tools/optimizer.hpp"
57 #include "message.h"
58 #include "SPVRemapper.h"
59#endif
60
61#ifdef ENABLE_OPT
62using namespace spvtools;
63#endif
64
John Kessenich140f3df2015-06-26 16:58:36 -060065// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020066#include "../glslang/MachineIndependent/localintermediate.h"
67#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060068#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050069#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060070
John Kessenich140f3df2015-06-26 16:58:36 -060071#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050072#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040073#include <list>
74#include <map>
75#include <stack>
76#include <string>
77#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060078
79namespace {
80
qining4c912612016-04-01 10:35:16 -040081namespace {
82class SpecConstantOpModeGuard {
83public:
84 SpecConstantOpModeGuard(spv::Builder* builder)
85 : builder_(builder) {
86 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040087 }
88 ~SpecConstantOpModeGuard() {
89 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
90 : builder_->setToNormalCodeGenMode();
91 }
qining40887662016-04-03 22:20:42 -040092 void turnOnSpecConstantOpMode() {
93 builder_->setToSpecConstCodeGenMode();
94 }
qining4c912612016-04-01 10:35:16 -040095
96private:
97 spv::Builder* builder_;
98 bool previous_flag_;
99};
100}
101
John Kessenich140f3df2015-06-26 16:58:36 -0600102//
103// The main holder of information for translating glslang to SPIR-V.
104//
105// Derives from the AST walking base class.
106//
107class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
108public:
John Kessenich121853f2017-05-31 17:11:16 -0600109 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800126 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800127 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100128 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700129 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800130 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600131 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600132 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
134 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600135 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
136 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
137 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600138 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700139 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600140 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600141 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
142 glslang::TLayoutPacking, const glslang::TQualifier&);
143 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
144 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700145 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700146 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800147 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600148 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700149 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700150 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
151 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
152 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100153 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600154
John Kessenich6fccb3c2016-09-19 16:01:41 -0600155 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600156 bool writableParam(glslang::TStorageQualifier);
157 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 void makeFunctions(const glslang::TIntermSequence&);
159 void makeGlobalInitializers(const glslang::TIntermSequence&);
160 void visitFunctions(const glslang::TIntermSequence&);
161 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600163 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
164 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
166
qining25262b32016-05-06 17:25:16 -0400167 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
168 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
169 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800170 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800171 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600172 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800173 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800174 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800175 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600176 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800177 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600178 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
179 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700180 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700182 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400183 spv::Id createSpvConstant(const glslang::TIntermTyped&);
184 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600185 bool isTrivialLeaf(const glslang::TIntermTyped* node);
186 bool isTrivial(const glslang::TIntermTyped* node);
187 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800188 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600189
John Kessenich121853f2017-05-31 17:11:16 -0600190 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600191 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600192 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700193 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 int sequenceDepth;
195
Lei Zhang17535f72016-05-04 15:55:59 -0400196 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400197
John Kessenich140f3df2015-06-26 16:58:36 -0600198 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
199 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700200 bool inEntryPoint;
201 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700202 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700203 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600204 const glslang::TIntermediate* glslangIntermediate;
205 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800206 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600207
John Kessenich2f273362015-07-18 22:34:27 -0600208 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600209 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600210 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700211 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600212 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600213 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600214};
215
216//
217// Helper functions for translating glslang representations to SPIR-V enumerants.
218//
219
220// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700221spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600222{
John Kessenich66e2faf2016-03-12 18:34:36 -0700223 switch (source) {
224 case glslang::EShSourceGlsl:
225 switch (profile) {
226 case ENoProfile:
227 case ECoreProfile:
228 case ECompatibilityProfile:
229 return spv::SourceLanguageGLSL;
230 case EEsProfile:
231 return spv::SourceLanguageESSL;
232 default:
233 return spv::SourceLanguageUnknown;
234 }
235 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600236 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 default:
238 return spv::SourceLanguageUnknown;
239 }
240}
241
242// Translate glslang language (stage) to SPIR-V execution model.
243spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
244{
245 switch (stage) {
246 case EShLangVertex: return spv::ExecutionModelVertex;
247 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
248 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
249 case EShLangGeometry: return spv::ExecutionModelGeometry;
250 case EShLangFragment: return spv::ExecutionModelFragment;
251 case EShLangCompute: return spv::ExecutionModelGLCompute;
252 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600254 return spv::ExecutionModelFragment;
255 }
256}
257
John Kessenich140f3df2015-06-26 16:58:36 -0600258// Translate glslang sampler type to SPIR-V dimensionality.
259spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
260{
261 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700262 case glslang::Esd1D: return spv::Dim1D;
263 case glslang::Esd2D: return spv::Dim2D;
264 case glslang::Esd3D: return spv::Dim3D;
265 case glslang::EsdCube: return spv::DimCube;
266 case glslang::EsdRect: return spv::DimRect;
267 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700268 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700270 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600271 return spv::Dim2D;
272 }
273}
274
John Kessenichf6640762016-08-01 19:44:00 -0600275// Translate glslang precision to SPIR-V precision decorations.
276spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600277{
John Kessenichf6640762016-08-01 19:44:00 -0600278 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700279 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600280 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 default:
282 return spv::NoPrecision;
283 }
284}
285
John Kessenichf6640762016-08-01 19:44:00 -0600286// Translate glslang type to SPIR-V precision decorations.
287spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
288{
289 return TranslatePrecisionDecoration(type.getQualifier().precision);
290}
291
John Kessenich140f3df2015-06-26 16:58:36 -0600292// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600293spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600294{
295 if (type.getBasicType() == glslang::EbtBlock) {
296 switch (type.getQualifier().storage) {
297 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600298 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600299 case glslang::EvqVaryingIn: return spv::DecorationBlock;
300 case glslang::EvqVaryingOut: return spv::DecorationBlock;
301 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700302 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600303 break;
304 }
305 }
306
John Kessenich4016e382016-07-15 11:53:56 -0600307 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600308}
309
Rex Xu1da878f2016-02-21 20:59:01 +0800310// Translate glslang type to SPIR-V memory decorations.
311void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
312{
313 if (qualifier.coherent)
314 memory.push_back(spv::DecorationCoherent);
315 if (qualifier.volatil)
316 memory.push_back(spv::DecorationVolatile);
317 if (qualifier.restrict)
318 memory.push_back(spv::DecorationRestrict);
319 if (qualifier.readonly)
320 memory.push_back(spv::DecorationNonWritable);
321 if (qualifier.writeonly)
322 memory.push_back(spv::DecorationNonReadable);
323}
324
John Kessenich140f3df2015-06-26 16:58:36 -0600325// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700326spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600327{
328 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700329 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600330 case glslang::ElmRowMajor:
331 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700332 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600333 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 default:
335 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600336 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 }
338 } else {
339 switch (type.getBasicType()) {
340 default:
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 break;
343 case glslang::EbtBlock:
344 switch (type.getQualifier().storage) {
345 case glslang::EvqUniform:
346 case glslang::EvqBuffer:
347 switch (type.getQualifier().layoutPacking) {
348 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600349 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
350 default:
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 case glslang::EvqVaryingIn:
354 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700355 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700358 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 }
361 }
362 }
363}
364
365// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600366// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700367// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800368spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600369{
Rex Xubbceed72016-05-21 09:40:44 +0800370 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700371 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800373 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700374 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700375 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600376 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800377#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800378 else if (qualifier.explicitInterp) {
379 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800380 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800381 }
Rex Xu9d93a232016-05-05 12:30:44 +0800382#endif
Rex Xubbceed72016-05-21 09:40:44 +0800383 else
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800385}
386
387// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600388// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800389// should be applied.
390spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
391{
392 if (qualifier.patch)
393 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700394 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600395 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700396 else if (qualifier.sample) {
397 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700399 } else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
John Kessenich92187592016-02-01 13:45:25 -0700403// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700404spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600405{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700406 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600407 return spv::DecorationInvariant;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410}
411
qining9220dbb2016-05-04 17:34:38 -0400412// If glslang type is noContraction, return SPIR-V NoContraction decoration.
413spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
414{
415 if (qualifier.noContraction)
416 return spv::DecorationNoContraction;
417 else
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400419}
420
David Netoa901ffe2016-06-08 14:11:40 +0100421// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
422// associated capabilities when required. For some built-in variables, a capability
423// is generated only when using the variable in an executable instruction, but not when
424// just declaring a struct member variable with it. This is true for PointSize,
425// ClipDistance, and CullDistance.
426spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600427{
428 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700429 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600430 // Defer adding the capability until the built-in is actually used.
431 if (! memberDeclaration) {
432 switch (glslangIntermediate->getStage()) {
433 case EShLangGeometry:
434 builder.addCapability(spv::CapabilityGeometryPointSize);
435 break;
436 case EShLangTessControl:
437 case EShLangTessEvaluation:
438 builder.addCapability(spv::CapabilityTessellationPointSize);
439 break;
440 default:
441 break;
442 }
John Kessenich92187592016-02-01 13:45:25 -0700443 }
444 return spv::BuiltInPointSize;
445
John Kessenichebb50532016-05-16 19:22:05 -0600446 // These *Distance capabilities logically belong here, but if the member is declared and
447 // then never used, consumers of SPIR-V prefer the capability not be declared.
448 // They are now generated when used, rather than here when declared.
449 // Potentially, the specification should be more clear what the minimum
450 // use needed is to trigger the capability.
451 //
John Kessenich92187592016-02-01 13:45:25 -0700452 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100453 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800454 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700455 return spv::BuiltInClipDistance;
456
457 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800459 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInCullDistance;
461
462 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600463 builder.addCapability(spv::CapabilityMultiViewport);
464 if (glslangIntermediate->getStage() == EShLangVertex ||
465 glslangIntermediate->getStage() == EShLangTessControl ||
466 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800467
John Kessenichba6a3c22017-09-13 13:22:50 -0600468 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
469 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800470 }
John Kessenich92187592016-02-01 13:45:25 -0700471 return spv::BuiltInViewportIndex;
472
John Kessenich5e801132016-02-15 11:09:46 -0700473 case glslang::EbvSampleId:
474 builder.addCapability(spv::CapabilitySampleRateShading);
475 return spv::BuiltInSampleId;
476
477 case glslang::EbvSamplePosition:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSamplePosition;
480
481 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700482 return spv::BuiltInSampleMask;
483
John Kessenich78a45572016-07-08 14:05:15 -0600484 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600485 builder.addCapability(spv::CapabilityGeometry);
486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800489
John Kessenichba6a3c22017-09-13 13:22:50 -0600490 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800492 }
John Kessenich78a45572016-07-08 14:05:15 -0600493 return spv::BuiltInLayer;
494
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvVertexId: return spv::BuiltInVertexId;
497 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700498 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
499 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800500
John Kessenichda581a22015-10-14 14:10:30 -0600501 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800502 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
503 builder.addCapability(spv::CapabilityDrawParameters);
504 return spv::BuiltInBaseVertex;
505
John Kessenichda581a22015-10-14 14:10:30 -0600506 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800507 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
508 builder.addCapability(spv::CapabilityDrawParameters);
509 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200510
John Kessenichda581a22015-10-14 14:10:30 -0600511 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800512 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
513 builder.addCapability(spv::CapabilityDrawParameters);
514 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200515
516 case glslang::EbvPrimitiveId:
517 if (glslangIntermediate->getStage() == EShLangFragment)
518 builder.addCapability(spv::CapabilityGeometry);
519 return spv::BuiltInPrimitiveId;
520
Rex Xu37cdcee2017-06-29 17:46:34 +0800521 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800522 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
523 builder.addCapability(spv::CapabilityStencilExportEXT);
524 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800525
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
528 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
529 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
530 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
531 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
532 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
533 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600534 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
535 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
536 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
537 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
538 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
539 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
540 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
541 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800542
Rex Xu574ab042016-04-14 16:53:07 +0800543 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800544 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800545 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
546 return spv::BuiltInSubgroupSize;
547
Rex Xu574ab042016-04-14 16:53:07 +0800548 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800549 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
551 return spv::BuiltInSubgroupLocalInvocationId;
552
Rex Xu574ab042016-04-14 16:53:07 +0800553 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800554 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
555 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
556 return spv::BuiltInSubgroupEqMaskKHR;
557
Rex Xu574ab042016-04-14 16:53:07 +0800558 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800559 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
560 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
561 return spv::BuiltInSubgroupGeMaskKHR;
562
Rex Xu574ab042016-04-14 16:53:07 +0800563 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800564 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
565 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
566 return spv::BuiltInSubgroupGtMaskKHR;
567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupLeMaskKHR;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLtMaskKHR;
577
Rex Xu9d93a232016-05-05 12:30:44 +0800578#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800579 case glslang::EbvBaryCoordNoPersp:
580 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
581 return spv::BuiltInBaryCoordNoPerspAMD;
582
583 case glslang::EbvBaryCoordNoPerspCentroid:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
586
587 case glslang::EbvBaryCoordNoPerspSample:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordNoPerspSampleAMD;
590
591 case glslang::EbvBaryCoordSmooth:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordSmoothAMD;
594
595 case glslang::EbvBaryCoordSmoothCentroid:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothCentroidAMD;
598
599 case glslang::EbvBaryCoordSmoothSample:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordSmoothSampleAMD;
602
603 case glslang::EbvBaryCoordPullModel:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800606#endif
chaoc771d89f2017-01-13 01:10:53 -0800607
John Kessenich6c8aaac2017-02-27 01:20:51 -0700608 case glslang::EbvDeviceIndex:
609 builder.addExtension(spv::E_SPV_KHR_device_group);
610 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700611 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700612
613 case glslang::EbvViewIndex:
614 builder.addExtension(spv::E_SPV_KHR_multiview);
615 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700616 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700617
chaoc771d89f2017-01-13 01:10:53 -0800618#ifdef NV_EXTENSIONS
619 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800620 if (!memberDeclaration) {
621 builder.addExtension(spv::E_SPV_NV_viewport_array2);
622 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
623 }
chaoc771d89f2017-01-13 01:10:53 -0800624 return spv::BuiltInViewportMaskNV;
625 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800626 if (!memberDeclaration) {
627 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
628 builder.addCapability(spv::CapabilityShaderStereoViewNV);
629 }
chaoc771d89f2017-01-13 01:10:53 -0800630 return spv::BuiltInSecondaryPositionNV;
631 case glslang::EbvSecondaryViewportMaskNV:
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::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800637 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800638 if (!memberDeclaration) {
639 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
640 builder.addCapability(spv::CapabilityPerViewAttributesNV);
641 }
chaocdf3956c2017-02-14 14:52:34 -0800642 return spv::BuiltInPositionPerViewNV;
643 case glslang::EbvViewportMaskPerViewNV:
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::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800649#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800650 default:
651 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600652 }
653}
654
Rex Xufc618912015-09-09 16:42:49 +0800655// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700656spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800657{
658 assert(type.getBasicType() == glslang::EbtSampler);
659
John Kessenich5d0fa972016-02-15 11:57:00 -0700660 // Check for capabilities
661 switch (type.getQualifier().layoutFormat) {
662 case glslang::ElfRg32f:
663 case glslang::ElfRg16f:
664 case glslang::ElfR11fG11fB10f:
665 case glslang::ElfR16f:
666 case glslang::ElfRgba16:
667 case glslang::ElfRgb10A2:
668 case glslang::ElfRg16:
669 case glslang::ElfRg8:
670 case glslang::ElfR16:
671 case glslang::ElfR8:
672 case glslang::ElfRgba16Snorm:
673 case glslang::ElfRg16Snorm:
674 case glslang::ElfRg8Snorm:
675 case glslang::ElfR16Snorm:
676 case glslang::ElfR8Snorm:
677
678 case glslang::ElfRg32i:
679 case glslang::ElfRg16i:
680 case glslang::ElfRg8i:
681 case glslang::ElfR16i:
682 case glslang::ElfR8i:
683
684 case glslang::ElfRgb10a2ui:
685 case glslang::ElfRg32ui:
686 case glslang::ElfRg16ui:
687 case glslang::ElfRg8ui:
688 case glslang::ElfR16ui:
689 case glslang::ElfR8ui:
690 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
691 break;
692
693 default:
694 break;
695 }
696
697 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800698 switch (type.getQualifier().layoutFormat) {
699 case glslang::ElfNone: return spv::ImageFormatUnknown;
700 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
701 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
702 case glslang::ElfR32f: return spv::ImageFormatR32f;
703 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
704 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
705 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
706 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
707 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
708 case glslang::ElfR16f: return spv::ImageFormatR16f;
709 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
710 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
711 case glslang::ElfRg16: return spv::ImageFormatRg16;
712 case glslang::ElfRg8: return spv::ImageFormatRg8;
713 case glslang::ElfR16: return spv::ImageFormatR16;
714 case glslang::ElfR8: return spv::ImageFormatR8;
715 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
716 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
717 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
718 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
719 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
720 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
721 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
722 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
723 case glslang::ElfR32i: return spv::ImageFormatR32i;
724 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
725 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
726 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
727 case glslang::ElfR16i: return spv::ImageFormatR16i;
728 case glslang::ElfR8i: return spv::ImageFormatR8i;
729 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
730 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
731 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
732 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
733 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
734 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
735 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
736 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
737 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
738 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600739 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800740 }
741}
742
Rex Xu57e65922017-07-04 23:23:40 +0800743spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
744{
745 switch (selectionControl) {
746 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
747 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
748 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
749 default: return spv::SelectionControlMaskNone;
750 }
751}
752
steve-lunargf1709e72017-05-02 20:14:50 -0600753spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
754{
755 switch (loopControl) {
756 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
757 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
758 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
759 // TODO: DependencyInfinite
760 // TODO: DependencyLength
761 default: return spv::LoopControlMaskNone;
762 }
763}
764
John Kessenicha5c5fb62017-05-05 05:09:58 -0600765// Translate glslang type to SPIR-V storage class.
766spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
767{
768 if (type.getQualifier().isPipeInput())
769 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600770 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600771 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600772
773 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
774 type.getQualifier().storage == glslang::EvqUniform) {
775 if (type.getBasicType() == glslang::EbtAtomicUint)
776 return spv::StorageClassAtomicCounter;
777 if (type.containsOpaque())
778 return spv::StorageClassUniformConstant;
779 }
780
781 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600782 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
783 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600784 }
785
786 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600787 if (type.getQualifier().layoutPushConstant)
788 return spv::StorageClassPushConstant;
789 if (type.getBasicType() == glslang::EbtBlock)
790 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600791 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600792 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600793
794 switch (type.getQualifier().storage) {
795 case glslang::EvqShared: return spv::StorageClassWorkgroup;
796 case glslang::EvqGlobal: return spv::StorageClassPrivate;
797 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
798 case glslang::EvqTemporary: return spv::StorageClassFunction;
799 default:
800 assert(0);
801 break;
802 }
803
804 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600805}
806
qining25262b32016-05-06 17:25:16 -0400807// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700808// descriptor set.
809bool IsDescriptorResource(const glslang::TType& type)
810{
John Kessenichf7497e22016-03-08 21:36:22 -0700811 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700812 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700813 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700814
815 // non block...
816 // basically samplerXXX/subpass/sampler/texture are all included
817 // if they are the global-scope-class, not the function parameter
818 // (or local, if they ever exist) class.
819 if (type.getBasicType() == glslang::EbtSampler)
820 return type.getQualifier().isUniformOrBuffer();
821
822 // None of the above.
823 return false;
824}
825
John Kesseniche0b6cad2015-12-24 10:30:13 -0700826void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
827{
828 if (child.layoutMatrix == glslang::ElmNone)
829 child.layoutMatrix = parent.layoutMatrix;
830
831 if (parent.invariant)
832 child.invariant = true;
833 if (parent.nopersp)
834 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800835#ifdef AMD_EXTENSIONS
836 if (parent.explicitInterp)
837 child.explicitInterp = true;
838#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700839 if (parent.flat)
840 child.flat = true;
841 if (parent.centroid)
842 child.centroid = true;
843 if (parent.patch)
844 child.patch = true;
845 if (parent.sample)
846 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800847 if (parent.coherent)
848 child.coherent = true;
849 if (parent.volatil)
850 child.volatil = true;
851 if (parent.restrict)
852 child.restrict = true;
853 if (parent.readonly)
854 child.readonly = true;
855 if (parent.writeonly)
856 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700857}
858
John Kessenichf2b7f332016-09-01 17:05:23 -0600859bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700860{
John Kessenich7b9fa252016-01-21 18:56:57 -0700861 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600862 // - struct members might inherit from a struct declaration
863 // (note that non-block structs don't explicitly inherit,
864 // only implicitly, meaning no decoration involved)
865 // - affect decorations on the struct members
866 // (note smooth does not, and expecting something like volatile
867 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700868 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600869 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700870}
871
John Kessenich140f3df2015-06-26 16:58:36 -0600872//
873// Implement the TGlslangToSpvTraverser class.
874//
875
John Kessenich121853f2017-05-31 17:11:16 -0600876TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
877 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
878 : TIntermTraverser(true, false, true),
879 options(options),
880 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600881 sequenceDepth(0), logger(buildLogger),
John Kessenicha372a3e2017-11-02 22:32:14 -0600882 builder((glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700883 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600884 glslangIntermediate(glslangIntermediate)
885{
886 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
887
888 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600889 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
890 glslangIntermediate->getVersion());
891
John Kessenich121853f2017-05-31 17:11:16 -0600892 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600893 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600894 builder.setSourceFile(glslangIntermediate->getSourceFile());
895
896 // Set the source shader's text. If for SPV version 1.0, include
897 // a preamble in comments stating the OpModuleProcessed instructions.
898 // Otherwise, emit those as actual instructions.
899 std::string text;
900 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
901 for (int p = 0; p < (int)processes.size(); ++p) {
902 if (glslangIntermediate->getSpv().spv < 0x00010100) {
903 text.append("// OpModuleProcessed ");
904 text.append(processes[p]);
905 text.append("\n");
906 } else
907 builder.addModuleProcessed(processes[p]);
908 }
909 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
910 text.append("#line 1\n");
911 text.append(glslangIntermediate->getSourceText());
912 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600913 }
John Kessenich140f3df2015-06-26 16:58:36 -0600914 stdBuiltins = builder.import("GLSL.std.450");
915 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600916 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
917 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600918
919 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600920 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
921 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600922 builder.addSourceExtension(it->c_str());
923
924 // Add the top-level modes for this shader.
925
John Kessenich92187592016-02-01 13:45:25 -0700926 if (glslangIntermediate->getXfbMode()) {
927 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600928 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700929 }
John Kessenich140f3df2015-06-26 16:58:36 -0600930
931 unsigned int mode;
932 switch (glslangIntermediate->getStage()) {
933 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600934 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600935 break;
936
steve-lunarge7412492017-03-23 11:56:07 -0600937 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600938 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600939 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600940
steve-lunarge7412492017-03-23 11:56:07 -0600941 glslang::TLayoutGeometry primitive;
942
943 if (glslangIntermediate->getStage() == EShLangTessControl) {
944 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
945 primitive = glslangIntermediate->getOutputPrimitive();
946 } else {
947 primitive = glslangIntermediate->getInputPrimitive();
948 }
949
950 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700951 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
952 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
953 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600954 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600955 }
John Kessenich4016e382016-07-15 11:53:56 -0600956 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600957 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
958
John Kesseniche6903322015-10-13 16:29:02 -0600959 switch (glslangIntermediate->getVertexSpacing()) {
960 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
961 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
962 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600963 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600964 }
John Kessenich4016e382016-07-15 11:53:56 -0600965 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600966 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
967
968 switch (glslangIntermediate->getVertexOrder()) {
969 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
970 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600971 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600972 }
John Kessenich4016e382016-07-15 11:53:56 -0600973 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600974 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
975
976 if (glslangIntermediate->getPointMode())
977 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600978 break;
979
980 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600981 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600982 switch (glslangIntermediate->getInputPrimitive()) {
983 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
984 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
985 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700986 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600987 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600988 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600989 }
John Kessenich4016e382016-07-15 11:53:56 -0600990 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600991 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600992
John Kessenich140f3df2015-06-26 16:58:36 -0600993 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
994
995 switch (glslangIntermediate->getOutputPrimitive()) {
996 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
997 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
998 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600999 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001000 }
John Kessenich4016e382016-07-15 11:53:56 -06001001 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001002 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1003 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1004 break;
1005
1006 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001007 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001008 if (glslangIntermediate->getPixelCenterInteger())
1009 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001010
John Kessenich140f3df2015-06-26 16:58:36 -06001011 if (glslangIntermediate->getOriginUpperLeft())
1012 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001013 else
1014 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001015
1016 if (glslangIntermediate->getEarlyFragmentTests())
1017 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1018
chaocc1204522017-06-30 17:14:30 -07001019 if (glslangIntermediate->getPostDepthCoverage()) {
1020 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1021 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1022 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1023 }
1024
John Kesseniche6903322015-10-13 16:29:02 -06001025 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001026 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1027 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001028 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001029 }
John Kessenich4016e382016-07-15 11:53:56 -06001030 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001031 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1032
1033 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1034 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001035 break;
1036
1037 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001038 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001039 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1040 glslangIntermediate->getLocalSize(1),
1041 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001042 break;
1043
1044 default:
1045 break;
1046 }
John Kessenich140f3df2015-06-26 16:58:36 -06001047}
1048
John Kessenichfca82622016-11-26 13:23:20 -07001049// Finish creating SPV, after the traversal is complete.
1050void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001051{
John Kessenich517fe7a2016-11-26 13:31:47 -07001052 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001053 builder.setBuildPoint(shaderEntry->getLastBlock());
1054 builder.leaveFunction();
1055 }
1056
John Kessenich7ba63412015-12-20 17:37:07 -07001057 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001058 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1059 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001060
qiningda397332016-03-09 19:54:03 -05001061 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001062}
1063
John Kessenichfca82622016-11-26 13:23:20 -07001064// Write the SPV into 'out'.
1065void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001066{
John Kessenichfca82622016-11-26 13:23:20 -07001067 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001068}
1069
1070//
1071// Implement the traversal functions.
1072//
1073// Return true from interior nodes to have the external traversal
1074// continue on to children. Return false if children were
1075// already processed.
1076//
1077
1078//
qining25262b32016-05-06 17:25:16 -04001079// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001080// - uniform/input reads
1081// - output writes
1082// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1083// - something simple that degenerates into the last bullet
1084//
1085void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1086{
qining75d1d802016-04-06 14:42:01 -04001087 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1088 if (symbol->getType().getQualifier().isSpecConstant())
1089 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1090
John Kessenich140f3df2015-06-26 16:58:36 -06001091 // getSymbolId() will set up all the IO decorations on the first call.
1092 // Formal function parameters were mapped during makeFunctions().
1093 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001094
1095 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1096 if (builder.isPointer(id)) {
1097 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001098 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1099 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1100 iOSet.insert(id);
1101 }
John Kessenich7ba63412015-12-20 17:37:07 -07001102 }
1103
1104 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001105 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001106 // Prepare to generate code for the access
1107
1108 // L-value chains will be computed left to right. We're on the symbol now,
1109 // which is the left-most part of the access chain, so now is "clear" time,
1110 // followed by setting the base.
1111 builder.clearAccessChain();
1112
1113 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001114 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001115 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001116 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001117 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001118 // These are also pure R-values.
1119 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001120 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001121 builder.setAccessChainRValue(id);
1122 else
1123 builder.setAccessChainLValue(id);
1124 }
1125}
1126
1127bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1128{
John Kesseniche485c7a2017-05-31 18:50:53 -06001129 builder.setLine(node->getLoc().line);
1130
qining40887662016-04-03 22:20:42 -04001131 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1132 if (node->getType().getQualifier().isSpecConstant())
1133 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1134
John Kessenich140f3df2015-06-26 16:58:36 -06001135 // First, handle special cases
1136 switch (node->getOp()) {
1137 case glslang::EOpAssign:
1138 case glslang::EOpAddAssign:
1139 case glslang::EOpSubAssign:
1140 case glslang::EOpMulAssign:
1141 case glslang::EOpVectorTimesMatrixAssign:
1142 case glslang::EOpVectorTimesScalarAssign:
1143 case glslang::EOpMatrixTimesScalarAssign:
1144 case glslang::EOpMatrixTimesMatrixAssign:
1145 case glslang::EOpDivAssign:
1146 case glslang::EOpModAssign:
1147 case glslang::EOpAndAssign:
1148 case glslang::EOpInclusiveOrAssign:
1149 case glslang::EOpExclusiveOrAssign:
1150 case glslang::EOpLeftShiftAssign:
1151 case glslang::EOpRightShiftAssign:
1152 // A bin-op assign "a += b" means the same thing as "a = a + b"
1153 // where a is evaluated before b. For a simple assignment, GLSL
1154 // says to evaluate the left before the right. So, always, left
1155 // node then right node.
1156 {
1157 // get the left l-value, save it away
1158 builder.clearAccessChain();
1159 node->getLeft()->traverse(this);
1160 spv::Builder::AccessChain lValue = builder.getAccessChain();
1161
1162 // evaluate the right
1163 builder.clearAccessChain();
1164 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001165 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001166
1167 if (node->getOp() != glslang::EOpAssign) {
1168 // the left is also an r-value
1169 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001170 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001171
1172 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001173 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001174 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001175 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1176 node->getType().getBasicType());
1177
1178 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001179 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001180 }
1181
1182 // store the result
1183 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001184 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001185
1186 // assignments are expressions having an rValue after they are evaluated...
1187 builder.clearAccessChain();
1188 builder.setAccessChainRValue(rValue);
1189 }
1190 return false;
1191 case glslang::EOpIndexDirect:
1192 case glslang::EOpIndexDirectStruct:
1193 {
1194 // Get the left part of the access chain.
1195 node->getLeft()->traverse(this);
1196
1197 // Add the next element in the chain
1198
David Netoa901ffe2016-06-08 14:11:40 +01001199 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001200 if (! node->getLeft()->getType().isArray() &&
1201 node->getLeft()->getType().isVector() &&
1202 node->getOp() == glslang::EOpIndexDirect) {
1203 // This is essentially a hard-coded vector swizzle of size 1,
1204 // so short circuit the access-chain stuff with a swizzle.
1205 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001206 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001207 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001208 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001209 int spvIndex = glslangIndex;
1210 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1211 node->getOp() == glslang::EOpIndexDirectStruct)
1212 {
1213 // This may be, e.g., an anonymous block-member selection, which generally need
1214 // index remapping due to hidden members in anonymous blocks.
1215 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1216 assert(remapper.size() > 0);
1217 spvIndex = remapper[glslangIndex];
1218 }
John Kessenichebb50532016-05-16 19:22:05 -06001219
David Netoa901ffe2016-06-08 14:11:40 +01001220 // normal case for indexing array or structure or block
1221 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1222
1223 // Add capabilities here for accessing PointSize and clip/cull distance.
1224 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001225 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001226 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001227 }
1228 }
1229 return false;
1230 case glslang::EOpIndexIndirect:
1231 {
1232 // Structure or array or vector indirection.
1233 // Will use native SPIR-V access-chain for struct and array indirection;
1234 // matrices are arrays of vectors, so will also work for a matrix.
1235 // Will use the access chain's 'component' for variable index into a vector.
1236
1237 // This adapter is building access chains left to right.
1238 // Set up the access chain to the left.
1239 node->getLeft()->traverse(this);
1240
1241 // save it so that computing the right side doesn't trash it
1242 spv::Builder::AccessChain partial = builder.getAccessChain();
1243
1244 // compute the next index in the chain
1245 builder.clearAccessChain();
1246 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001247 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001248
1249 // restore the saved access chain
1250 builder.setAccessChain(partial);
1251
1252 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001253 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001254 else
John Kessenichfa668da2015-09-13 14:46:30 -06001255 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001256 }
1257 return false;
1258 case glslang::EOpVectorSwizzle:
1259 {
1260 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001262 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001263 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001264 }
1265 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001266 case glslang::EOpMatrixSwizzle:
1267 logger->missingFunctionality("matrix swizzle");
1268 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001269 case glslang::EOpLogicalOr:
1270 case glslang::EOpLogicalAnd:
1271 {
1272
1273 // These may require short circuiting, but can sometimes be done as straight
1274 // binary operations. The right operand must be short circuited if it has
1275 // side effects, and should probably be if it is complex.
1276 if (isTrivial(node->getRight()->getAsTyped()))
1277 break; // handle below as a normal binary operation
1278 // otherwise, we need to do dynamic short circuiting on the right operand
1279 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1280 builder.clearAccessChain();
1281 builder.setAccessChainRValue(result);
1282 }
1283 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001284 default:
1285 break;
1286 }
1287
1288 // Assume generic binary op...
1289
John Kessenich32cfd492016-02-02 12:37:46 -07001290 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001291 builder.clearAccessChain();
1292 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001293 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001294
John Kessenich32cfd492016-02-02 12:37:46 -07001295 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001296 builder.clearAccessChain();
1297 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001298 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
John Kessenich32cfd492016-02-02 12:37:46 -07001300 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001301 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001302 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001303 convertGlslangToSpvType(node->getType()), left, right,
1304 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001305
John Kessenich50e57562015-12-21 21:21:11 -07001306 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001307 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001308 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001309 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001310 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001311 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001312 return false;
1313 }
John Kessenich140f3df2015-06-26 16:58:36 -06001314}
1315
1316bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1317{
John Kesseniche485c7a2017-05-31 18:50:53 -06001318 builder.setLine(node->getLoc().line);
1319
qining40887662016-04-03 22:20:42 -04001320 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1321 if (node->getType().getQualifier().isSpecConstant())
1322 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1323
John Kessenichfc51d282015-08-19 13:34:18 -06001324 spv::Id result = spv::NoResult;
1325
1326 // try texturing first
1327 result = createImageTextureFunctionCall(node);
1328 if (result != spv::NoResult) {
1329 builder.clearAccessChain();
1330 builder.setAccessChainRValue(result);
1331
1332 return false; // done with this node
1333 }
1334
1335 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001336
1337 if (node->getOp() == glslang::EOpArrayLength) {
1338 // Quite special; won't want to evaluate the operand.
1339
1340 // Normal .length() would have been constant folded by the front-end.
1341 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001342 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001343 assert(node->getOperand()->getType().isRuntimeSizedArray());
1344 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1345 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001346 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1347 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001348
1349 builder.clearAccessChain();
1350 builder.setAccessChainRValue(length);
1351
1352 return false;
1353 }
1354
John Kessenichfc51d282015-08-19 13:34:18 -06001355 // Start by evaluating the operand
1356
John Kessenich8c8505c2016-07-26 12:50:38 -06001357 // Does it need a swizzle inversion? If so, evaluation is inverted;
1358 // operate first on the swizzle base, then apply the swizzle.
1359 spv::Id invertedType = spv::NoType;
1360 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1361 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1362 invertedType = getInvertedSwizzleType(*node->getOperand());
1363
John Kessenich140f3df2015-06-26 16:58:36 -06001364 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001365 if (invertedType != spv::NoType)
1366 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1367 else
1368 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001369
Rex Xufc618912015-09-09 16:42:49 +08001370 spv::Id operand = spv::NoResult;
1371
1372 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1373 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001374 node->getOp() == glslang::EOpAtomicCounter ||
1375 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001376 operand = builder.accessChainGetLValue(); // Special case l-value operands
1377 else
John Kessenich32cfd492016-02-02 12:37:46 -07001378 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001379
John Kessenichf6640762016-08-01 19:44:00 -06001380 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001381 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001384 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001385 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 // if not, then possibly an operation
1388 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001389 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001392 if (invertedType)
1393 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1394
John Kessenich140f3df2015-06-26 16:58:36 -06001395 builder.clearAccessChain();
1396 builder.setAccessChainRValue(result);
1397
1398 return false; // done with this node
1399 }
1400
1401 // it must be a special case, check...
1402 switch (node->getOp()) {
1403 case glslang::EOpPostIncrement:
1404 case glslang::EOpPostDecrement:
1405 case glslang::EOpPreIncrement:
1406 case glslang::EOpPreDecrement:
1407 {
1408 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001409 spv::Id one = 0;
1410 if (node->getBasicType() == glslang::EbtFloat)
1411 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001412 else if (node->getBasicType() == glslang::EbtDouble)
1413 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001414#ifdef AMD_EXTENSIONS
1415 else if (node->getBasicType() == glslang::EbtFloat16)
1416 one = builder.makeFloat16Constant(1.0F);
1417#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001418 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1419 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001420#ifdef AMD_EXTENSIONS
1421 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1422 one = builder.makeInt16Constant(1);
1423#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001424 else
1425 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001426 glslang::TOperator op;
1427 if (node->getOp() == glslang::EOpPreIncrement ||
1428 node->getOp() == glslang::EOpPostIncrement)
1429 op = glslang::EOpAdd;
1430 else
1431 op = glslang::EOpSub;
1432
John Kessenichf6640762016-08-01 19:44:00 -06001433 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001434 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001435 convertGlslangToSpvType(node->getType()), operand, one,
1436 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001437 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // The result of operation is always stored, but conditionally the
1440 // consumed result. The consumed result is always an r-value.
1441 builder.accessChainStore(result);
1442 builder.clearAccessChain();
1443 if (node->getOp() == glslang::EOpPreIncrement ||
1444 node->getOp() == glslang::EOpPreDecrement)
1445 builder.setAccessChainRValue(result);
1446 else
1447 builder.setAccessChainRValue(operand);
1448 }
1449
1450 return false;
1451
1452 case glslang::EOpEmitStreamVertex:
1453 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1454 return false;
1455 case glslang::EOpEndStreamPrimitive:
1456 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1457 return false;
1458
1459 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001460 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001461 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001462 }
John Kessenich140f3df2015-06-26 16:58:36 -06001463}
1464
1465bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1466{
qining27e04a02016-04-14 16:40:20 -04001467 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1468 if (node->getType().getQualifier().isSpecConstant())
1469 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1470
John Kessenichfc51d282015-08-19 13:34:18 -06001471 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001472 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1473 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001474
1475 // try texturing
1476 result = createImageTextureFunctionCall(node);
1477 if (result != spv::NoResult) {
1478 builder.clearAccessChain();
1479 builder.setAccessChainRValue(result);
1480
1481 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001482#ifdef AMD_EXTENSIONS
1483 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1484#else
John Kessenich56bab042015-09-16 10:54:31 -06001485 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001486#endif
Rex Xufc618912015-09-09 16:42:49 +08001487 // "imageStore" is a special case, which has no result
1488 return false;
1489 }
John Kessenichfc51d282015-08-19 13:34:18 -06001490
John Kessenich140f3df2015-06-26 16:58:36 -06001491 glslang::TOperator binOp = glslang::EOpNull;
1492 bool reduceComparison = true;
1493 bool isMatrix = false;
1494 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001495 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001496
1497 assert(node->getOp());
1498
John Kessenichf6640762016-08-01 19:44:00 -06001499 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001500
1501 switch (node->getOp()) {
1502 case glslang::EOpSequence:
1503 {
1504 if (preVisit)
1505 ++sequenceDepth;
1506 else
1507 --sequenceDepth;
1508
1509 if (sequenceDepth == 1) {
1510 // If this is the parent node of all the functions, we want to see them
1511 // early, so all call points have actual SPIR-V functions to reference.
1512 // In all cases, still let the traverser visit the children for us.
1513 makeFunctions(node->getAsAggregate()->getSequence());
1514
John Kessenich6fccb3c2016-09-19 16:01:41 -06001515 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001516 // anything else gets there, so visit out of order, doing them all now.
1517 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1518
John Kessenich6a60c2f2016-12-08 21:01:59 -07001519 // 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 -06001520 // so do them manually.
1521 visitFunctions(node->getAsAggregate()->getSequence());
1522
1523 return false;
1524 }
1525
1526 return true;
1527 }
1528 case glslang::EOpLinkerObjects:
1529 {
1530 if (visit == glslang::EvPreVisit)
1531 linkageOnly = true;
1532 else
1533 linkageOnly = false;
1534
1535 return true;
1536 }
1537 case glslang::EOpComma:
1538 {
1539 // processing from left to right naturally leaves the right-most
1540 // lying around in the access chain
1541 glslang::TIntermSequence& glslangOperands = node->getSequence();
1542 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1543 glslangOperands[i]->traverse(this);
1544
1545 return false;
1546 }
1547 case glslang::EOpFunction:
1548 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001549 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001550 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001551 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001552 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001553 } else {
1554 handleFunctionEntry(node);
1555 }
1556 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001557 if (inEntryPoint)
1558 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001559 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001560 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001561 }
1562
1563 return true;
1564 case glslang::EOpParameters:
1565 // Parameters will have been consumed by EOpFunction processing, but not
1566 // the body, so we still visited the function node's children, making this
1567 // child redundant.
1568 return false;
1569 case glslang::EOpFunctionCall:
1570 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001571 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001572 if (node->isUserDefined())
1573 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001574 // 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 -07001575 if (result) {
1576 builder.clearAccessChain();
1577 builder.setAccessChainRValue(result);
1578 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001579 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001580
1581 return false;
1582 }
1583 case glslang::EOpConstructMat2x2:
1584 case glslang::EOpConstructMat2x3:
1585 case glslang::EOpConstructMat2x4:
1586 case glslang::EOpConstructMat3x2:
1587 case glslang::EOpConstructMat3x3:
1588 case glslang::EOpConstructMat3x4:
1589 case glslang::EOpConstructMat4x2:
1590 case glslang::EOpConstructMat4x3:
1591 case glslang::EOpConstructMat4x4:
1592 case glslang::EOpConstructDMat2x2:
1593 case glslang::EOpConstructDMat2x3:
1594 case glslang::EOpConstructDMat2x4:
1595 case glslang::EOpConstructDMat3x2:
1596 case glslang::EOpConstructDMat3x3:
1597 case glslang::EOpConstructDMat3x4:
1598 case glslang::EOpConstructDMat4x2:
1599 case glslang::EOpConstructDMat4x3:
1600 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001601 case glslang::EOpConstructIMat2x2:
1602 case glslang::EOpConstructIMat2x3:
1603 case glslang::EOpConstructIMat2x4:
1604 case glslang::EOpConstructIMat3x2:
1605 case glslang::EOpConstructIMat3x3:
1606 case glslang::EOpConstructIMat3x4:
1607 case glslang::EOpConstructIMat4x2:
1608 case glslang::EOpConstructIMat4x3:
1609 case glslang::EOpConstructIMat4x4:
1610 case glslang::EOpConstructUMat2x2:
1611 case glslang::EOpConstructUMat2x3:
1612 case glslang::EOpConstructUMat2x4:
1613 case glslang::EOpConstructUMat3x2:
1614 case glslang::EOpConstructUMat3x3:
1615 case glslang::EOpConstructUMat3x4:
1616 case glslang::EOpConstructUMat4x2:
1617 case glslang::EOpConstructUMat4x3:
1618 case glslang::EOpConstructUMat4x4:
1619 case glslang::EOpConstructBMat2x2:
1620 case glslang::EOpConstructBMat2x3:
1621 case glslang::EOpConstructBMat2x4:
1622 case glslang::EOpConstructBMat3x2:
1623 case glslang::EOpConstructBMat3x3:
1624 case glslang::EOpConstructBMat3x4:
1625 case glslang::EOpConstructBMat4x2:
1626 case glslang::EOpConstructBMat4x3:
1627 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001628#ifdef AMD_EXTENSIONS
1629 case glslang::EOpConstructF16Mat2x2:
1630 case glslang::EOpConstructF16Mat2x3:
1631 case glslang::EOpConstructF16Mat2x4:
1632 case glslang::EOpConstructF16Mat3x2:
1633 case glslang::EOpConstructF16Mat3x3:
1634 case glslang::EOpConstructF16Mat3x4:
1635 case glslang::EOpConstructF16Mat4x2:
1636 case glslang::EOpConstructF16Mat4x3:
1637 case glslang::EOpConstructF16Mat4x4:
1638#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001639 isMatrix = true;
1640 // fall through
1641 case glslang::EOpConstructFloat:
1642 case glslang::EOpConstructVec2:
1643 case glslang::EOpConstructVec3:
1644 case glslang::EOpConstructVec4:
1645 case glslang::EOpConstructDouble:
1646 case glslang::EOpConstructDVec2:
1647 case glslang::EOpConstructDVec3:
1648 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001649#ifdef AMD_EXTENSIONS
1650 case glslang::EOpConstructFloat16:
1651 case glslang::EOpConstructF16Vec2:
1652 case glslang::EOpConstructF16Vec3:
1653 case glslang::EOpConstructF16Vec4:
1654#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001655 case glslang::EOpConstructBool:
1656 case glslang::EOpConstructBVec2:
1657 case glslang::EOpConstructBVec3:
1658 case glslang::EOpConstructBVec4:
1659 case glslang::EOpConstructInt:
1660 case glslang::EOpConstructIVec2:
1661 case glslang::EOpConstructIVec3:
1662 case glslang::EOpConstructIVec4:
1663 case glslang::EOpConstructUint:
1664 case glslang::EOpConstructUVec2:
1665 case glslang::EOpConstructUVec3:
1666 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001667 case glslang::EOpConstructInt64:
1668 case glslang::EOpConstructI64Vec2:
1669 case glslang::EOpConstructI64Vec3:
1670 case glslang::EOpConstructI64Vec4:
1671 case glslang::EOpConstructUint64:
1672 case glslang::EOpConstructU64Vec2:
1673 case glslang::EOpConstructU64Vec3:
1674 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001675#ifdef AMD_EXTENSIONS
1676 case glslang::EOpConstructInt16:
1677 case glslang::EOpConstructI16Vec2:
1678 case glslang::EOpConstructI16Vec3:
1679 case glslang::EOpConstructI16Vec4:
1680 case glslang::EOpConstructUint16:
1681 case glslang::EOpConstructU16Vec2:
1682 case glslang::EOpConstructU16Vec3:
1683 case glslang::EOpConstructU16Vec4:
1684#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001685 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001686 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001687 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001688 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001689 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001690 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001691 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001692 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001693 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001694 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001695 std::vector<spv::Id> constituents;
1696 for (int c = 0; c < (int)arguments.size(); ++c)
1697 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001698 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001699 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001701 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001702 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001703
1704 builder.clearAccessChain();
1705 builder.setAccessChainRValue(constructed);
1706
1707 return false;
1708 }
1709
1710 // These six are component-wise compares with component-wise results.
1711 // Forward on to createBinaryOperation(), requesting a vector result.
1712 case glslang::EOpLessThan:
1713 case glslang::EOpGreaterThan:
1714 case glslang::EOpLessThanEqual:
1715 case glslang::EOpGreaterThanEqual:
1716 case glslang::EOpVectorEqual:
1717 case glslang::EOpVectorNotEqual:
1718 {
1719 // Map the operation to a binary
1720 binOp = node->getOp();
1721 reduceComparison = false;
1722 switch (node->getOp()) {
1723 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1724 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1725 default: binOp = node->getOp(); break;
1726 }
1727
1728 break;
1729 }
1730 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001731 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001732 binOp = glslang::EOpMul;
1733 break;
1734 case glslang::EOpOuterProduct:
1735 // two vectors multiplied to make a matrix
1736 binOp = glslang::EOpOuterProduct;
1737 break;
1738 case glslang::EOpDot:
1739 {
qining25262b32016-05-06 17:25:16 -04001740 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001741 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001742 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001743 binOp = glslang::EOpMul;
1744 break;
1745 }
1746 case glslang::EOpMod:
1747 // when an aggregate, this is the floating-point mod built-in function,
1748 // which can be emitted by the one in createBinaryOperation()
1749 binOp = glslang::EOpMod;
1750 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001751 case glslang::EOpEmitVertex:
1752 case glslang::EOpEndPrimitive:
1753 case glslang::EOpBarrier:
1754 case glslang::EOpMemoryBarrier:
1755 case glslang::EOpMemoryBarrierAtomicCounter:
1756 case glslang::EOpMemoryBarrierBuffer:
1757 case glslang::EOpMemoryBarrierImage:
1758 case glslang::EOpMemoryBarrierShared:
1759 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001760 case glslang::EOpAllMemoryBarrierWithGroupSync:
1761 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1762 case glslang::EOpWorkgroupMemoryBarrier:
1763 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001764 noReturnValue = true;
1765 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1766 break;
1767
John Kessenich426394d2015-07-23 10:22:48 -06001768 case glslang::EOpAtomicAdd:
1769 case glslang::EOpAtomicMin:
1770 case glslang::EOpAtomicMax:
1771 case glslang::EOpAtomicAnd:
1772 case glslang::EOpAtomicOr:
1773 case glslang::EOpAtomicXor:
1774 case glslang::EOpAtomicExchange:
1775 case glslang::EOpAtomicCompSwap:
1776 atomic = true;
1777 break;
1778
John Kessenich0d0c6d32017-07-23 16:08:26 -06001779 case glslang::EOpAtomicCounterAdd:
1780 case glslang::EOpAtomicCounterSubtract:
1781 case glslang::EOpAtomicCounterMin:
1782 case glslang::EOpAtomicCounterMax:
1783 case glslang::EOpAtomicCounterAnd:
1784 case glslang::EOpAtomicCounterOr:
1785 case glslang::EOpAtomicCounterXor:
1786 case glslang::EOpAtomicCounterExchange:
1787 case glslang::EOpAtomicCounterCompSwap:
1788 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1789 builder.addCapability(spv::CapabilityAtomicStorageOps);
1790 atomic = true;
1791 break;
1792
John Kessenich140f3df2015-06-26 16:58:36 -06001793 default:
1794 break;
1795 }
1796
1797 //
1798 // See if it maps to a regular operation.
1799 //
John Kessenich140f3df2015-06-26 16:58:36 -06001800 if (binOp != glslang::EOpNull) {
1801 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1802 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1803 assert(left && right);
1804
1805 builder.clearAccessChain();
1806 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001807 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001808
1809 builder.clearAccessChain();
1810 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001811 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001812
John Kesseniche485c7a2017-05-31 18:50:53 -06001813 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001814 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001815 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001816 left->getType().getBasicType(), reduceComparison);
1817
1818 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001819 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001820 builder.clearAccessChain();
1821 builder.setAccessChainRValue(result);
1822
1823 return false;
1824 }
1825
John Kessenich426394d2015-07-23 10:22:48 -06001826 //
1827 // Create the list of operands.
1828 //
John Kessenich140f3df2015-06-26 16:58:36 -06001829 glslang::TIntermSequence& glslangOperands = node->getSequence();
1830 std::vector<spv::Id> operands;
1831 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001832 // special case l-value operands; there are just a few
1833 bool lvalue = false;
1834 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001835 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001836 case glslang::EOpModf:
1837 if (arg == 1)
1838 lvalue = true;
1839 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001840 case glslang::EOpInterpolateAtSample:
1841 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001842#ifdef AMD_EXTENSIONS
1843 case glslang::EOpInterpolateAtVertex:
1844#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001845 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001846 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001847
1848 // Does it need a swizzle inversion? If so, evaluation is inverted;
1849 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001850 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001851 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1852 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1853 }
Rex Xu7a26c172015-12-08 17:12:09 +08001854 break;
Rex Xud4782c12015-09-06 16:30:11 +08001855 case glslang::EOpAtomicAdd:
1856 case glslang::EOpAtomicMin:
1857 case glslang::EOpAtomicMax:
1858 case glslang::EOpAtomicAnd:
1859 case glslang::EOpAtomicOr:
1860 case glslang::EOpAtomicXor:
1861 case glslang::EOpAtomicExchange:
1862 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001863 case glslang::EOpAtomicCounterAdd:
1864 case glslang::EOpAtomicCounterSubtract:
1865 case glslang::EOpAtomicCounterMin:
1866 case glslang::EOpAtomicCounterMax:
1867 case glslang::EOpAtomicCounterAnd:
1868 case glslang::EOpAtomicCounterOr:
1869 case glslang::EOpAtomicCounterXor:
1870 case glslang::EOpAtomicCounterExchange:
1871 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001872 if (arg == 0)
1873 lvalue = true;
1874 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001875 case glslang::EOpAddCarry:
1876 case glslang::EOpSubBorrow:
1877 if (arg == 2)
1878 lvalue = true;
1879 break;
1880 case glslang::EOpUMulExtended:
1881 case glslang::EOpIMulExtended:
1882 if (arg >= 2)
1883 lvalue = true;
1884 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001885 default:
1886 break;
1887 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001888 builder.clearAccessChain();
1889 if (invertedType != spv::NoType && arg == 0)
1890 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1891 else
1892 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001893 if (lvalue)
1894 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001895 else {
1896 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001897 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001898 }
John Kessenich140f3df2015-06-26 16:58:36 -06001899 }
John Kessenich426394d2015-07-23 10:22:48 -06001900
John Kesseniche485c7a2017-05-31 18:50:53 -06001901 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001902 if (atomic) {
1903 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001904 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001905 } else {
1906 // Pass through to generic operations.
1907 switch (glslangOperands.size()) {
1908 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001910 break;
1911 case 1:
qining25262b32016-05-06 17:25:16 -04001912 result = createUnaryOperation(
1913 node->getOp(), precision,
1914 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001915 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001916 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001917 break;
1918 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001919 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001920 break;
1921 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001922 if (invertedType)
1923 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001924 }
1925
1926 if (noReturnValue)
1927 return false;
1928
1929 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001930 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001931 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001932 } else {
1933 builder.clearAccessChain();
1934 builder.setAccessChainRValue(result);
1935 return false;
1936 }
1937}
1938
John Kessenich433e9ff2017-01-26 20:31:11 -07001939// This path handles both if-then-else and ?:
1940// The if-then-else has a node type of void, while
1941// ?: has either a void or a non-void node type
1942//
1943// Leaving the result, when not void:
1944// GLSL only has r-values as the result of a :?, but
1945// if we have an l-value, that can be more efficient if it will
1946// become the base of a complex r-value expression, because the
1947// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001948bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1949{
John Kessenich433e9ff2017-01-26 20:31:11 -07001950 // See if it simple and safe to generate OpSelect instead of using control flow.
1951 // Crucially, side effects must be avoided, and there are performance trade-offs.
1952 // Return true if good idea (and safe) for OpSelect, false otherwise.
1953 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001954 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1955 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001956 return false;
1957
1958 if (node->getTrueBlock() == nullptr ||
1959 node->getFalseBlock() == nullptr)
1960 return false;
1961
1962 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1963 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1964
1965 // return true if a single operand to ? : is okay for OpSelect
1966 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001967 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001968 };
1969
1970 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1971 operandOkay(node->getFalseBlock()->getAsTyped());
1972 };
1973
1974 // Emit OpSelect for this selection.
1975 const auto handleAsOpSelect = [&]() {
1976 node->getCondition()->traverse(this);
1977 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1978 node->getTrueBlock()->traverse(this);
1979 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1980 node->getFalseBlock()->traverse(this);
1981 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1982
John Kesseniche485c7a2017-05-31 18:50:53 -06001983 builder.setLine(node->getLoc().line);
1984
John Kesseniche434ad92017-03-30 10:09:28 -06001985 // smear condition to vector, if necessary (AST is always scalar)
1986 if (builder.isVector(trueValue))
1987 condition = builder.smearScalar(spv::NoPrecision, condition,
1988 builder.makeVectorType(builder.makeBoolType(),
1989 builder.getNumComponents(trueValue)));
1990
1991 spv::Id select = builder.createTriOp(spv::OpSelect,
1992 convertGlslangToSpvType(node->getType()), condition,
1993 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 builder.clearAccessChain();
1995 builder.setAccessChainRValue(select);
1996 };
1997
1998 // Try for OpSelect
1999
2000 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002001 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2002 if (node->getType().getQualifier().isSpecConstant())
2003 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2004
John Kessenich433e9ff2017-01-26 20:31:11 -07002005 handleAsOpSelect();
2006 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002007 }
2008
Rex Xu57e65922017-07-04 23:23:40 +08002009 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002010 // Don't handle results as temporaries, because there will be two names
2011 // and better to leave SSA to later passes.
2012 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2013 ? spv::NoResult
2014 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2015
John Kessenich140f3df2015-06-26 16:58:36 -06002016 // emit the condition before doing anything with selection
2017 node->getCondition()->traverse(this);
2018
Rex Xu57e65922017-07-04 23:23:40 +08002019 // Selection control:
2020 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2021
John Kessenich140f3df2015-06-26 16:58:36 -06002022 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002023 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002024
John Kessenich433e9ff2017-01-26 20:31:11 -07002025 // emit the "then" statement
2026 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002027 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002028 if (result != spv::NoResult)
2029 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002030 }
2031
John Kessenich433e9ff2017-01-26 20:31:11 -07002032 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002033 ifBuilder.makeBeginElse();
2034 // emit the "else" statement
2035 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002036 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002037 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002038 }
2039
John Kessenich433e9ff2017-01-26 20:31:11 -07002040 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002041 ifBuilder.makeEndIf();
2042
John Kessenich433e9ff2017-01-26 20:31:11 -07002043 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002044 // GLSL only has r-values as the result of a :?, but
2045 // if we have an l-value, that can be more efficient if it will
2046 // become the base of a complex r-value expression, because the
2047 // next layer copies r-values into memory to use the access-chain mechanism
2048 builder.clearAccessChain();
2049 builder.setAccessChainLValue(result);
2050 }
2051
2052 return false;
2053}
2054
2055bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2056{
2057 // emit and get the condition before doing anything with switch
2058 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002059 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002060
Rex Xu57e65922017-07-04 23:23:40 +08002061 // Selection control:
2062 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2063
John Kessenich140f3df2015-06-26 16:58:36 -06002064 // browse the children to sort out code segments
2065 int defaultSegment = -1;
2066 std::vector<TIntermNode*> codeSegments;
2067 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2068 std::vector<int> caseValues;
2069 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2070 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2071 TIntermNode* child = *c;
2072 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002073 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002074 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002075 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002076 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2077 } else
2078 codeSegments.push_back(child);
2079 }
2080
qining25262b32016-05-06 17:25:16 -04002081 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002082 // statements between the last case and the end of the switch statement
2083 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2084 (int)codeSegments.size() == defaultSegment)
2085 codeSegments.push_back(nullptr);
2086
2087 // make the switch statement
2088 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002089 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002090
2091 // emit all the code in the segments
2092 breakForLoop.push(false);
2093 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2094 builder.nextSwitchSegment(segmentBlocks, s);
2095 if (codeSegments[s])
2096 codeSegments[s]->traverse(this);
2097 else
2098 builder.addSwitchBreak();
2099 }
2100 breakForLoop.pop();
2101
2102 builder.endSwitch(segmentBlocks);
2103
2104 return false;
2105}
2106
2107void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2108{
2109 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002110 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002111
2112 builder.clearAccessChain();
2113 builder.setAccessChainRValue(constant);
2114}
2115
2116bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2117{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002118 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002119 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002120
2121 // Loop control:
2122 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2123
2124 // TODO: dependency length
2125
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002126 // Spec requires back edges to target header blocks, and every header block
2127 // must dominate its merge block. Make a header block first to ensure these
2128 // conditions are met. By definition, it will contain OpLoopMerge, followed
2129 // by a block-ending branch. But we don't want to put any other body/test
2130 // instructions in it, since the body/test may have arbitrary instructions,
2131 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002132 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002133 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002134 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002135 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002136 spv::Block& test = builder.makeNewBlock();
2137 builder.createBranch(&test);
2138
2139 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002140 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002141 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002142 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2143
2144 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002145 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002146 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002147 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002148 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002149 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002150
2151 builder.setBuildPoint(&blocks.continue_target);
2152 if (node->getTerminal())
2153 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002154 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002155 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002156 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002157 builder.createBranch(&blocks.body);
2158
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002159 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002160 builder.setBuildPoint(&blocks.body);
2161 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002162 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002163 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002164 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002165
2166 builder.setBuildPoint(&blocks.continue_target);
2167 if (node->getTerminal())
2168 node->getTerminal()->traverse(this);
2169 if (node->getTest()) {
2170 node->getTest()->traverse(this);
2171 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002172 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002173 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002174 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002175 // TODO: unless there was a break/return/discard instruction
2176 // somewhere in the body, this is an infinite loop, so we should
2177 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002178 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002179 }
John Kessenich140f3df2015-06-26 16:58:36 -06002180 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002181 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002182 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002183 return false;
2184}
2185
2186bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2187{
2188 if (node->getExpression())
2189 node->getExpression()->traverse(this);
2190
John Kesseniche485c7a2017-05-31 18:50:53 -06002191 builder.setLine(node->getLoc().line);
2192
John Kessenich140f3df2015-06-26 16:58:36 -06002193 switch (node->getFlowOp()) {
2194 case glslang::EOpKill:
2195 builder.makeDiscard();
2196 break;
2197 case glslang::EOpBreak:
2198 if (breakForLoop.top())
2199 builder.createLoopExit();
2200 else
2201 builder.addSwitchBreak();
2202 break;
2203 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002204 builder.createLoopContinue();
2205 break;
2206 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002207 if (node->getExpression()) {
2208 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2209 spv::Id returnId = accessChainLoad(glslangReturnType);
2210 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2211 builder.clearAccessChain();
2212 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2213 builder.setAccessChainLValue(copyId);
2214 multiTypeStore(glslangReturnType, returnId);
2215 returnId = builder.createLoad(copyId);
2216 }
2217 builder.makeReturn(false, returnId);
2218 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002219 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002220
2221 builder.clearAccessChain();
2222 break;
2223
2224 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002225 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002226 break;
2227 }
2228
2229 return false;
2230}
2231
2232spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2233{
qining25262b32016-05-06 17:25:16 -04002234 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002235 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002236 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002237 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002238 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002239 }
2240
2241 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002242 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002243 spv::Id spvType = convertGlslangToSpvType(node->getType());
2244
Rex Xuf89ad982017-04-07 23:22:33 +08002245#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002246 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2247 node->getType().containsBasicType(glslang::EbtInt16) ||
2248 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002249 if (contains16BitType) {
2250 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2251 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2252 builder.addCapability(spv::CapabilityStorageInputOutput16);
2253 } else if (storageClass == spv::StorageClassPushConstant) {
2254 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2255 builder.addCapability(spv::CapabilityStoragePushConstant16);
2256 } else if (storageClass == spv::StorageClassUniform) {
2257 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2258 builder.addCapability(spv::CapabilityStorageUniform16);
2259 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2260 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2261 }
2262 }
2263#endif
2264
John Kessenich140f3df2015-06-26 16:58:36 -06002265 const char* name = node->getName().c_str();
2266 if (glslang::IsAnonymous(name))
2267 name = "";
2268
2269 return builder.createVariable(storageClass, spvType, name);
2270}
2271
2272// Return type Id of the sampled type.
2273spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2274{
2275 switch (sampler.type) {
2276 case glslang::EbtFloat: return builder.makeFloatType(32);
2277 case glslang::EbtInt: return builder.makeIntType(32);
2278 case glslang::EbtUint: return builder.makeUintType(32);
2279 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002280 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002281 return builder.makeFloatType(32);
2282 }
2283}
2284
John Kessenich8c8505c2016-07-26 12:50:38 -06002285// If node is a swizzle operation, return the type that should be used if
2286// the swizzle base is first consumed by another operation, before the swizzle
2287// is applied.
2288spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2289{
John Kessenichecba76f2017-01-06 00:34:48 -07002290 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002291 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2292 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2293 else
2294 return spv::NoType;
2295}
2296
2297// When inverting a swizzle with a parent op, this function
2298// will apply the swizzle operation to a completed parent operation.
2299spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2300{
2301 std::vector<unsigned> swizzle;
2302 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2303 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2304}
2305
John Kessenich8c8505c2016-07-26 12:50:38 -06002306// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2307void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2308{
2309 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2310 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2311 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2312}
2313
John Kessenich3ac051e2015-12-20 11:29:16 -07002314// Convert from a glslang type to an SPV type, by calling into a
2315// recursive version of this function. This establishes the inherited
2316// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002317spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2318{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002319 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002320}
2321
2322// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002323// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002324// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002325spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002326{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002327 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002328
2329 switch (type.getBasicType()) {
2330 case glslang::EbtVoid:
2331 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002332 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002333 break;
2334 case glslang::EbtFloat:
2335 spvType = builder.makeFloatType(32);
2336 break;
2337 case glslang::EbtDouble:
2338 spvType = builder.makeFloatType(64);
2339 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002340#ifdef AMD_EXTENSIONS
2341 case glslang::EbtFloat16:
2342 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002343 spvType = builder.makeFloatType(16);
2344 break;
2345#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002346 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002347 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2348 // a 32-bit int where non-0 means true.
2349 if (explicitLayout != glslang::ElpNone)
2350 spvType = builder.makeUintType(32);
2351 else
2352 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002353 break;
2354 case glslang::EbtInt:
2355 spvType = builder.makeIntType(32);
2356 break;
2357 case glslang::EbtUint:
2358 spvType = builder.makeUintType(32);
2359 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002360 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002361 spvType = builder.makeIntType(64);
2362 break;
2363 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002364 spvType = builder.makeUintType(64);
2365 break;
Rex Xucabbb782017-03-24 13:41:14 +08002366#ifdef AMD_EXTENSIONS
2367 case glslang::EbtInt16:
2368 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2369 spvType = builder.makeIntType(16);
2370 break;
2371 case glslang::EbtUint16:
2372 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2373 spvType = builder.makeUintType(16);
2374 break;
2375#endif
John Kessenich426394d2015-07-23 10:22:48 -06002376 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002377 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002378 spvType = builder.makeUintType(32);
2379 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002380 case glslang::EbtSampler:
2381 {
2382 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002383 if (sampler.sampler) {
2384 // pure sampler
2385 spvType = builder.makeSamplerType();
2386 } else {
2387 // an image is present, make its type
2388 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2389 sampler.image ? 2 : 1, TranslateImageFormat(type));
2390 if (sampler.combined) {
2391 // already has both image and sampler, make the combined type
2392 spvType = builder.makeSampledImageType(spvType);
2393 }
John Kessenich55e7d112015-11-15 21:33:39 -07002394 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002395 }
John Kessenich140f3df2015-06-26 16:58:36 -06002396 break;
2397 case glslang::EbtStruct:
2398 case glslang::EbtBlock:
2399 {
2400 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002401 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002402
2403 // Try to share structs for different layouts, but not yet for other
2404 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002405 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002406 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002407 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002408 break;
2409
2410 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002411 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002412 memberRemapper[glslangMembers].resize(glslangMembers->size());
2413 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002414 }
2415 break;
2416 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002417 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002418 break;
2419 }
2420
2421 if (type.isMatrix())
2422 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2423 else {
2424 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2425 if (type.getVectorSize() > 1)
2426 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2427 }
2428
2429 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002430 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2431
John Kessenichc9a80832015-09-12 12:17:44 -06002432 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002433 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002434 // We need to decorate array strides for types needing explicit layout, except blocks.
2435 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002436 // Use a dummy glslang type for querying internal strides of
2437 // arrays of arrays, but using just a one-dimensional array.
2438 glslang::TType simpleArrayType(type, 0); // deference type of the array
2439 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2440 simpleArrayType.getArraySizes().dereference();
2441
2442 // Will compute the higher-order strides here, rather than making a whole
2443 // pile of types and doing repetitive recursion on their contents.
2444 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2445 }
John Kessenichf8842e52016-01-04 19:22:56 -07002446
2447 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002448 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002449 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002450 if (stride > 0)
2451 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002452 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002453 }
2454 } else {
2455 // single-dimensional array, and don't yet have stride
2456
John Kessenichf8842e52016-01-04 19:22:56 -07002457 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2459 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002460 }
John Kessenich31ed4832015-09-09 17:51:38 -06002461
John Kessenichc9a80832015-09-12 12:17:44 -06002462 // Do the outer dimension, which might not be known for a runtime-sized array
2463 if (type.isRuntimeSizedArray()) {
2464 spvType = builder.makeRuntimeArray(spvType);
2465 } else {
2466 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002467 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002468 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002469 if (stride > 0)
2470 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002471 }
2472
2473 return spvType;
2474}
2475
John Kessenich0e737842017-03-24 18:38:16 -06002476// TODO: this functionality should exist at a higher level, in creating the AST
2477//
2478// Identify interface members that don't have their required extension turned on.
2479//
2480bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2481{
2482 auto& extensions = glslangIntermediate->getRequestedExtensions();
2483
Rex Xubcf291a2017-03-29 23:01:36 +08002484 if (member.getFieldName() == "gl_ViewportMask" &&
2485 extensions.find("GL_NV_viewport_array2") == extensions.end())
2486 return true;
2487 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2488 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2489 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002490 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2491 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2492 return true;
2493 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2494 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2495 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002496 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2497 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2498 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002499
2500 return false;
2501};
2502
John Kessenich6090df02016-06-30 21:18:02 -06002503// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2504// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2505// Mutually recursive with convertGlslangToSpvType().
2506spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2507 const glslang::TTypeList* glslangMembers,
2508 glslang::TLayoutPacking explicitLayout,
2509 const glslang::TQualifier& qualifier)
2510{
2511 // Create a vector of struct types for SPIR-V to consume
2512 std::vector<spv::Id> spvMembers;
2513 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 -06002514 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2515 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2516 if (glslangMember.hiddenMember()) {
2517 ++memberDelta;
2518 if (type.getBasicType() == glslang::EbtBlock)
2519 memberRemapper[glslangMembers][i] = -1;
2520 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002521 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002522 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002523 if (filterMember(glslangMember))
2524 continue;
2525 }
John Kessenich6090df02016-06-30 21:18:02 -06002526 // modify just this child's view of the qualifier
2527 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2528 InheritQualifiers(memberQualifier, qualifier);
2529
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002530 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002531 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002532 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002533
2534 // recurse
2535 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2536 }
2537 }
2538
2539 // Make the SPIR-V type
2540 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002541 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002542 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2543
2544 // Decorate it
2545 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2546
2547 return spvType;
2548}
2549
2550void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2551 const glslang::TTypeList* glslangMembers,
2552 glslang::TLayoutPacking explicitLayout,
2553 const glslang::TQualifier& qualifier,
2554 spv::Id spvType)
2555{
2556 // Name and decorate the non-hidden members
2557 int offset = -1;
2558 int locationOffset = 0; // for use within the members of this struct
2559 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2560 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2561 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002562 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002563 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002564 if (filterMember(glslangMember))
2565 continue;
2566 }
John Kessenich6090df02016-06-30 21:18:02 -06002567
2568 // modify just this child's view of the qualifier
2569 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2570 InheritQualifiers(memberQualifier, qualifier);
2571
2572 // using -1 above to indicate a hidden member
2573 if (member >= 0) {
2574 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2575 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2576 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2577 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002578 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2579 type.getQualifier().storage == glslang::EvqVaryingOut) {
2580 if (type.getBasicType() == glslang::EbtBlock ||
2581 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002582 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2583 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2584 }
2585 }
2586 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2587
Rex Xu286ca432017-07-27 14:33:16 +08002588 if (type.getBasicType() == glslang::EbtBlock &&
2589 qualifier.storage == glslang::EvqBuffer) {
2590 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002591 std::vector<spv::Decoration> memory;
2592 TranslateMemoryDecoration(memberQualifier, memory);
2593 for (unsigned int i = 0; i < memory.size(); ++i)
2594 addMemberDecoration(spvType, member, memory[i]);
2595 }
2596
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002597 // Location assignment was already completed correctly by the front end,
2598 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002599 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002600 // ill-specified and decisions have been made to not allow this.
2601 if (! type.isArray() && memberQualifier.hasLocation())
2602 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002603
John Kessenich2f47bc92016-06-30 21:47:35 -06002604 if (qualifier.hasLocation()) // track for upcoming inheritance
2605 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2606
John Kessenich6090df02016-06-30 21:18:02 -06002607 // component, XFB, others
2608 if (glslangMember.getQualifier().hasComponent())
2609 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2610 if (glslangMember.getQualifier().hasXfbOffset())
2611 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2612 else if (explicitLayout != glslang::ElpNone) {
2613 // figure out what to do with offset, which is accumulating
2614 int nextOffset;
2615 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2616 if (offset >= 0)
2617 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2618 offset = nextOffset;
2619 }
2620
2621 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2622 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2623
2624 // built-in variable decorations
2625 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002626 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002627 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002628
2629#ifdef NV_EXTENSIONS
2630 if (builtIn == spv::BuiltInLayer) {
2631 // SPV_NV_viewport_array2 extension
2632 if (glslangMember.getQualifier().layoutViewportRelative){
2633 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2634 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2635 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2636 }
2637 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2638 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2640 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2641 }
2642 }
chaocdf3956c2017-02-14 14:52:34 -08002643 if (glslangMember.getQualifier().layoutPassthrough) {
2644 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2645 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2646 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2647 }
chaoc771d89f2017-01-13 01:10:53 -08002648#endif
John Kessenich6090df02016-06-30 21:18:02 -06002649 }
2650 }
2651
2652 // Decorate the structure
2653 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002654 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002655 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2656 builder.addCapability(spv::CapabilityGeometryStreams);
2657 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2658 }
2659 if (glslangIntermediate->getXfbMode()) {
2660 builder.addCapability(spv::CapabilityTransformFeedback);
2661 if (type.getQualifier().hasXfbStride())
2662 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2663 if (type.getQualifier().hasXfbBuffer())
2664 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2665 }
2666}
2667
John Kessenich6c292d32016-02-15 20:58:50 -07002668// Turn the expression forming the array size into an id.
2669// This is not quite trivial, because of specialization constants.
2670// Sometimes, a raw constant is turned into an Id, and sometimes
2671// a specialization constant expression is.
2672spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2673{
2674 // First, see if this is sized with a node, meaning a specialization constant:
2675 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2676 if (specNode != nullptr) {
2677 builder.clearAccessChain();
2678 specNode->traverse(this);
2679 return accessChainLoad(specNode->getAsTyped()->getType());
2680 }
qining25262b32016-05-06 17:25:16 -04002681
John Kessenich6c292d32016-02-15 20:58:50 -07002682 // Otherwise, need a compile-time (front end) size, get it:
2683 int size = arraySizes.getDimSize(dim);
2684 assert(size > 0);
2685 return builder.makeUintConstant(size);
2686}
2687
John Kessenich103bef92016-02-08 21:38:15 -07002688// Wrap the builder's accessChainLoad to:
2689// - localize handling of RelaxedPrecision
2690// - use the SPIR-V inferred type instead of another conversion of the glslang type
2691// (avoids unnecessary work and possible type punning for structures)
2692// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002693spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2694{
John Kessenich103bef92016-02-08 21:38:15 -07002695 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2696 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2697
2698 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002699 if (type.getBasicType() == glslang::EbtBool) {
2700 if (builder.isScalarType(nominalTypeId)) {
2701 // Conversion for bool
2702 spv::Id boolType = builder.makeBoolType();
2703 if (nominalTypeId != boolType)
2704 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2705 } else if (builder.isVectorType(nominalTypeId)) {
2706 // Conversion for bvec
2707 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2708 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2709 if (nominalTypeId != bvecType)
2710 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2711 }
2712 }
John Kessenich103bef92016-02-08 21:38:15 -07002713
2714 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002715}
2716
Rex Xu27253232016-02-23 17:51:09 +08002717// Wrap the builder's accessChainStore to:
2718// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002719//
2720// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002721void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2722{
2723 // Need to convert to abstract types when necessary
2724 if (type.getBasicType() == glslang::EbtBool) {
2725 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2726
2727 if (builder.isScalarType(nominalTypeId)) {
2728 // Conversion for bool
2729 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002730 if (nominalTypeId != boolType) {
2731 // keep these outside arguments, for determinant order-of-evaluation
2732 spv::Id one = builder.makeUintConstant(1);
2733 spv::Id zero = builder.makeUintConstant(0);
2734 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2735 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002736 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002737 } else if (builder.isVectorType(nominalTypeId)) {
2738 // Conversion for bvec
2739 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2740 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002741 if (nominalTypeId != bvecType) {
2742 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002743 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2744 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2745 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002746 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002747 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2748 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002749 }
2750 }
2751
2752 builder.accessChainStore(rvalue);
2753}
2754
John Kessenich4bf71552016-09-02 11:20:21 -06002755// For storing when types match at the glslang level, but not might match at the
2756// SPIR-V level.
2757//
2758// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002759// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002760// as in a member-decorated way.
2761//
2762// NOTE: This function can handle any store request; if it's not special it
2763// simplifies to a simple OpStore.
2764//
2765// Implicitly uses the existing builder.accessChain as the storage target.
2766void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2767{
John Kessenichb3e24e42016-09-11 12:33:43 -06002768 // we only do the complex path here if it's an aggregate
2769 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002770 accessChainStore(type, rValue);
2771 return;
2772 }
2773
John Kessenichb3e24e42016-09-11 12:33:43 -06002774 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002775 spv::Id rType = builder.getTypeId(rValue);
2776 spv::Id lValue = builder.accessChainGetLValue();
2777 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2778 if (lType == rType) {
2779 accessChainStore(type, rValue);
2780 return;
2781 }
2782
John Kessenichb3e24e42016-09-11 12:33:43 -06002783 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002784 // where the two types were the same type in GLSL. This requires member
2785 // by member copy, recursively.
2786
John Kessenichb3e24e42016-09-11 12:33:43 -06002787 // If an array, copy element by element.
2788 if (type.isArray()) {
2789 glslang::TType glslangElementType(type, 0);
2790 spv::Id elementRType = builder.getContainedTypeId(rType);
2791 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2792 // get the source member
2793 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002794
John Kessenichb3e24e42016-09-11 12:33:43 -06002795 // set up the target storage
2796 builder.clearAccessChain();
2797 builder.setAccessChainLValue(lValue);
2798 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002799
John Kessenichb3e24e42016-09-11 12:33:43 -06002800 // store the member
2801 multiTypeStore(glslangElementType, elementRValue);
2802 }
2803 } else {
2804 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002805
John Kessenichb3e24e42016-09-11 12:33:43 -06002806 // loop over structure members
2807 const glslang::TTypeList& members = *type.getStruct();
2808 for (int m = 0; m < (int)members.size(); ++m) {
2809 const glslang::TType& glslangMemberType = *members[m].type;
2810
2811 // get the source member
2812 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2813 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2814
2815 // set up the target storage
2816 builder.clearAccessChain();
2817 builder.setAccessChainLValue(lValue);
2818 builder.accessChainPush(builder.makeIntConstant(m));
2819
2820 // store the member
2821 multiTypeStore(glslangMemberType, memberRValue);
2822 }
John Kessenich4bf71552016-09-02 11:20:21 -06002823 }
2824}
2825
John Kessenichf85e8062015-12-19 13:57:10 -07002826// Decide whether or not this type should be
2827// decorated with offsets and strides, and if so
2828// whether std140 or std430 rules should be applied.
2829glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002830{
John Kessenichf85e8062015-12-19 13:57:10 -07002831 // has to be a block
2832 if (type.getBasicType() != glslang::EbtBlock)
2833 return glslang::ElpNone;
2834
2835 // has to be a uniform or buffer block
2836 if (type.getQualifier().storage != glslang::EvqUniform &&
2837 type.getQualifier().storage != glslang::EvqBuffer)
2838 return glslang::ElpNone;
2839
2840 // return the layout to use
2841 switch (type.getQualifier().layoutPacking) {
2842 case glslang::ElpStd140:
2843 case glslang::ElpStd430:
2844 return type.getQualifier().layoutPacking;
2845 default:
2846 return glslang::ElpNone;
2847 }
John Kessenich31ed4832015-09-09 17:51:38 -06002848}
2849
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002850// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002851int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002852{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002853 int size;
John Kessenich49987892015-12-29 17:11:44 -07002854 int stride;
2855 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002856
2857 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002858}
2859
John Kessenich49987892015-12-29 17:11:44 -07002860// 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 -07002861// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002862int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002863{
John Kessenich49987892015-12-29 17:11:44 -07002864 glslang::TType elementType;
2865 elementType.shallowCopy(matrixType);
2866 elementType.clearArraySizes();
2867
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002868 int size;
John Kessenich49987892015-12-29 17:11:44 -07002869 int stride;
2870 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2871
2872 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002873}
2874
John Kessenich5e4b1242015-08-06 22:53:06 -06002875// Given a member type of a struct, realign the current offset for it, and compute
2876// the next (not yet aligned) offset for the next member, which will get aligned
2877// on the next call.
2878// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2879// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2880// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002881void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002882 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002883{
2884 // this will get a positive value when deemed necessary
2885 nextOffset = -1;
2886
John Kessenich5e4b1242015-08-06 22:53:06 -06002887 // override anything in currentOffset with user-set offset
2888 if (memberType.getQualifier().hasOffset())
2889 currentOffset = memberType.getQualifier().layoutOffset;
2890
2891 // It could be that current linker usage in glslang updated all the layoutOffset,
2892 // in which case the following code does not matter. But, that's not quite right
2893 // once cross-compilation unit GLSL validation is done, as the original user
2894 // settings are needed in layoutOffset, and then the following will come into play.
2895
John Kessenichf85e8062015-12-19 13:57:10 -07002896 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 if (! memberType.getQualifier().hasOffset())
2898 currentOffset = -1;
2899
2900 return;
2901 }
2902
John Kessenichf85e8062015-12-19 13:57:10 -07002903 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002904 if (currentOffset < 0)
2905 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002906
John Kessenich5e4b1242015-08-06 22:53:06 -06002907 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2908 // but possibly not yet correctly aligned.
2909
2910 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002911 int dummyStride;
2912 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002913
2914 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002915 // TODO: make this consistent in early phases of code:
2916 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2917 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2918 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002919 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002920 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002921 int dummySize;
2922 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2923 if (componentAlignment <= 4)
2924 memberAlignment = componentAlignment;
2925 }
2926
2927 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002928 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002929
2930 // Bump up to vec4 if there is a bad straddle
2931 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2932 glslang::RoundToPow2(currentOffset, 16);
2933
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 nextOffset = currentOffset + memberSize;
2935}
2936
David Netoa901ffe2016-06-08 14:11:40 +01002937void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002938{
David Netoa901ffe2016-06-08 14:11:40 +01002939 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2940 switch (glslangBuiltIn)
2941 {
2942 case glslang::EbvClipDistance:
2943 case glslang::EbvCullDistance:
2944 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002945#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002946 case glslang::EbvViewportMaskNV:
2947 case glslang::EbvSecondaryPositionNV:
2948 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002949 case glslang::EbvPositionPerViewNV:
2950 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002951#endif
David Netoa901ffe2016-06-08 14:11:40 +01002952 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2953 // Alternately, we could just call this for any glslang built-in, since the
2954 // capability already guards against duplicates.
2955 TranslateBuiltInDecoration(glslangBuiltIn, false);
2956 break;
2957 default:
2958 // Capabilities were already generated when the struct was declared.
2959 break;
2960 }
John Kessenichebb50532016-05-16 19:22:05 -06002961}
2962
John Kessenich6fccb3c2016-09-19 16:01:41 -06002963bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002964{
John Kessenicheee9d532016-09-19 18:09:30 -06002965 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002966}
2967
John Kessenichd41993d2017-09-10 15:21:05 -06002968// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002969// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2970// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002971bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2972{
John Kessenich6a14f782017-12-04 02:48:10 -07002973 assert(qualifier == glslang::EvqIn ||
2974 qualifier == glslang::EvqOut ||
2975 qualifier == glslang::EvqInOut ||
2976 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002977 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)
John Kessenich6a14f782017-12-04 02:48:10 -07002987 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06002988 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 Kessenichfe4e5722017-10-19 02:07:30 -06003284 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3285 builder.setPrecision(result, precision);
3286 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003287 }
3288
John Kessenich56bab042015-09-16 10:54:31 -06003289 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003290#ifdef AMD_EXTENSIONS
3291 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3292#else
John Kessenich56bab042015-09-16 10:54:31 -06003293 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003294#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003295 if (sampler.ms) {
3296 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003297 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003298#ifdef AMD_EXTENSIONS
3299 } else if (cracked.lod) {
3300 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3301 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3302
3303 operands.push_back(spv::ImageOperandsLodMask);
3304 operands.push_back(*opIt);
3305#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003306 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003307 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3308 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003309
3310 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3311 builder.setPrecision(result, precision);
3312 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003313#ifdef AMD_EXTENSIONS
3314 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3315#else
John Kessenich56bab042015-09-16 10:54:31 -06003316 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003317#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003318 if (sampler.ms) {
3319 operands.push_back(*(opIt + 1));
3320 operands.push_back(spv::ImageOperandsSampleMask);
3321 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003322#ifdef AMD_EXTENSIONS
3323 } else if (cracked.lod) {
3324 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3325 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3326
3327 operands.push_back(*(opIt + 1));
3328 operands.push_back(spv::ImageOperandsLodMask);
3329 operands.push_back(*opIt);
3330#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003331 } else
3332 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003333 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003334 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3335 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003336 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003337#ifdef AMD_EXTENSIONS
3338 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3339#else
Rex Xu5eafa472016-02-19 22:24:03 +08003340 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003341#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003342 builder.addCapability(spv::CapabilitySparseResidency);
3343 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3344 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3345
3346 if (sampler.ms) {
3347 operands.push_back(spv::ImageOperandsSampleMask);
3348 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003349#ifdef AMD_EXTENSIONS
3350 } else if (cracked.lod) {
3351 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3352 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3353
3354 operands.push_back(spv::ImageOperandsLodMask);
3355 operands.push_back(*opIt++);
3356#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003357 }
3358
3359 // Create the return type that was a special structure
3360 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003361 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003362 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3363 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3364
3365 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3366
3367 // Decode the return type
3368 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3369 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003370 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003371 // Process image atomic operations
3372
3373 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3374 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003375 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003376
John Kessenich8c8505c2016-07-26 12:50:38 -06003377 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003378 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003379
3380 std::vector<spv::Id> operands;
3381 operands.push_back(pointer);
3382 for (; opIt != arguments.end(); ++opIt)
3383 operands.push_back(*opIt);
3384
John Kessenich8c8505c2016-07-26 12:50:38 -06003385 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003386 }
3387 }
3388
amhagan05506bb2017-06-13 16:53:02 -04003389#ifdef AMD_EXTENSIONS
3390 // Check for fragment mask functions other than queries
3391 if (cracked.fragMask) {
3392 assert(sampler.ms);
3393
3394 auto opIt = arguments.begin();
3395 std::vector<spv::Id> operands;
3396
3397 // Extract the image if necessary
3398 if (builder.isSampledImage(params.sampler))
3399 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3400
3401 operands.push_back(params.sampler);
3402 ++opIt;
3403
3404 if (sampler.isSubpass()) {
3405 // add on the (0,0) coordinate
3406 spv::Id zero = builder.makeIntConstant(0);
3407 std::vector<spv::Id> comps;
3408 comps.push_back(zero);
3409 comps.push_back(zero);
3410 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3411 }
3412
3413 for (; opIt != arguments.end(); ++opIt)
3414 operands.push_back(*opIt);
3415
3416 spv::Op fragMaskOp = spv::OpNop;
3417 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3418 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3419 else if (node->getOp() == glslang::EOpFragmentFetch)
3420 fragMaskOp = spv::OpFragmentFetchAMD;
3421
3422 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3423 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3424 return builder.createOp(fragMaskOp, resultType(), operands);
3425 }
3426#endif
3427
Rex Xufc618912015-09-09 16:42:49 +08003428 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003429 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003430 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3431
John Kessenichfc51d282015-08-19 13:34:18 -06003432 // check for bias argument
3433 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003434#ifdef AMD_EXTENSIONS
3435 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3436#else
Rex Xu71519fe2015-11-11 15:35:47 +08003437 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003438#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003439 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003440#ifdef AMD_EXTENSIONS
3441 if (cracked.gather)
3442 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3443#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003444 if (cracked.offset)
3445 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003446#ifdef AMD_EXTENSIONS
3447 else if (cracked.offsets)
3448 ++nonBiasArgCount;
3449#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003450 if (cracked.grad)
3451 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003452 if (cracked.lodClamp)
3453 ++nonBiasArgCount;
3454 if (sparse)
3455 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003456
3457 if ((int)arguments.size() > nonBiasArgCount)
3458 bias = true;
3459 }
3460
John Kessenicha5c33d62016-06-02 23:45:21 -06003461 // See if the sampler param should really be just the SPV image part
3462 if (cracked.fetch) {
3463 // a fetch needs to have the image extracted first
3464 if (builder.isSampledImage(params.sampler))
3465 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3466 }
3467
Rex Xu225e0fc2016-11-17 17:47:59 +08003468#ifdef AMD_EXTENSIONS
3469 if (cracked.gather) {
3470 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3471 if (bias || cracked.lod ||
3472 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3473 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003474 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003475 }
3476 }
3477#endif
3478
John Kessenichfc51d282015-08-19 13:34:18 -06003479 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003480
John Kessenichfc51d282015-08-19 13:34:18 -06003481 params.coords = arguments[1];
3482 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003483 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003484
3485 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003486 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003487 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003488 ++extraArgs;
3489 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003490 params.Dref = arguments[2];
3491 ++extraArgs;
3492 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003493 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003494 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003495 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003496 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003497 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003498 dRefComp = builder.getNumComponents(params.coords) - 1;
3499 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003500 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3501 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003502
3503 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003504 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003505 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003506 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003507 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3508 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3509 noImplicitLod = true;
3510 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003511
3512 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003513 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003514 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003515 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003516 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003517
3518 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003519 if (cracked.grad) {
3520 params.gradX = arguments[2 + extraArgs];
3521 params.gradY = arguments[3 + extraArgs];
3522 extraArgs += 2;
3523 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003524
3525 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003526 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003527 params.offset = arguments[2 + extraArgs];
3528 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003529 } else if (cracked.offsets) {
3530 params.offsets = arguments[2 + extraArgs];
3531 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003532 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003533
3534 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003535 if (cracked.lodClamp) {
3536 params.lodClamp = arguments[2 + extraArgs];
3537 ++extraArgs;
3538 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003539
3540 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003541 if (sparse) {
3542 params.texelOut = arguments[2 + extraArgs];
3543 ++extraArgs;
3544 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003545
John Kessenich76d4dfc2016-06-16 12:43:23 -06003546 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003547 if (cracked.gather && ! sampler.shadow) {
3548 // default component is 0, if missing, otherwise an argument
3549 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003550 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003551 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003552 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003553 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003554 }
3555
3556 // bias
3557 if (bias) {
3558 params.bias = arguments[2 + extraArgs];
3559 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003560 }
John Kessenichfc51d282015-08-19 13:34:18 -06003561
John Kessenich65336482016-06-16 14:06:26 -06003562 // projective component (might not to move)
3563 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3564 // are divided by the last component of P."
3565 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3566 // unused components will appear after all used components."
3567 if (cracked.proj) {
3568 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3569 int projTargetComp;
3570 switch (sampler.dim) {
3571 case glslang::Esd1D: projTargetComp = 1; break;
3572 case glslang::Esd2D: projTargetComp = 2; break;
3573 case glslang::EsdRect: projTargetComp = 2; break;
3574 default: projTargetComp = projSourceComp; break;
3575 }
3576 // copy the projective coordinate if we have to
3577 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003578 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003579 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3580 projSourceComp);
3581 params.coords = builder.createCompositeInsert(projComp, params.coords,
3582 builder.getTypeId(params.coords), projTargetComp);
3583 }
3584 }
3585
John Kessenich8c8505c2016-07-26 12:50:38 -06003586 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003587}
3588
3589spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3590{
3591 // Grab the function's pointer from the previously created function
3592 spv::Function* function = functionMap[node->getName().c_str()];
3593 if (! function)
3594 return 0;
3595
3596 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3597 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3598
3599 // See comments in makeFunctions() for details about the semantics for parameter passing.
3600 //
3601 // These imply we need a four step process:
3602 // 1. Evaluate the arguments
3603 // 2. Allocate and make copies of in, out, and inout arguments
3604 // 3. Make the call
3605 // 4. Copy back the results
3606
3607 // 1. Evaluate the arguments
3608 std::vector<spv::Builder::AccessChain> lValues;
3609 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003610 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003612 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003613 // build l-value
3614 builder.clearAccessChain();
3615 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003616 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003617 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003618 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3619 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003620 // save l-value
3621 lValues.push_back(builder.getAccessChain());
3622 } else {
3623 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003624 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003625 }
3626 }
3627
3628 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3629 // copy the original into that space.
3630 //
3631 // Also, build up the list of actual arguments to pass in for the call
3632 int lValueCount = 0;
3633 int rValueCount = 0;
3634 std::vector<spv::Id> spvArgs;
3635 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003636 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003637 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003638 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003639 builder.setAccessChain(lValues[lValueCount]);
3640 arg = builder.accessChainGetLValue();
3641 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003642 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003643 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003644 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3645 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3646 // need to copy the input into output space
3647 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003648 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003649 builder.clearAccessChain();
3650 builder.setAccessChainLValue(arg);
3651 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003652 }
3653 ++lValueCount;
3654 } else {
3655 arg = rValues[rValueCount];
3656 ++rValueCount;
3657 }
3658 spvArgs.push_back(arg);
3659 }
3660
3661 // 3. Make the call.
3662 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003663 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003664
3665 // 4. Copy back out an "out" arguments.
3666 lValueCount = 0;
3667 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003668 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003669 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3670 ++lValueCount;
3671 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003672 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3673 spv::Id copy = builder.createLoad(spvArgs[a]);
3674 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003675 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003676 }
3677 ++lValueCount;
3678 }
3679 }
3680
3681 return result;
3682}
3683
3684// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003685spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3686 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003687 spv::Id typeId, spv::Id left, spv::Id right,
3688 glslang::TBasicType typeProxy, bool reduceComparison)
3689{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003690#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003691 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003692 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3693#else
Rex Xucabbb782017-03-24 13:41:14 +08003694 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003696#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003697 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003698
3699 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003700 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003701 bool comparison = false;
3702
3703 switch (op) {
3704 case glslang::EOpAdd:
3705 case glslang::EOpAddAssign:
3706 if (isFloat)
3707 binOp = spv::OpFAdd;
3708 else
3709 binOp = spv::OpIAdd;
3710 break;
3711 case glslang::EOpSub:
3712 case glslang::EOpSubAssign:
3713 if (isFloat)
3714 binOp = spv::OpFSub;
3715 else
3716 binOp = spv::OpISub;
3717 break;
3718 case glslang::EOpMul:
3719 case glslang::EOpMulAssign:
3720 if (isFloat)
3721 binOp = spv::OpFMul;
3722 else
3723 binOp = spv::OpIMul;
3724 break;
3725 case glslang::EOpVectorTimesScalar:
3726 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003727 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003728 if (builder.isVector(right))
3729 std::swap(left, right);
3730 assert(builder.isScalar(right));
3731 needMatchingVectors = false;
3732 binOp = spv::OpVectorTimesScalar;
3733 } else
3734 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpVectorTimesMatrix:
3737 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003738 binOp = spv::OpVectorTimesMatrix;
3739 break;
3740 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003741 binOp = spv::OpMatrixTimesVector;
3742 break;
3743 case glslang::EOpMatrixTimesScalar:
3744 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003745 binOp = spv::OpMatrixTimesScalar;
3746 break;
3747 case glslang::EOpMatrixTimesMatrix:
3748 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003749 binOp = spv::OpMatrixTimesMatrix;
3750 break;
3751 case glslang::EOpOuterProduct:
3752 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003753 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755
3756 case glslang::EOpDiv:
3757 case glslang::EOpDivAssign:
3758 if (isFloat)
3759 binOp = spv::OpFDiv;
3760 else if (isUnsigned)
3761 binOp = spv::OpUDiv;
3762 else
3763 binOp = spv::OpSDiv;
3764 break;
3765 case glslang::EOpMod:
3766 case glslang::EOpModAssign:
3767 if (isFloat)
3768 binOp = spv::OpFMod;
3769 else if (isUnsigned)
3770 binOp = spv::OpUMod;
3771 else
3772 binOp = spv::OpSMod;
3773 break;
3774 case glslang::EOpRightShift:
3775 case glslang::EOpRightShiftAssign:
3776 if (isUnsigned)
3777 binOp = spv::OpShiftRightLogical;
3778 else
3779 binOp = spv::OpShiftRightArithmetic;
3780 break;
3781 case glslang::EOpLeftShift:
3782 case glslang::EOpLeftShiftAssign:
3783 binOp = spv::OpShiftLeftLogical;
3784 break;
3785 case glslang::EOpAnd:
3786 case glslang::EOpAndAssign:
3787 binOp = spv::OpBitwiseAnd;
3788 break;
3789 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003790 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003791 binOp = spv::OpLogicalAnd;
3792 break;
3793 case glslang::EOpInclusiveOr:
3794 case glslang::EOpInclusiveOrAssign:
3795 binOp = spv::OpBitwiseOr;
3796 break;
3797 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003798 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 binOp = spv::OpLogicalOr;
3800 break;
3801 case glslang::EOpExclusiveOr:
3802 case glslang::EOpExclusiveOrAssign:
3803 binOp = spv::OpBitwiseXor;
3804 break;
3805 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003806 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003807 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
3809
3810 case glslang::EOpLessThan:
3811 case glslang::EOpGreaterThan:
3812 case glslang::EOpLessThanEqual:
3813 case glslang::EOpGreaterThanEqual:
3814 case glslang::EOpEqual:
3815 case glslang::EOpNotEqual:
3816 case glslang::EOpVectorEqual:
3817 case glslang::EOpVectorNotEqual:
3818 comparison = true;
3819 break;
3820 default:
3821 break;
3822 }
3823
John Kessenich7c1aa102015-10-15 13:29:11 -06003824 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003825 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003826 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003827 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003828 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003829
3830 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003831 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003832 builder.promoteScalar(precision, left, right);
3833
qining25262b32016-05-06 17:25:16 -04003834 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3835 addDecoration(result, noContraction);
3836 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003837 }
3838
3839 if (! comparison)
3840 return 0;
3841
John Kessenich7c1aa102015-10-15 13:29:11 -06003842 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003843
John Kessenich4583b612016-08-07 19:14:22 -06003844 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3845 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003846 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003847
3848 switch (op) {
3849 case glslang::EOpLessThan:
3850 if (isFloat)
3851 binOp = spv::OpFOrdLessThan;
3852 else if (isUnsigned)
3853 binOp = spv::OpULessThan;
3854 else
3855 binOp = spv::OpSLessThan;
3856 break;
3857 case glslang::EOpGreaterThan:
3858 if (isFloat)
3859 binOp = spv::OpFOrdGreaterThan;
3860 else if (isUnsigned)
3861 binOp = spv::OpUGreaterThan;
3862 else
3863 binOp = spv::OpSGreaterThan;
3864 break;
3865 case glslang::EOpLessThanEqual:
3866 if (isFloat)
3867 binOp = spv::OpFOrdLessThanEqual;
3868 else if (isUnsigned)
3869 binOp = spv::OpULessThanEqual;
3870 else
3871 binOp = spv::OpSLessThanEqual;
3872 break;
3873 case glslang::EOpGreaterThanEqual:
3874 if (isFloat)
3875 binOp = spv::OpFOrdGreaterThanEqual;
3876 else if (isUnsigned)
3877 binOp = spv::OpUGreaterThanEqual;
3878 else
3879 binOp = spv::OpSGreaterThanEqual;
3880 break;
3881 case glslang::EOpEqual:
3882 case glslang::EOpVectorEqual:
3883 if (isFloat)
3884 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003885 else if (isBool)
3886 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 else
3888 binOp = spv::OpIEqual;
3889 break;
3890 case glslang::EOpNotEqual:
3891 case glslang::EOpVectorNotEqual:
3892 if (isFloat)
3893 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003894 else if (isBool)
3895 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003896 else
3897 binOp = spv::OpINotEqual;
3898 break;
3899 default:
3900 break;
3901 }
3902
qining25262b32016-05-06 17:25:16 -04003903 if (binOp != spv::OpNop) {
3904 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3905 addDecoration(result, noContraction);
3906 return builder.setPrecision(result, precision);
3907 }
John Kessenich140f3df2015-06-26 16:58:36 -06003908
3909 return 0;
3910}
3911
John Kessenich04bb8a02015-12-12 12:28:14 -07003912//
3913// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3914// These can be any of:
3915//
3916// matrix * scalar
3917// scalar * matrix
3918// matrix * matrix linear algebraic
3919// matrix * vector
3920// vector * matrix
3921// matrix * matrix componentwise
3922// matrix op matrix op in {+, -, /}
3923// matrix op scalar op in {+, -, /}
3924// scalar op matrix op in {+, -, /}
3925//
qining25262b32016-05-06 17:25:16 -04003926spv::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 -07003927{
3928 bool firstClass = true;
3929
3930 // First, handle first-class matrix operations (* and matrix/scalar)
3931 switch (op) {
3932 case spv::OpFDiv:
3933 if (builder.isMatrix(left) && builder.isScalar(right)) {
3934 // turn matrix / scalar into a multiply...
3935 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3936 op = spv::OpMatrixTimesScalar;
3937 } else
3938 firstClass = false;
3939 break;
3940 case spv::OpMatrixTimesScalar:
3941 if (builder.isMatrix(right))
3942 std::swap(left, right);
3943 assert(builder.isScalar(right));
3944 break;
3945 case spv::OpVectorTimesMatrix:
3946 assert(builder.isVector(left));
3947 assert(builder.isMatrix(right));
3948 break;
3949 case spv::OpMatrixTimesVector:
3950 assert(builder.isMatrix(left));
3951 assert(builder.isVector(right));
3952 break;
3953 case spv::OpMatrixTimesMatrix:
3954 assert(builder.isMatrix(left));
3955 assert(builder.isMatrix(right));
3956 break;
3957 default:
3958 firstClass = false;
3959 break;
3960 }
3961
qining25262b32016-05-06 17:25:16 -04003962 if (firstClass) {
3963 spv::Id result = builder.createBinOp(op, typeId, left, right);
3964 addDecoration(result, noContraction);
3965 return builder.setPrecision(result, precision);
3966 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003967
LoopDawg592860c2016-06-09 08:57:35 -06003968 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003969 // The result type of all of them is the same type as the (a) matrix operand.
3970 // The algorithm is to:
3971 // - break the matrix(es) into vectors
3972 // - smear any scalar to a vector
3973 // - do vector operations
3974 // - make a matrix out the vector results
3975 switch (op) {
3976 case spv::OpFAdd:
3977 case spv::OpFSub:
3978 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003979 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003980 case spv::OpFMul:
3981 {
3982 // one time set up...
3983 bool leftMat = builder.isMatrix(left);
3984 bool rightMat = builder.isMatrix(right);
3985 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3986 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3987 spv::Id scalarType = builder.getScalarTypeId(typeId);
3988 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3989 std::vector<spv::Id> results;
3990 spv::Id smearVec = spv::NoResult;
3991 if (builder.isScalar(left))
3992 smearVec = builder.smearScalar(precision, left, vecType);
3993 else if (builder.isScalar(right))
3994 smearVec = builder.smearScalar(precision, right, vecType);
3995
3996 // do each vector op
3997 for (unsigned int c = 0; c < numCols; ++c) {
3998 std::vector<unsigned int> indexes;
3999 indexes.push_back(c);
4000 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4001 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004002 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4003 addDecoration(result, noContraction);
4004 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004005 }
4006
4007 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004008 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004009 }
4010 default:
4011 assert(0);
4012 return spv::NoResult;
4013 }
4014}
4015
qining25262b32016-05-06 17:25:16 -04004016spv::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 -06004017{
4018 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004019 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004020 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004021#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004022 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004023 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4024#else
Rex Xucabbb782017-03-24 13:41:14 +08004025 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004026 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004027#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004028
4029 switch (op) {
4030 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004031 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004032 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004033 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004034 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004035 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004036 unaryOp = spv::OpSNegate;
4037 break;
4038
4039 case glslang::EOpLogicalNot:
4040 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004041 unaryOp = spv::OpLogicalNot;
4042 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004043 case glslang::EOpBitwiseNot:
4044 unaryOp = spv::OpNot;
4045 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004046
John Kessenich140f3df2015-06-26 16:58:36 -06004047 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004048 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004049 break;
4050 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004051 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004052 break;
4053 case glslang::EOpTranspose:
4054 unaryOp = spv::OpTranspose;
4055 break;
4056
4057 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 break;
4063 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004064 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004065 break;
4066 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 break;
4069 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
4072 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004073 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004074 break;
4075 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004076 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004079 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004080 break;
4081
4082 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004083 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004084 break;
4085 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004086 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004087 break;
4088 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004089 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004090 break;
4091 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004092 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004093 break;
4094 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004095 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004096 break;
4097 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004098 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004099 break;
4100
4101 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004102 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 break;
4104 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004105 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004106 break;
4107
4108 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004110 break;
4111 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004112 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004113 break;
4114 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004115 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004116 break;
4117 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004118 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004121 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004122 break;
4123 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004124 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004125 break;
4126
4127 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004128 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004129 break;
4130 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004131 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004132 break;
4133 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004134 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004135 break;
4136 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004137 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004138 break;
4139 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004140 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004141 break;
4142 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004143 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004144 break;
4145
4146 case glslang::EOpIsNan:
4147 unaryOp = spv::OpIsNan;
4148 break;
4149 case glslang::EOpIsInf:
4150 unaryOp = spv::OpIsInf;
4151 break;
LoopDawg592860c2016-06-09 08:57:35 -06004152 case glslang::EOpIsFinite:
4153 unaryOp = spv::OpIsFinite;
4154 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004155
Rex Xucbc426e2015-12-15 16:03:10 +08004156 case glslang::EOpFloatBitsToInt:
4157 case glslang::EOpFloatBitsToUint:
4158 case glslang::EOpIntBitsToFloat:
4159 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004160 case glslang::EOpDoubleBitsToInt64:
4161 case glslang::EOpDoubleBitsToUint64:
4162 case glslang::EOpInt64BitsToDouble:
4163 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004164#ifdef AMD_EXTENSIONS
4165 case glslang::EOpFloat16BitsToInt16:
4166 case glslang::EOpFloat16BitsToUint16:
4167 case glslang::EOpInt16BitsToFloat16:
4168 case glslang::EOpUint16BitsToFloat16:
4169#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004170 unaryOp = spv::OpBitcast;
4171 break;
4172
John Kessenich140f3df2015-06-26 16:58:36 -06004173 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004174 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004175 break;
4176 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004177 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004178 break;
4179 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004180 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004181 break;
4182 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004183 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004184 break;
4185 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004186 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004187 break;
4188 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004189 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004190 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004191 case glslang::EOpPackSnorm4x8:
4192 libCall = spv::GLSLstd450PackSnorm4x8;
4193 break;
4194 case glslang::EOpUnpackSnorm4x8:
4195 libCall = spv::GLSLstd450UnpackSnorm4x8;
4196 break;
4197 case glslang::EOpPackUnorm4x8:
4198 libCall = spv::GLSLstd450PackUnorm4x8;
4199 break;
4200 case glslang::EOpUnpackUnorm4x8:
4201 libCall = spv::GLSLstd450UnpackUnorm4x8;
4202 break;
4203 case glslang::EOpPackDouble2x32:
4204 libCall = spv::GLSLstd450PackDouble2x32;
4205 break;
4206 case glslang::EOpUnpackDouble2x32:
4207 libCall = spv::GLSLstd450UnpackDouble2x32;
4208 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004209
Rex Xu8ff43de2016-04-22 16:51:45 +08004210 case glslang::EOpPackInt2x32:
4211 case glslang::EOpUnpackInt2x32:
4212 case glslang::EOpPackUint2x32:
4213 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004214 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004215 break;
4216
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004217#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004218 case glslang::EOpPackInt2x16:
4219 case glslang::EOpUnpackInt2x16:
4220 case glslang::EOpPackUint2x16:
4221 case glslang::EOpUnpackUint2x16:
4222 case glslang::EOpPackInt4x16:
4223 case glslang::EOpUnpackInt4x16:
4224 case glslang::EOpPackUint4x16:
4225 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004226 case glslang::EOpPackFloat2x16:
4227 case glslang::EOpUnpackFloat2x16:
4228 unaryOp = spv::OpBitcast;
4229 break;
4230#endif
4231
John Kessenich140f3df2015-06-26 16:58:36 -06004232 case glslang::EOpDPdx:
4233 unaryOp = spv::OpDPdx;
4234 break;
4235 case glslang::EOpDPdy:
4236 unaryOp = spv::OpDPdy;
4237 break;
4238 case glslang::EOpFwidth:
4239 unaryOp = spv::OpFwidth;
4240 break;
4241 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004242 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004243 unaryOp = spv::OpDPdxFine;
4244 break;
4245 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004246 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004247 unaryOp = spv::OpDPdyFine;
4248 break;
4249 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004250 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004251 unaryOp = spv::OpFwidthFine;
4252 break;
4253 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004254 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004255 unaryOp = spv::OpDPdxCoarse;
4256 break;
4257 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004258 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004259 unaryOp = spv::OpDPdyCoarse;
4260 break;
4261 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004262 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004263 unaryOp = spv::OpFwidthCoarse;
4264 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004265 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004266 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004267 libCall = spv::GLSLstd450InterpolateAtCentroid;
4268 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004269 case glslang::EOpAny:
4270 unaryOp = spv::OpAny;
4271 break;
4272 case glslang::EOpAll:
4273 unaryOp = spv::OpAll;
4274 break;
4275
4276 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004277 if (isFloat)
4278 libCall = spv::GLSLstd450FAbs;
4279 else
4280 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004281 break;
4282 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004283 if (isFloat)
4284 libCall = spv::GLSLstd450FSign;
4285 else
4286 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004287 break;
4288
John Kessenichfc51d282015-08-19 13:34:18 -06004289 case glslang::EOpAtomicCounterIncrement:
4290 case glslang::EOpAtomicCounterDecrement:
4291 case glslang::EOpAtomicCounter:
4292 {
4293 // Handle all of the atomics in one place, in createAtomicOperation()
4294 std::vector<spv::Id> operands;
4295 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004296 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004297 }
4298
John Kessenichfc51d282015-08-19 13:34:18 -06004299 case glslang::EOpBitFieldReverse:
4300 unaryOp = spv::OpBitReverse;
4301 break;
4302 case glslang::EOpBitCount:
4303 unaryOp = spv::OpBitCount;
4304 break;
4305 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004306 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004307 break;
4308 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004309 if (isUnsigned)
4310 libCall = spv::GLSLstd450FindUMsb;
4311 else
4312 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004313 break;
4314
Rex Xu574ab042016-04-14 16:53:07 +08004315 case glslang::EOpBallot:
4316 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004317 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004318 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004319 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004320#ifdef AMD_EXTENSIONS
4321 case glslang::EOpMinInvocations:
4322 case glslang::EOpMaxInvocations:
4323 case glslang::EOpAddInvocations:
4324 case glslang::EOpMinInvocationsNonUniform:
4325 case glslang::EOpMaxInvocationsNonUniform:
4326 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004327 case glslang::EOpMinInvocationsInclusiveScan:
4328 case glslang::EOpMaxInvocationsInclusiveScan:
4329 case glslang::EOpAddInvocationsInclusiveScan:
4330 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4331 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4332 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4333 case glslang::EOpMinInvocationsExclusiveScan:
4334 case glslang::EOpMaxInvocationsExclusiveScan:
4335 case glslang::EOpAddInvocationsExclusiveScan:
4336 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4337 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4338 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004339#endif
Rex Xu51596642016-09-21 18:56:12 +08004340 {
4341 std::vector<spv::Id> operands;
4342 operands.push_back(operand);
4343 return createInvocationsOperation(op, typeId, operands, typeProxy);
4344 }
Rex Xu9d93a232016-05-05 12:30:44 +08004345
4346#ifdef AMD_EXTENSIONS
4347 case glslang::EOpMbcnt:
4348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4349 libCall = spv::MbcntAMD;
4350 break;
4351
4352 case glslang::EOpCubeFaceIndex:
4353 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4354 libCall = spv::CubeFaceIndexAMD;
4355 break;
4356
4357 case glslang::EOpCubeFaceCoord:
4358 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4359 libCall = spv::CubeFaceCoordAMD;
4360 break;
4361#endif
Rex Xu338b1852016-05-05 20:38:33 +08004362
John Kessenich140f3df2015-06-26 16:58:36 -06004363 default:
4364 return 0;
4365 }
4366
4367 spv::Id id;
4368 if (libCall >= 0) {
4369 std::vector<spv::Id> args;
4370 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004371 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004372 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004373 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004374 }
John Kessenich140f3df2015-06-26 16:58:36 -06004375
qining25262b32016-05-06 17:25:16 -04004376 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004377 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004378}
4379
John Kessenich7a53f762016-01-20 11:19:27 -07004380// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004381spv::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 -07004382{
4383 // Handle unary operations vector by vector.
4384 // The result type is the same type as the original type.
4385 // The algorithm is to:
4386 // - break the matrix into vectors
4387 // - apply the operation to each vector
4388 // - make a matrix out the vector results
4389
4390 // get the types sorted out
4391 int numCols = builder.getNumColumns(operand);
4392 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004393 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4394 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004395 std::vector<spv::Id> results;
4396
4397 // do each vector op
4398 for (int c = 0; c < numCols; ++c) {
4399 std::vector<unsigned int> indexes;
4400 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004401 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4402 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4403 addDecoration(destVec, noContraction);
4404 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004405 }
4406
4407 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004408 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004409}
4410
Rex Xu73e3ce72016-04-27 18:48:17 +08004411spv::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 -06004412{
4413 spv::Op convOp = spv::OpNop;
4414 spv::Id zero = 0;
4415 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004416 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004417
4418 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4419
4420 switch (op) {
4421 case glslang::EOpConvIntToBool:
4422 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004423 case glslang::EOpConvInt64ToBool:
4424 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004425#ifdef AMD_EXTENSIONS
4426 case glslang::EOpConvInt16ToBool:
4427 case glslang::EOpConvUint16ToBool:
4428#endif
4429 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4430 zero = builder.makeUint64Constant(0);
4431#ifdef AMD_EXTENSIONS
4432 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4433 zero = builder.makeUint16Constant(0);
4434#endif
4435 else
4436 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004437 zero = makeSmearedConstant(zero, vectorSize);
4438 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4439
4440 case glslang::EOpConvFloatToBool:
4441 zero = builder.makeFloatConstant(0.0F);
4442 zero = makeSmearedConstant(zero, vectorSize);
4443 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4444
4445 case glslang::EOpConvDoubleToBool:
4446 zero = builder.makeDoubleConstant(0.0);
4447 zero = makeSmearedConstant(zero, vectorSize);
4448 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4449
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004450#ifdef AMD_EXTENSIONS
4451 case glslang::EOpConvFloat16ToBool:
4452 zero = builder.makeFloat16Constant(0.0F);
4453 zero = makeSmearedConstant(zero, vectorSize);
4454 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4455#endif
4456
John Kessenich140f3df2015-06-26 16:58:36 -06004457 case glslang::EOpConvBoolToFloat:
4458 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004459 zero = builder.makeFloatConstant(0.0F);
4460 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004461 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004462
John Kessenich140f3df2015-06-26 16:58:36 -06004463 case glslang::EOpConvBoolToDouble:
4464 convOp = spv::OpSelect;
4465 zero = builder.makeDoubleConstant(0.0);
4466 one = builder.makeDoubleConstant(1.0);
4467 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004468
4469#ifdef AMD_EXTENSIONS
4470 case glslang::EOpConvBoolToFloat16:
4471 convOp = spv::OpSelect;
4472 zero = builder.makeFloat16Constant(0.0F);
4473 one = builder.makeFloat16Constant(1.0F);
4474 break;
4475#endif
4476
John Kessenich140f3df2015-06-26 16:58:36 -06004477 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004478 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004479#ifdef AMD_EXTENSIONS
4480 case glslang::EOpConvBoolToInt16:
4481#endif
4482 if (op == glslang::EOpConvBoolToInt64)
4483 zero = builder.makeInt64Constant(0);
4484#ifdef AMD_EXTENSIONS
4485 else if (op == glslang::EOpConvBoolToInt16)
4486 zero = builder.makeInt16Constant(0);
4487#endif
4488 else
4489 zero = builder.makeIntConstant(0);
4490
4491 if (op == glslang::EOpConvBoolToInt64)
4492 one = builder.makeInt64Constant(1);
4493#ifdef AMD_EXTENSIONS
4494 else if (op == glslang::EOpConvBoolToInt16)
4495 one = builder.makeInt16Constant(1);
4496#endif
4497 else
4498 one = builder.makeIntConstant(1);
4499
John Kessenich140f3df2015-06-26 16:58:36 -06004500 convOp = spv::OpSelect;
4501 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004502
John Kessenich140f3df2015-06-26 16:58:36 -06004503 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004504 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004505#ifdef AMD_EXTENSIONS
4506 case glslang::EOpConvBoolToUint16:
4507#endif
4508 if (op == glslang::EOpConvBoolToUint64)
4509 zero = builder.makeUint64Constant(0);
4510#ifdef AMD_EXTENSIONS
4511 else if (op == glslang::EOpConvBoolToUint16)
4512 zero = builder.makeUint16Constant(0);
4513#endif
4514 else
4515 zero = builder.makeUintConstant(0);
4516
4517 if (op == glslang::EOpConvBoolToUint64)
4518 one = builder.makeUint64Constant(1);
4519#ifdef AMD_EXTENSIONS
4520 else if (op == glslang::EOpConvBoolToUint16)
4521 one = builder.makeUint16Constant(1);
4522#endif
4523 else
4524 one = builder.makeUintConstant(1);
4525
John Kessenich140f3df2015-06-26 16:58:36 -06004526 convOp = spv::OpSelect;
4527 break;
4528
4529 case glslang::EOpConvIntToFloat:
4530 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004531 case glslang::EOpConvInt64ToFloat:
4532 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004533#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004534 case glslang::EOpConvInt16ToFloat:
4535 case glslang::EOpConvInt16ToDouble:
4536 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004537 case glslang::EOpConvIntToFloat16:
4538 case glslang::EOpConvInt64ToFloat16:
4539#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004540 convOp = spv::OpConvertSToF;
4541 break;
4542
4543 case glslang::EOpConvUintToFloat:
4544 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004545 case glslang::EOpConvUint64ToFloat:
4546 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004547#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004548 case glslang::EOpConvUint16ToFloat:
4549 case glslang::EOpConvUint16ToDouble:
4550 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004551 case glslang::EOpConvUintToFloat16:
4552 case glslang::EOpConvUint64ToFloat16:
4553#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004554 convOp = spv::OpConvertUToF;
4555 break;
4556
4557 case glslang::EOpConvDoubleToFloat:
4558 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004559#ifdef AMD_EXTENSIONS
4560 case glslang::EOpConvDoubleToFloat16:
4561 case glslang::EOpConvFloat16ToDouble:
4562 case glslang::EOpConvFloatToFloat16:
4563 case glslang::EOpConvFloat16ToFloat:
4564#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004565 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004566 if (builder.isMatrixType(destType))
4567 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004568 break;
4569
4570 case glslang::EOpConvFloatToInt:
4571 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004572 case glslang::EOpConvFloatToInt64:
4573 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004574#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004575 case glslang::EOpConvFloatToInt16:
4576 case glslang::EOpConvDoubleToInt16:
4577 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004578 case glslang::EOpConvFloat16ToInt:
4579 case glslang::EOpConvFloat16ToInt64:
4580#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004581 convOp = spv::OpConvertFToS;
4582 break;
4583
4584 case glslang::EOpConvUintToInt:
4585 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004586 case glslang::EOpConvUint64ToInt64:
4587 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004588#ifdef AMD_EXTENSIONS
4589 case glslang::EOpConvUint16ToInt16:
4590 case glslang::EOpConvInt16ToUint16:
4591#endif
qininge24aa5e2016-04-07 15:40:27 -04004592 if (builder.isInSpecConstCodeGenMode()) {
4593 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004594 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4595 zero = builder.makeUint64Constant(0);
4596#ifdef AMD_EXTENSIONS
4597 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4598 zero = builder.makeUint16Constant(0);
4599#endif
4600 else
4601 zero = builder.makeUintConstant(0);
4602
qining189b2032016-04-12 23:16:20 -04004603 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004604 // Use OpIAdd, instead of OpBitcast to do the conversion when
4605 // generating for OpSpecConstantOp instruction.
4606 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4607 }
4608 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004609 convOp = spv::OpBitcast;
4610 break;
4611
4612 case glslang::EOpConvFloatToUint:
4613 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004614 case glslang::EOpConvFloatToUint64:
4615 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004616#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004617 case glslang::EOpConvFloatToUint16:
4618 case glslang::EOpConvDoubleToUint16:
4619 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004620 case glslang::EOpConvFloat16ToUint:
4621 case glslang::EOpConvFloat16ToUint64:
4622#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004623 convOp = spv::OpConvertFToU;
4624 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004625
4626 case glslang::EOpConvIntToInt64:
4627 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004628#ifdef AMD_EXTENSIONS
4629 case glslang::EOpConvIntToInt16:
4630 case glslang::EOpConvInt16ToInt:
4631 case glslang::EOpConvInt64ToInt16:
4632 case glslang::EOpConvInt16ToInt64:
4633#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004634 convOp = spv::OpSConvert;
4635 break;
4636
4637 case glslang::EOpConvUintToUint64:
4638 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004639#ifdef AMD_EXTENSIONS
4640 case glslang::EOpConvUintToUint16:
4641 case glslang::EOpConvUint16ToUint:
4642 case glslang::EOpConvUint64ToUint16:
4643 case glslang::EOpConvUint16ToUint64:
4644#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004645 convOp = spv::OpUConvert;
4646 break;
4647
4648 case glslang::EOpConvIntToUint64:
4649 case glslang::EOpConvInt64ToUint:
4650 case glslang::EOpConvUint64ToInt:
4651 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004652#ifdef AMD_EXTENSIONS
4653 case glslang::EOpConvInt16ToUint:
4654 case glslang::EOpConvUintToInt16:
4655 case glslang::EOpConvInt16ToUint64:
4656 case glslang::EOpConvUint64ToInt16:
4657 case glslang::EOpConvUint16ToInt:
4658 case glslang::EOpConvIntToUint16:
4659 case glslang::EOpConvUint16ToInt64:
4660 case glslang::EOpConvInt64ToUint16:
4661#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004662 // OpSConvert/OpUConvert + OpBitCast
4663 switch (op) {
4664 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004665#ifdef AMD_EXTENSIONS
4666 case glslang::EOpConvInt16ToUint64:
4667#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004668 convOp = spv::OpSConvert;
4669 type = builder.makeIntType(64);
4670 break;
4671 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004672#ifdef AMD_EXTENSIONS
4673 case glslang::EOpConvInt16ToUint:
4674#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004675 convOp = spv::OpSConvert;
4676 type = builder.makeIntType(32);
4677 break;
4678 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004679#ifdef AMD_EXTENSIONS
4680 case glslang::EOpConvUint16ToInt:
4681#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004682 convOp = spv::OpUConvert;
4683 type = builder.makeUintType(32);
4684 break;
4685 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004686#ifdef AMD_EXTENSIONS
4687 case glslang::EOpConvUint16ToInt64:
4688#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004689 convOp = spv::OpUConvert;
4690 type = builder.makeUintType(64);
4691 break;
Rex Xucabbb782017-03-24 13:41:14 +08004692#ifdef AMD_EXTENSIONS
4693 case glslang::EOpConvUintToInt16:
4694 case glslang::EOpConvUint64ToInt16:
4695 convOp = spv::OpUConvert;
4696 type = builder.makeUintType(16);
4697 break;
4698 case glslang::EOpConvIntToUint16:
4699 case glslang::EOpConvInt64ToUint16:
4700 convOp = spv::OpSConvert;
4701 type = builder.makeIntType(16);
4702 break;
4703#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004704 default:
4705 assert(0);
4706 break;
4707 }
4708
4709 if (vectorSize > 0)
4710 type = builder.makeVectorType(type, vectorSize);
4711
4712 operand = builder.createUnaryOp(convOp, type, operand);
4713
4714 if (builder.isInSpecConstCodeGenMode()) {
4715 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004716#ifdef AMD_EXTENSIONS
4717 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4718 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4719 zero = builder.makeUint64Constant(0);
4720 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4721 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4722 zero = builder.makeUint16Constant(0);
4723 else
4724 zero = builder.makeUintConstant(0);
4725#else
4726 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4727 zero = builder.makeUint64Constant(0);
4728 else
4729 zero = builder.makeUintConstant(0);
4730#endif
4731
Rex Xu8ff43de2016-04-22 16:51:45 +08004732 zero = makeSmearedConstant(zero, vectorSize);
4733 // Use OpIAdd, instead of OpBitcast to do the conversion when
4734 // generating for OpSpecConstantOp instruction.
4735 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4736 }
4737 // For normal run-time conversion instruction, use OpBitcast.
4738 convOp = spv::OpBitcast;
4739 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004740 default:
4741 break;
4742 }
4743
4744 spv::Id result = 0;
4745 if (convOp == spv::OpNop)
4746 return result;
4747
4748 if (convOp == spv::OpSelect) {
4749 zero = makeSmearedConstant(zero, vectorSize);
4750 one = makeSmearedConstant(one, vectorSize);
4751 result = builder.createTriOp(convOp, destType, operand, one, zero);
4752 } else
4753 result = builder.createUnaryOp(convOp, destType, operand);
4754
John Kessenich32cfd492016-02-02 12:37:46 -07004755 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004756}
4757
4758spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4759{
4760 if (vectorSize == 0)
4761 return constant;
4762
4763 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4764 std::vector<spv::Id> components;
4765 for (int c = 0; c < vectorSize; ++c)
4766 components.push_back(constant);
4767 return builder.makeCompositeConstant(vectorTypeId, components);
4768}
4769
John Kessenich426394d2015-07-23 10:22:48 -06004770// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004771spv::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 -06004772{
4773 spv::Op opCode = spv::OpNop;
4774
4775 switch (op) {
4776 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004777 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004778 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004779 opCode = spv::OpAtomicIAdd;
4780 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004781 case glslang::EOpAtomicCounterSubtract:
4782 opCode = spv::OpAtomicISub;
4783 break;
John Kessenich426394d2015-07-23 10:22:48 -06004784 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004785 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004786 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004787 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004788 break;
4789 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004790 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004791 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004792 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004793 break;
4794 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004795 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004796 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004797 opCode = spv::OpAtomicAnd;
4798 break;
4799 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004800 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004801 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004802 opCode = spv::OpAtomicOr;
4803 break;
4804 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004805 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004806 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004807 opCode = spv::OpAtomicXor;
4808 break;
4809 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004810 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004811 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004812 opCode = spv::OpAtomicExchange;
4813 break;
4814 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004815 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004816 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004817 opCode = spv::OpAtomicCompareExchange;
4818 break;
4819 case glslang::EOpAtomicCounterIncrement:
4820 opCode = spv::OpAtomicIIncrement;
4821 break;
4822 case glslang::EOpAtomicCounterDecrement:
4823 opCode = spv::OpAtomicIDecrement;
4824 break;
4825 case glslang::EOpAtomicCounter:
4826 opCode = spv::OpAtomicLoad;
4827 break;
4828 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004829 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004830 break;
4831 }
4832
Rex Xue8fe8b02017-09-26 15:42:56 +08004833 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4834 builder.addCapability(spv::CapabilityInt64Atomics);
4835
John Kessenich426394d2015-07-23 10:22:48 -06004836 // Sort out the operands
4837 // - mapping from glslang -> SPV
4838 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004839 // - compare-exchange swaps the value and comparator
4840 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004841 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004842 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4843 auto opIt = operands.begin(); // walk the glslang operands
4844 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004845 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4846 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4847 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004848 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4849 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004850 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004851 spvAtomicOperands.push_back(*(opIt + 1));
4852 spvAtomicOperands.push_back(*opIt);
4853 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004854 }
John Kessenich426394d2015-07-23 10:22:48 -06004855
John Kessenich3e60a6f2015-09-14 22:45:16 -06004856 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004857 for (; opIt != operands.end(); ++opIt)
4858 spvAtomicOperands.push_back(*opIt);
4859
John Kessenich48d6e792017-10-06 21:21:48 -06004860 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4861
4862 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4863 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4864 if (op == glslang::EOpAtomicCounterDecrement)
4865 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4866
4867 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004868}
4869
John Kessenich91cef522016-05-05 16:45:40 -06004870// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004871spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004872{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004873#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004874 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004875 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004876#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004877
Rex Xu51596642016-09-21 18:56:12 +08004878 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004879 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004880 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4881
chaocf200da82016-12-20 12:44:35 -08004882 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4883 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004884 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4885 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004886 } else if (op == glslang::EOpAnyInvocation ||
4887 op == glslang::EOpAllInvocations ||
4888 op == glslang::EOpAllInvocationsEqual) {
4889 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4890 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004891 } else {
4892 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004893#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004894 if (op == glslang::EOpMinInvocationsNonUniform ||
4895 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004896 op == glslang::EOpAddInvocationsNonUniform ||
4897 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4898 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4899 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4900 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4901 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4902 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004903 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004904#endif
Rex Xu51596642016-09-21 18:56:12 +08004905
4906 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004907#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004908 switch (op) {
4909 case glslang::EOpMinInvocations:
4910 case glslang::EOpMaxInvocations:
4911 case glslang::EOpAddInvocations:
4912 case glslang::EOpMinInvocationsNonUniform:
4913 case glslang::EOpMaxInvocationsNonUniform:
4914 case glslang::EOpAddInvocationsNonUniform:
4915 groupOperation = spv::GroupOperationReduce;
4916 spvGroupOperands.push_back(groupOperation);
4917 break;
4918 case glslang::EOpMinInvocationsInclusiveScan:
4919 case glslang::EOpMaxInvocationsInclusiveScan:
4920 case glslang::EOpAddInvocationsInclusiveScan:
4921 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4922 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4923 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4924 groupOperation = spv::GroupOperationInclusiveScan;
4925 spvGroupOperands.push_back(groupOperation);
4926 break;
4927 case glslang::EOpMinInvocationsExclusiveScan:
4928 case glslang::EOpMaxInvocationsExclusiveScan:
4929 case glslang::EOpAddInvocationsExclusiveScan:
4930 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4931 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4932 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4933 groupOperation = spv::GroupOperationExclusiveScan;
4934 spvGroupOperands.push_back(groupOperation);
4935 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004936 default:
4937 break;
Rex Xu430ef402016-10-14 17:22:23 +08004938 }
Rex Xu9d93a232016-05-05 12:30:44 +08004939#endif
Rex Xu51596642016-09-21 18:56:12 +08004940 }
4941
4942 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4943 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004944
4945 switch (op) {
4946 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004947 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004948 break;
John Kessenich91cef522016-05-05 16:45:40 -06004949 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004950 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004951 break;
John Kessenich91cef522016-05-05 16:45:40 -06004952 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004953 opCode = spv::OpSubgroupAllEqualKHR;
4954 break;
Rex Xu51596642016-09-21 18:56:12 +08004955 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004956 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004957 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004958 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004959 break;
4960 case glslang::EOpReadFirstInvocation:
4961 opCode = spv::OpSubgroupFirstInvocationKHR;
4962 break;
4963 case glslang::EOpBallot:
4964 {
4965 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4966 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4967 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4968 //
4969 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4970 //
4971 spv::Id uintType = builder.makeUintType(32);
4972 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4973 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4974
4975 std::vector<spv::Id> components;
4976 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4977 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4978
4979 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4980 return builder.createUnaryOp(spv::OpBitcast, typeId,
4981 builder.createCompositeConstruct(uvec2Type, components));
4982 }
4983
Rex Xu9d93a232016-05-05 12:30:44 +08004984#ifdef AMD_EXTENSIONS
4985 case glslang::EOpMinInvocations:
4986 case glslang::EOpMaxInvocations:
4987 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004988 case glslang::EOpMinInvocationsInclusiveScan:
4989 case glslang::EOpMaxInvocationsInclusiveScan:
4990 case glslang::EOpAddInvocationsInclusiveScan:
4991 case glslang::EOpMinInvocationsExclusiveScan:
4992 case glslang::EOpMaxInvocationsExclusiveScan:
4993 case glslang::EOpAddInvocationsExclusiveScan:
4994 if (op == glslang::EOpMinInvocations ||
4995 op == glslang::EOpMinInvocationsInclusiveScan ||
4996 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004997 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004998 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004999 else {
5000 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005001 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005002 else
Rex Xu51596642016-09-21 18:56:12 +08005003 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005004 }
Rex Xu430ef402016-10-14 17:22:23 +08005005 } else if (op == glslang::EOpMaxInvocations ||
5006 op == glslang::EOpMaxInvocationsInclusiveScan ||
5007 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005008 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005009 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005010 else {
5011 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005012 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005013 else
Rex Xu51596642016-09-21 18:56:12 +08005014 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005015 }
5016 } else {
5017 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005018 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005019 else
Rex Xu51596642016-09-21 18:56:12 +08005020 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005021 }
5022
Rex Xu2bbbe062016-08-23 15:41:05 +08005023 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005024 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005025
5026 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005027 case glslang::EOpMinInvocationsNonUniform:
5028 case glslang::EOpMaxInvocationsNonUniform:
5029 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005030 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5031 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5032 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5033 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5034 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5035 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5036 if (op == glslang::EOpMinInvocationsNonUniform ||
5037 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5038 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005039 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005040 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005041 else {
5042 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005043 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005044 else
Rex Xu51596642016-09-21 18:56:12 +08005045 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005046 }
5047 }
Rex Xu430ef402016-10-14 17:22:23 +08005048 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5049 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5050 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005051 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005052 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005053 else {
5054 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005055 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005056 else
Rex Xu51596642016-09-21 18:56:12 +08005057 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005058 }
5059 }
5060 else {
5061 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005062 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005063 else
Rex Xu51596642016-09-21 18:56:12 +08005064 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005065 }
5066
Rex Xu2bbbe062016-08-23 15:41:05 +08005067 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005068 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005069
5070 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005071#endif
John Kessenich91cef522016-05-05 16:45:40 -06005072 default:
5073 logger->missingFunctionality("invocation operation");
5074 return spv::NoResult;
5075 }
Rex Xu51596642016-09-21 18:56:12 +08005076
5077 assert(opCode != spv::OpNop);
5078 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005079}
5080
Rex Xu2bbbe062016-08-23 15:41:05 +08005081// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005082spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005083{
Rex Xub7072052016-09-26 15:53:40 +08005084#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005085 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5086 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005087 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005088 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005089 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5090 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5091 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005092#else
5093 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5094 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005095 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5096 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005097#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005098
5099 // Handle group invocation operations scalar by scalar.
5100 // The result type is the same type as the original type.
5101 // The algorithm is to:
5102 // - break the vector into scalars
5103 // - apply the operation to each scalar
5104 // - make a vector out the scalar results
5105
5106 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005107 int numComponents = builder.getNumComponents(operands[0]);
5108 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005109 std::vector<spv::Id> results;
5110
5111 // do each scalar op
5112 for (int comp = 0; comp < numComponents; ++comp) {
5113 std::vector<unsigned int> indexes;
5114 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005115 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005116 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005117 if (op == spv::OpSubgroupReadInvocationKHR) {
5118 spvGroupOperands.push_back(scalar);
5119 spvGroupOperands.push_back(operands[1]);
5120 } else if (op == spv::OpGroupBroadcast) {
5121 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005122 spvGroupOperands.push_back(scalar);
5123 spvGroupOperands.push_back(operands[1]);
5124 } else {
chaocf200da82016-12-20 12:44:35 -08005125 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005126 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005127 spvGroupOperands.push_back(scalar);
5128 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005129
Rex Xub7072052016-09-26 15:53:40 +08005130 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005131 }
5132
5133 // put the pieces together
5134 return builder.createCompositeConstruct(typeId, results);
5135}
Rex Xu2bbbe062016-08-23 15:41:05 +08005136
John Kessenich5e4b1242015-08-06 22:53:06 -06005137spv::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 -06005138{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005139#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005140 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005141 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5142#else
Rex Xucabbb782017-03-24 13:41:14 +08005143 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005144 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005145#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005146
John Kessenich140f3df2015-06-26 16:58:36 -06005147 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005148 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005149 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005150 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005151 spv::Id typeId0 = 0;
5152 if (consumedOperands > 0)
5153 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005154 spv::Id typeId1 = 0;
5155 if (consumedOperands > 1)
5156 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005157 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005158
5159 switch (op) {
5160 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005161 if (isFloat)
5162 libCall = spv::GLSLstd450FMin;
5163 else if (isUnsigned)
5164 libCall = spv::GLSLstd450UMin;
5165 else
5166 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005167 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005168 break;
5169 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005170 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005171 break;
5172 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005173 if (isFloat)
5174 libCall = spv::GLSLstd450FMax;
5175 else if (isUnsigned)
5176 libCall = spv::GLSLstd450UMax;
5177 else
5178 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005179 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005180 break;
5181 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005182 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005183 break;
5184 case glslang::EOpDot:
5185 opCode = spv::OpDot;
5186 break;
5187 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005188 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 break;
5190
5191 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005192 if (isFloat)
5193 libCall = spv::GLSLstd450FClamp;
5194 else if (isUnsigned)
5195 libCall = spv::GLSLstd450UClamp;
5196 else
5197 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005198 builder.promoteScalar(precision, operands.front(), operands[1]);
5199 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005200 break;
5201 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005202 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5203 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005204 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005205 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005206 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005207 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005208 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005209 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005213 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005214 break;
5215 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005216 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005217 builder.promoteScalar(precision, operands[0], operands[2]);
5218 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
5220
5221 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005222 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 break;
5224 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005225 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 break;
5227 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005228 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005229 break;
5230 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005236 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005237 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005238 libCall = spv::GLSLstd450InterpolateAtSample;
5239 break;
5240 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005241 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005242 libCall = spv::GLSLstd450InterpolateAtOffset;
5243 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005244 case glslang::EOpAddCarry:
5245 opCode = spv::OpIAddCarry;
5246 typeId = builder.makeStructResultType(typeId0, typeId0);
5247 consumedOperands = 2;
5248 break;
5249 case glslang::EOpSubBorrow:
5250 opCode = spv::OpISubBorrow;
5251 typeId = builder.makeStructResultType(typeId0, typeId0);
5252 consumedOperands = 2;
5253 break;
5254 case glslang::EOpUMulExtended:
5255 opCode = spv::OpUMulExtended;
5256 typeId = builder.makeStructResultType(typeId0, typeId0);
5257 consumedOperands = 2;
5258 break;
5259 case glslang::EOpIMulExtended:
5260 opCode = spv::OpSMulExtended;
5261 typeId = builder.makeStructResultType(typeId0, typeId0);
5262 consumedOperands = 2;
5263 break;
5264 case glslang::EOpBitfieldExtract:
5265 if (isUnsigned)
5266 opCode = spv::OpBitFieldUExtract;
5267 else
5268 opCode = spv::OpBitFieldSExtract;
5269 break;
5270 case glslang::EOpBitfieldInsert:
5271 opCode = spv::OpBitFieldInsert;
5272 break;
5273
5274 case glslang::EOpFma:
5275 libCall = spv::GLSLstd450Fma;
5276 break;
5277 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005278 {
5279 libCall = spv::GLSLstd450FrexpStruct;
5280 assert(builder.isPointerType(typeId1));
5281 typeId1 = builder.getContainedTypeId(typeId1);
5282#ifdef AMD_EXTENSIONS
5283 int width = builder.getScalarTypeWidth(typeId1);
5284#else
5285 int width = 32;
5286#endif
5287 if (builder.getNumComponents(operands[0]) == 1)
5288 frexpIntType = builder.makeIntegerType(width, true);
5289 else
5290 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5291 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5292 consumedOperands = 1;
5293 }
John Kessenich55e7d112015-11-15 21:33:39 -07005294 break;
5295 case glslang::EOpLdexp:
5296 libCall = spv::GLSLstd450Ldexp;
5297 break;
5298
Rex Xu574ab042016-04-14 16:53:07 +08005299 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005300 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005301
Rex Xu9d93a232016-05-05 12:30:44 +08005302#ifdef AMD_EXTENSIONS
5303 case glslang::EOpSwizzleInvocations:
5304 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5305 libCall = spv::SwizzleInvocationsAMD;
5306 break;
5307 case glslang::EOpSwizzleInvocationsMasked:
5308 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5309 libCall = spv::SwizzleInvocationsMaskedAMD;
5310 break;
5311 case glslang::EOpWriteInvocation:
5312 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5313 libCall = spv::WriteInvocationAMD;
5314 break;
5315
5316 case glslang::EOpMin3:
5317 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5318 if (isFloat)
5319 libCall = spv::FMin3AMD;
5320 else {
5321 if (isUnsigned)
5322 libCall = spv::UMin3AMD;
5323 else
5324 libCall = spv::SMin3AMD;
5325 }
5326 break;
5327 case glslang::EOpMax3:
5328 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5329 if (isFloat)
5330 libCall = spv::FMax3AMD;
5331 else {
5332 if (isUnsigned)
5333 libCall = spv::UMax3AMD;
5334 else
5335 libCall = spv::SMax3AMD;
5336 }
5337 break;
5338 case glslang::EOpMid3:
5339 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5340 if (isFloat)
5341 libCall = spv::FMid3AMD;
5342 else {
5343 if (isUnsigned)
5344 libCall = spv::UMid3AMD;
5345 else
5346 libCall = spv::SMid3AMD;
5347 }
5348 break;
5349
5350 case glslang::EOpInterpolateAtVertex:
5351 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5352 libCall = spv::InterpolateAtVertexAMD;
5353 break;
5354#endif
5355
John Kessenich140f3df2015-06-26 16:58:36 -06005356 default:
5357 return 0;
5358 }
5359
5360 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005361 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005362 // Use an extended instruction from the standard library.
5363 // Construct the call arguments, without modifying the original operands vector.
5364 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5365 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005366 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005367 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005368 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005369 case 0:
5370 // should all be handled by visitAggregate and createNoArgOperation
5371 assert(0);
5372 return 0;
5373 case 1:
5374 // should all be handled by createUnaryOperation
5375 assert(0);
5376 return 0;
5377 case 2:
5378 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5379 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005380 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005381 // anything 3 or over doesn't have l-value operands, so all should be consumed
5382 assert(consumedOperands == operands.size());
5383 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005384 break;
5385 }
5386 }
5387
John Kessenich55e7d112015-11-15 21:33:39 -07005388 // Decode the return types that were structures
5389 switch (op) {
5390 case glslang::EOpAddCarry:
5391 case glslang::EOpSubBorrow:
5392 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5393 id = builder.createCompositeExtract(id, typeId0, 0);
5394 break;
5395 case glslang::EOpUMulExtended:
5396 case glslang::EOpIMulExtended:
5397 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5398 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5399 break;
5400 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005401 {
5402 assert(operands.size() == 2);
5403 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5404 // "exp" is floating-point type (from HLSL intrinsic)
5405 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5406 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5407 builder.createStore(member1, operands[1]);
5408 } else
5409 // "exp" is integer type (from GLSL built-in function)
5410 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5411 id = builder.createCompositeExtract(id, typeId0, 0);
5412 }
John Kessenich55e7d112015-11-15 21:33:39 -07005413 break;
5414 default:
5415 break;
5416 }
5417
John Kessenich32cfd492016-02-02 12:37:46 -07005418 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005419}
5420
Rex Xu9d93a232016-05-05 12:30:44 +08005421// Intrinsics with no arguments (or no return value, and no precision).
5422spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005423{
5424 // TODO: get the barrier operands correct
5425
5426 switch (op) {
5427 case glslang::EOpEmitVertex:
5428 builder.createNoResultOp(spv::OpEmitVertex);
5429 return 0;
5430 case glslang::EOpEndPrimitive:
5431 builder.createNoResultOp(spv::OpEndPrimitive);
5432 return 0;
5433 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005434 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005435 return 0;
5436 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005437 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005438 return 0;
5439 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005440 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005441 return 0;
5442 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005443 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005444 return 0;
5445 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005446 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005447 return 0;
5448 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005449 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005450 return 0;
5451 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005452 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005453 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005454 case glslang::EOpAllMemoryBarrierWithGroupSync:
5455 // Control barrier with non-"None" semantic is also a memory barrier.
5456 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5457 return 0;
5458 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5459 // Control barrier with non-"None" semantic is also a memory barrier.
5460 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5461 return 0;
5462 case glslang::EOpWorkgroupMemoryBarrier:
5463 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5464 return 0;
5465 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5466 // Control barrier with non-"None" semantic is also a memory barrier.
5467 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5468 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005469#ifdef AMD_EXTENSIONS
5470 case glslang::EOpTime:
5471 {
5472 std::vector<spv::Id> args; // Dummy arguments
5473 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5474 return builder.setPrecision(id, precision);
5475 }
5476#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005477 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005478 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005479 return 0;
5480 }
5481}
5482
5483spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5484{
John Kessenich2f273362015-07-18 22:34:27 -06005485 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005486 spv::Id id;
5487 if (symbolValues.end() != iter) {
5488 id = iter->second;
5489 return id;
5490 }
5491
5492 // it was not found, create it
5493 id = createSpvVariable(symbol);
5494 symbolValues[symbol->getId()] = id;
5495
Rex Xuc884b4a2016-06-29 15:03:44 +08005496 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005497 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005498 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005499 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005500 if (symbol->getType().getQualifier().hasSpecConstantId())
5501 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005502 if (symbol->getQualifier().hasIndex())
5503 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5504 if (symbol->getQualifier().hasComponent())
5505 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5506 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005507 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005508 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005509 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005510 if (symbol->getQualifier().hasXfbBuffer())
5511 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5512 if (symbol->getQualifier().hasXfbOffset())
5513 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5514 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005515 // atomic counters use this:
5516 if (symbol->getQualifier().hasOffset())
5517 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005518 }
5519
scygan2c864272016-05-18 18:09:17 +02005520 if (symbol->getQualifier().hasLocation())
5521 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005522 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005523 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005524 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005525 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005526 }
John Kessenich140f3df2015-06-26 16:58:36 -06005527 if (symbol->getQualifier().hasSet())
5528 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005529 else if (IsDescriptorResource(symbol->getType())) {
5530 // default to 0
5531 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5532 }
John Kessenich140f3df2015-06-26 16:58:36 -06005533 if (symbol->getQualifier().hasBinding())
5534 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005535 if (symbol->getQualifier().hasAttachment())
5536 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005537 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005538 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005539 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005541 if (symbol->getQualifier().hasXfbBuffer())
5542 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5543 }
5544
Rex Xu1da878f2016-02-21 20:59:01 +08005545 if (symbol->getType().isImage()) {
5546 std::vector<spv::Decoration> memory;
5547 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5548 for (unsigned int i = 0; i < memory.size(); ++i)
5549 addDecoration(id, memory[i]);
5550 }
5551
John Kessenich140f3df2015-06-26 16:58:36 -06005552 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005553 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005554 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005555 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005556
John Kessenichecba76f2017-01-06 00:34:48 -07005557#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005558 if (builtIn == spv::BuiltInSampleMask) {
5559 spv::Decoration decoration;
5560 // GL_NV_sample_mask_override_coverage extension
5561 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005562 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005563 else
5564 decoration = (spv::Decoration)spv::DecorationMax;
5565 addDecoration(id, decoration);
5566 if (decoration != spv::DecorationMax) {
5567 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5568 }
5569 }
chaoc771d89f2017-01-13 01:10:53 -08005570 else if (builtIn == spv::BuiltInLayer) {
5571 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005572 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005573 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5574 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5575 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5576 }
John Kessenichb41bff62017-08-11 13:07:17 -06005577 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005578 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5579 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5580 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5581 }
5582 }
5583
chaoc6e5acae2016-12-20 13:28:52 -08005584 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005585 addDecoration(id, spv::DecorationPassthroughNV);
5586 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005587 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5588 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005589#endif
5590
John Kessenich140f3df2015-06-26 16:58:36 -06005591 return id;
5592}
5593
John Kessenich55e7d112015-11-15 21:33:39 -07005594// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005595void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5596{
John Kessenich4016e382016-07-15 11:53:56 -06005597 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005598 builder.addDecoration(id, dec);
5599}
5600
John Kessenich55e7d112015-11-15 21:33:39 -07005601// If 'dec' is valid, add a one-operand decoration to an object
5602void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5603{
John Kessenich4016e382016-07-15 11:53:56 -06005604 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005605 builder.addDecoration(id, dec, value);
5606}
5607
5608// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005609void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5610{
John Kessenich4016e382016-07-15 11:53:56 -06005611 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005612 builder.addMemberDecoration(id, (unsigned)member, dec);
5613}
5614
John Kessenich92187592016-02-01 13:45:25 -07005615// If 'dec' is valid, add a one-operand decoration to a struct member
5616void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5617{
John Kessenich4016e382016-07-15 11:53:56 -06005618 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005619 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5620}
5621
John Kessenich55e7d112015-11-15 21:33:39 -07005622// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005623// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005624//
5625// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5626//
5627// Recursively walk the nodes. The nodes form a tree whose leaves are
5628// regular constants, which themselves are trees that createSpvConstant()
5629// recursively walks. So, this function walks the "top" of the tree:
5630// - emit specialization constant-building instructions for specConstant
5631// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005632spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005633{
John Kessenich7cc0e282016-03-20 00:46:02 -06005634 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005635
qining4f4bb812016-04-03 23:55:17 -04005636 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005637 if (! node.getQualifier().specConstant) {
5638 // hand off to the non-spec-constant path
5639 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5640 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005641 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005642 nextConst, false);
5643 }
5644
5645 // We now know we have a specialization constant to build
5646
John Kessenichd94c0032016-05-30 19:29:40 -06005647 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005648 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5649 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5650 std::vector<spv::Id> dimConstId;
5651 for (int dim = 0; dim < 3; ++dim) {
5652 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5653 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5654 if (specConst)
5655 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5656 }
5657 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5658 }
5659
5660 // An AST node labelled as specialization constant should be a symbol node.
5661 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5662 if (auto* sn = node.getAsSymbolNode()) {
5663 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005664 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5665 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5666 // will set the builder into spec constant op instruction generating mode.
5667 sub_tree->traverse(this);
5668 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005669 } else if (auto* const_union_array = &sn->getConstArray()){
5670 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005671 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5672 builder.addName(id, sn->getName().c_str());
5673 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005674 }
5675 }
qining4f4bb812016-04-03 23:55:17 -04005676
5677 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5678 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005679 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005680 exit(1);
5681 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005682}
5683
John Kessenich140f3df2015-06-26 16:58:36 -06005684// Use 'consts' as the flattened glslang source of scalar constants to recursively
5685// build the aggregate SPIR-V constant.
5686//
5687// If there are not enough elements present in 'consts', 0 will be substituted;
5688// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5689//
qining08408382016-03-21 09:51:37 -04005690spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005691{
5692 // vector of constants for SPIR-V
5693 std::vector<spv::Id> spvConsts;
5694
5695 // Type is used for struct and array constants
5696 spv::Id typeId = convertGlslangToSpvType(glslangType);
5697
5698 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005699 glslang::TType elementType(glslangType, 0);
5700 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005701 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005702 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005703 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005704 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005705 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005706 } else if (glslangType.getStruct()) {
5707 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5708 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005709 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005710 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005711 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5712 bool zero = nextConst >= consts.size();
5713 switch (glslangType.getBasicType()) {
5714 case glslang::EbtInt:
5715 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5716 break;
5717 case glslang::EbtUint:
5718 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5719 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005720 case glslang::EbtInt64:
5721 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5722 break;
5723 case glslang::EbtUint64:
5724 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5725 break;
Rex Xucabbb782017-03-24 13:41:14 +08005726#ifdef AMD_EXTENSIONS
5727 case glslang::EbtInt16:
5728 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5729 break;
5730 case glslang::EbtUint16:
5731 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5732 break;
5733#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005734 case glslang::EbtFloat:
5735 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5736 break;
5737 case glslang::EbtDouble:
5738 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5739 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005740#ifdef AMD_EXTENSIONS
5741 case glslang::EbtFloat16:
5742 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5743 break;
5744#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005745 case glslang::EbtBool:
5746 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5747 break;
5748 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005749 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005750 break;
5751 }
5752 ++nextConst;
5753 }
5754 } else {
5755 // we have a non-aggregate (scalar) constant
5756 bool zero = nextConst >= consts.size();
5757 spv::Id scalar = 0;
5758 switch (glslangType.getBasicType()) {
5759 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005760 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005761 break;
5762 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005763 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005764 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005765 case glslang::EbtInt64:
5766 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5767 break;
5768 case glslang::EbtUint64:
5769 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5770 break;
Rex Xucabbb782017-03-24 13:41:14 +08005771#ifdef AMD_EXTENSIONS
5772 case glslang::EbtInt16:
5773 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5774 break;
5775 case glslang::EbtUint16:
5776 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5777 break;
5778#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005779 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005780 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005781 break;
5782 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005783 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005784 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005785#ifdef AMD_EXTENSIONS
5786 case glslang::EbtFloat16:
5787 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5788 break;
5789#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005790 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005791 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005792 break;
5793 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005794 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005795 break;
5796 }
5797 ++nextConst;
5798 return scalar;
5799 }
5800
5801 return builder.makeCompositeConstant(typeId, spvConsts);
5802}
5803
John Kessenich7c1aa102015-10-15 13:29:11 -06005804// Return true if the node is a constant or symbol whose reading has no
5805// non-trivial observable cost or effect.
5806bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5807{
5808 // don't know what this is
5809 if (node == nullptr)
5810 return false;
5811
5812 // a constant is safe
5813 if (node->getAsConstantUnion() != nullptr)
5814 return true;
5815
5816 // not a symbol means non-trivial
5817 if (node->getAsSymbolNode() == nullptr)
5818 return false;
5819
5820 // a symbol, depends on what's being read
5821 switch (node->getType().getQualifier().storage) {
5822 case glslang::EvqTemporary:
5823 case glslang::EvqGlobal:
5824 case glslang::EvqIn:
5825 case glslang::EvqInOut:
5826 case glslang::EvqConst:
5827 case glslang::EvqConstReadOnly:
5828 case glslang::EvqUniform:
5829 return true;
5830 default:
5831 return false;
5832 }
qining25262b32016-05-06 17:25:16 -04005833}
John Kessenich7c1aa102015-10-15 13:29:11 -06005834
5835// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005836// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005837// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005838// Return true if trivial.
5839bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5840{
5841 if (node == nullptr)
5842 return false;
5843
John Kessenich84cc15f2017-05-24 16:44:47 -06005844 // count non scalars as trivial, as well as anything coming from HLSL
5845 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005846 return true;
5847
John Kessenich7c1aa102015-10-15 13:29:11 -06005848 // symbols and constants are trivial
5849 if (isTrivialLeaf(node))
5850 return true;
5851
5852 // otherwise, it needs to be a simple operation or one or two leaf nodes
5853
5854 // not a simple operation
5855 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5856 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5857 if (binaryNode == nullptr && unaryNode == nullptr)
5858 return false;
5859
5860 // not on leaf nodes
5861 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5862 return false;
5863
5864 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5865 return false;
5866 }
5867
5868 switch (node->getAsOperator()->getOp()) {
5869 case glslang::EOpLogicalNot:
5870 case glslang::EOpConvIntToBool:
5871 case glslang::EOpConvUintToBool:
5872 case glslang::EOpConvFloatToBool:
5873 case glslang::EOpConvDoubleToBool:
5874 case glslang::EOpEqual:
5875 case glslang::EOpNotEqual:
5876 case glslang::EOpLessThan:
5877 case glslang::EOpGreaterThan:
5878 case glslang::EOpLessThanEqual:
5879 case glslang::EOpGreaterThanEqual:
5880 case glslang::EOpIndexDirect:
5881 case glslang::EOpIndexDirectStruct:
5882 case glslang::EOpLogicalXor:
5883 case glslang::EOpAny:
5884 case glslang::EOpAll:
5885 return true;
5886 default:
5887 return false;
5888 }
5889}
5890
5891// Emit short-circuiting code, where 'right' is never evaluated unless
5892// the left side is true (for &&) or false (for ||).
5893spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5894{
5895 spv::Id boolTypeId = builder.makeBoolType();
5896
5897 // emit left operand
5898 builder.clearAccessChain();
5899 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005900 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005901
5902 // Operands to accumulate OpPhi operands
5903 std::vector<spv::Id> phiOperands;
5904 // accumulate left operand's phi information
5905 phiOperands.push_back(leftId);
5906 phiOperands.push_back(builder.getBuildPoint()->getId());
5907
5908 // Make the two kinds of operation symmetric with a "!"
5909 // || => emit "if (! left) result = right"
5910 // && => emit "if ( left) result = right"
5911 //
5912 // TODO: this runtime "not" for || could be avoided by adding functionality
5913 // to 'builder' to have an "else" without an "then"
5914 if (op == glslang::EOpLogicalOr)
5915 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5916
5917 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005918 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005919
5920 // emit right operand as the "then" part of the "if"
5921 builder.clearAccessChain();
5922 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005923 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005924
5925 // accumulate left operand's phi information
5926 phiOperands.push_back(rightId);
5927 phiOperands.push_back(builder.getBuildPoint()->getId());
5928
5929 // finish the "if"
5930 ifBuilder.makeEndIf();
5931
5932 // phi together the two results
5933 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5934}
5935
Rex Xu9d93a232016-05-05 12:30:44 +08005936// Return type Id of the imported set of extended instructions corresponds to the name.
5937// Import this set if it has not been imported yet.
5938spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5939{
5940 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5941 return extBuiltinMap[name];
5942 else {
Rex Xu51596642016-09-21 18:56:12 +08005943 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005944 spv::Id extBuiltins = builder.import(name);
5945 extBuiltinMap[name] = extBuiltins;
5946 return extBuiltins;
5947 }
5948}
5949
John Kessenich140f3df2015-06-26 16:58:36 -06005950}; // end anonymous namespace
5951
5952namespace glslang {
5953
John Kessenich68d78fd2015-07-12 19:28:10 -06005954void GetSpirvVersion(std::string& version)
5955{
John Kessenich9e55f632015-07-15 10:03:39 -06005956 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005957 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005958 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005959 version = buf;
5960}
5961
John Kessenicha372a3e2017-11-02 22:32:14 -06005962// For low-order part of the generator's magic number. Bump up
5963// when there is a change in the style (e.g., if SSA form changes,
5964// or a different instruction sequence to do something gets used).
5965int GetSpirvGeneratorVersion()
5966{
5967 return 2;
5968}
5969
John Kessenich140f3df2015-06-26 16:58:36 -06005970// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005971void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005972{
5973 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005974 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005975 if (out.fail())
5976 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005977 for (int i = 0; i < (int)spirv.size(); ++i) {
5978 unsigned int word = spirv[i];
5979 out.write((const char*)&word, 4);
5980 }
5981 out.close();
5982}
5983
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005984// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005985void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005986{
5987 std::ofstream out;
5988 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005989 if (out.fail())
5990 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005991 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005992 if (varName != nullptr) {
5993 out << "\t #pragma once" << std::endl;
5994 out << "const uint32_t " << varName << "[] = {" << std::endl;
5995 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005996 const int WORDS_PER_LINE = 8;
5997 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5998 out << "\t";
5999 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6000 const unsigned int word = spirv[i + j];
6001 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6002 if (i + j + 1 < (int)spirv.size()) {
6003 out << ",";
6004 }
6005 }
6006 out << std::endl;
6007 }
Flavio15017db2017-02-15 14:29:33 -08006008 if (varName != nullptr) {
6009 out << "};";
6010 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006011 out.close();
6012}
6013
GregFcd1f1692017-09-21 18:40:22 -06006014#ifdef ENABLE_OPT
6015void errHandler(const std::string& str) {
6016 std::cerr << str << std::endl;
6017}
6018#endif
6019
John Kessenich140f3df2015-06-26 16:58:36 -06006020//
6021// Set up the glslang traversal
6022//
John Kessenich121853f2017-05-31 17:11:16 -06006023void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006024{
Lei Zhang17535f72016-05-04 15:55:59 -04006025 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006026 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006027}
6028
John Kessenich121853f2017-05-31 17:11:16 -06006029void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6030 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006031{
John Kessenich140f3df2015-06-26 16:58:36 -06006032 TIntermNode* root = intermediate.getTreeRoot();
6033
6034 if (root == 0)
6035 return;
6036
John Kessenich121853f2017-05-31 17:11:16 -06006037 glslang::SpvOptions defaultOptions;
6038 if (options == nullptr)
6039 options = &defaultOptions;
6040
John Kessenich140f3df2015-06-26 16:58:36 -06006041 glslang::GetThreadPoolAllocator().push();
6042
John Kessenich121853f2017-05-31 17:11:16 -06006043 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006044 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006045 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006046 it.dumpSpv(spirv);
6047
GregFcd1f1692017-09-21 18:40:22 -06006048#ifdef ENABLE_OPT
6049 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6050 // eg. forward and remove memory writes of opaque types.
6051 if ((intermediate.getSource() == EShSourceHlsl ||
6052 options->optimizeSize) &&
6053 !options->disableOptimizer) {
6054 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6055
6056 spvtools::Optimizer optimizer(target_env);
6057 optimizer.SetMessageConsumer([](spv_message_level_t level,
6058 const char* source,
6059 const spv_position_t& position,
6060 const char* message) {
6061 std::cerr << StringifyMessage(level, source, position, message)
6062 << std::endl;
6063 });
6064
6065 optimizer.RegisterPass(CreateInlineExhaustivePass());
6066 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6067 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6068 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6069 optimizer.RegisterPass(CreateInsertExtractElimPass());
6070 optimizer.RegisterPass(CreateAggressiveDCEPass());
6071 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006072 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006073 optimizer.RegisterPass(CreateBlockMergePass());
6074 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6075 optimizer.RegisterPass(CreateInsertExtractElimPass());
6076 optimizer.RegisterPass(CreateAggressiveDCEPass());
6077 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6078 // if (options->optimizeSize)
6079 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6080
6081 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6082 return;
6083
6084 // Remove dead module-level objects: functions, types, vars
6085 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6086 spv::spirvbin_t Remapper(0);
6087 Remapper.registerErrorHandler(errHandler);
6088 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6089 }
6090#endif
6091
John Kessenich140f3df2015-06-26 16:58:36 -06006092 glslang::GetThreadPoolAllocator().pop();
6093}
6094
6095}; // end namespace glslang