blob: ce5e3696e647c152a053bf6eb24e7007b0384e7a [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"
Piers Daniell1c5443c2017-12-13 13:07:22 -070047 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080048#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080050#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080051#ifdef NV_EXTENSIONS
52 #include "GLSL.ext.NV.h"
53#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060054}
John Kessenich140f3df2015-06-26 16:58:36 -060055
GregFcd1f1692017-09-21 18:40:22 -060056#ifdef ENABLE_OPT
57 #include "spirv-tools/optimizer.hpp"
58 #include "message.h"
59 #include "SPVRemapper.h"
60#endif
61
62#ifdef ENABLE_OPT
63using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
101}
102
John Kessenich140f3df2015-06-26 16:58:36 -0600103//
104// The main holder of information for translating glslang to SPIR-V.
105//
106// Derives from the AST walking base class.
107//
108class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
109public:
John Kessenich121853f2017-05-31 17:11:16 -0600110 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700111 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600112
113 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
114 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
115 void visitConstantUnion(glslang::TIntermConstantUnion*);
116 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
117 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
118 void visitSymbol(glslang::TIntermSymbol* symbol);
119 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
120 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
121 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
122
John Kessenichfca82622016-11-26 13:23:20 -0700123 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700124 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600125
126protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100129 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700130 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800131 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600132 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600133 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600134 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
135 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600136 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
137 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
138 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700140 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600141 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600142 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
143 glslang::TLayoutPacking, const glslang::TQualifier&);
144 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
145 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700146 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700147 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800148 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600149 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700150 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700151 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
152 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
153 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 +0100154 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600155
John Kessenich6fccb3c2016-09-19 16:01:41 -0600156 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600157 bool writableParam(glslang::TStorageQualifier);
158 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600159 void makeFunctions(const glslang::TIntermSequence&);
160 void makeGlobalInitializers(const glslang::TIntermSequence&);
161 void visitFunctions(const glslang::TIntermSequence&);
162 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600164 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
165 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
167
qining25262b32016-05-06 17:25:16 -0400168 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);
169 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
170 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 +0800171 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 +0800172 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 -0600173 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 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 +0800175 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800176 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600177 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 +0800178 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600179 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
180 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700181 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600182 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700183 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400184 spv::Id createSpvConstant(const glslang::TIntermTyped&);
185 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600186 bool isTrivialLeaf(const glslang::TIntermTyped* node);
187 bool isTrivial(const glslang::TIntermTyped* node);
188 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500189#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800190 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500191#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600192
John Kessenich121853f2017-05-31 17:11:16 -0600193 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600195 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700196 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600197 int sequenceDepth;
198
Lei Zhang17535f72016-05-04 15:55:59 -0400199 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400200
John Kessenich140f3df2015-06-26 16:58:36 -0600201 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
202 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700203 bool inEntryPoint;
204 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700205 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700206 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600207 const glslang::TIntermediate* glslangIntermediate;
208 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800209 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600210
John Kessenich2f273362015-07-18 22:34:27 -0600211 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600212 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700214 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600215 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600216 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600217};
218
219//
220// Helper functions for translating glslang representations to SPIR-V enumerants.
221//
222
223// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700224spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600225{
John Kessenich66e2faf2016-03-12 18:34:36 -0700226 switch (source) {
227 case glslang::EShSourceGlsl:
228 switch (profile) {
229 case ENoProfile:
230 case ECoreProfile:
231 case ECompatibilityProfile:
232 return spv::SourceLanguageGLSL;
233 case EEsProfile:
234 return spv::SourceLanguageESSL;
235 default:
236 return spv::SourceLanguageUnknown;
237 }
238 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600239 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 default:
241 return spv::SourceLanguageUnknown;
242 }
243}
244
245// Translate glslang language (stage) to SPIR-V execution model.
246spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
247{
248 switch (stage) {
249 case EShLangVertex: return spv::ExecutionModelVertex;
250 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
251 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
252 case EShLangGeometry: return spv::ExecutionModelGeometry;
253 case EShLangFragment: return spv::ExecutionModelFragment;
254 case EShLangCompute: return spv::ExecutionModelGLCompute;
255 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700256 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600257 return spv::ExecutionModelFragment;
258 }
259}
260
John Kessenich140f3df2015-06-26 16:58:36 -0600261// Translate glslang sampler type to SPIR-V dimensionality.
262spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
263{
264 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700265 case glslang::Esd1D: return spv::Dim1D;
266 case glslang::Esd2D: return spv::Dim2D;
267 case glslang::Esd3D: return spv::Dim3D;
268 case glslang::EsdCube: return spv::DimCube;
269 case glslang::EsdRect: return spv::DimRect;
270 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700271 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::Dim2D;
275 }
276}
277
John Kessenichf6640762016-08-01 19:44:00 -0600278// Translate glslang precision to SPIR-V precision decorations.
279spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600280{
John Kessenichf6640762016-08-01 19:44:00 -0600281 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700282 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600283 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
285 return spv::NoPrecision;
286 }
287}
288
John Kessenichf6640762016-08-01 19:44:00 -0600289// Translate glslang type to SPIR-V precision decorations.
290spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
291{
292 return TranslatePrecisionDecoration(type.getQualifier().precision);
293}
294
John Kessenich140f3df2015-06-26 16:58:36 -0600295// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600296spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
298 if (type.getBasicType() == glslang::EbtBlock) {
299 switch (type.getQualifier().storage) {
300 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600301 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 case glslang::EvqVaryingIn: return spv::DecorationBlock;
303 case glslang::EvqVaryingOut: return spv::DecorationBlock;
304 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700305 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600306 break;
307 }
308 }
309
John Kessenich4016e382016-07-15 11:53:56 -0600310 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600311}
312
Rex Xu1da878f2016-02-21 20:59:01 +0800313// Translate glslang type to SPIR-V memory decorations.
314void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
315{
316 if (qualifier.coherent)
317 memory.push_back(spv::DecorationCoherent);
318 if (qualifier.volatil)
319 memory.push_back(spv::DecorationVolatile);
320 if (qualifier.restrict)
321 memory.push_back(spv::DecorationRestrict);
322 if (qualifier.readonly)
323 memory.push_back(spv::DecorationNonWritable);
324 if (qualifier.writeonly)
325 memory.push_back(spv::DecorationNonReadable);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700329spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700332 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600333 case glslang::ElmRowMajor:
334 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700335 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 default:
338 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600339 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 }
341 } else {
342 switch (type.getBasicType()) {
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 break;
346 case glslang::EbtBlock:
347 switch (type.getQualifier().storage) {
348 case glslang::EvqUniform:
349 case glslang::EvqBuffer:
350 switch (type.getQualifier().layoutPacking) {
351 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
353 default:
John Kessenich4016e382016-07-15 11:53:56 -0600354 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600355 }
356 case glslang::EvqVaryingIn:
357 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700358 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700361 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 }
364 }
365 }
366}
367
368// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600369// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700370// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800371spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600372{
Rex Xubbceed72016-05-21 09:40:44 +0800373 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700374 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700377 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700378 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600379 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800380#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800381 else if (qualifier.explicitInterp) {
382 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800383 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800384 }
Rex Xu9d93a232016-05-05 12:30:44 +0800385#endif
Rex Xubbceed72016-05-21 09:40:44 +0800386 else
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388}
389
390// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600391// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800392// should be applied.
393spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
394{
395 if (qualifier.patch)
396 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700399 else if (qualifier.sample) {
400 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700402 } else
John Kessenich4016e382016-07-15 11:53:56 -0600403 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600404}
405
John Kessenich92187592016-02-01 13:45:25 -0700406// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600408{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationInvariant;
411 else
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600413}
414
qining9220dbb2016-05-04 17:34:38 -0400415// If glslang type is noContraction, return SPIR-V NoContraction decoration.
416spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
417{
418 if (qualifier.noContraction)
419 return spv::DecorationNoContraction;
420 else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400422}
423
David Netoa901ffe2016-06-08 14:11:40 +0100424// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
425// associated capabilities when required. For some built-in variables, a capability
426// is generated only when using the variable in an executable instruction, but not when
427// just declaring a struct member variable with it. This is true for PointSize,
428// ClipDistance, and CullDistance.
429spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600430{
431 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700432 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600433 // Defer adding the capability until the built-in is actually used.
434 if (! memberDeclaration) {
435 switch (glslangIntermediate->getStage()) {
436 case EShLangGeometry:
437 builder.addCapability(spv::CapabilityGeometryPointSize);
438 break;
439 case EShLangTessControl:
440 case EShLangTessEvaluation:
441 builder.addCapability(spv::CapabilityTessellationPointSize);
442 break;
443 default:
444 break;
445 }
John Kessenich92187592016-02-01 13:45:25 -0700446 }
447 return spv::BuiltInPointSize;
448
John Kessenichebb50532016-05-16 19:22:05 -0600449 // These *Distance capabilities logically belong here, but if the member is declared and
450 // then never used, consumers of SPIR-V prefer the capability not be declared.
451 // They are now generated when used, rather than here when declared.
452 // Potentially, the specification should be more clear what the minimum
453 // use needed is to trigger the capability.
454 //
John Kessenich92187592016-02-01 13:45:25 -0700455 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100456 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800457 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700458 return spv::BuiltInClipDistance;
459
460 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100461 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800462 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700463 return spv::BuiltInCullDistance;
464
465 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600466 builder.addCapability(spv::CapabilityMultiViewport);
467 if (glslangIntermediate->getStage() == EShLangVertex ||
468 glslangIntermediate->getStage() == EShLangTessControl ||
469 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800470
John Kessenichba6a3c22017-09-13 13:22:50 -0600471 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
472 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800473 }
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInViewportIndex;
475
John Kessenich5e801132016-02-15 11:09:46 -0700476 case glslang::EbvSampleId:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleId;
479
480 case glslang::EbvSamplePosition:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSamplePosition;
483
484 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700485 return spv::BuiltInSampleMask;
486
John Kessenich78a45572016-07-08 14:05:15 -0600487 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600488 builder.addCapability(spv::CapabilityGeometry);
489 if (glslangIntermediate->getStage() == EShLangVertex ||
490 glslangIntermediate->getStage() == EShLangTessControl ||
491 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800492
John Kessenichba6a3c22017-09-13 13:22:50 -0600493 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
494 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800495 }
John Kessenich78a45572016-07-08 14:05:15 -0600496 return spv::BuiltInLayer;
497
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvVertexId: return spv::BuiltInVertexId;
500 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700501 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
502 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800505 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
506 builder.addCapability(spv::CapabilityDrawParameters);
507 return spv::BuiltInBaseVertex;
508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
519 case glslang::EbvPrimitiveId:
520 if (glslangIntermediate->getStage() == EShLangFragment)
521 builder.addCapability(spv::CapabilityGeometry);
522 return spv::BuiltInPrimitiveId;
523
Rex Xu37cdcee2017-06-29 17:46:34 +0800524 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800525 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
526 builder.addCapability(spv::CapabilityStencilExportEXT);
527 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800528
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
531 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
532 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
533 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
534 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
535 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
536 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
538 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
539 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
540 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
541 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
542 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
543 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
544 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800545
Rex Xu574ab042016-04-14 16:53:07 +0800546 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800547 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800548 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
549 return spv::BuiltInSubgroupSize;
550
Rex Xu574ab042016-04-14 16:53:07 +0800551 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800552 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
554 return spv::BuiltInSubgroupLocalInvocationId;
555
Rex Xu574ab042016-04-14 16:53:07 +0800556 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800557 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
558 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
559 return spv::BuiltInSubgroupEqMaskKHR;
560
Rex Xu574ab042016-04-14 16:53:07 +0800561 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800562 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
563 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
564 return spv::BuiltInSubgroupGeMaskKHR;
565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupGtMaskKHR;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLeMaskKHR;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupLtMaskKHR;
580
Rex Xu9d93a232016-05-05 12:30:44 +0800581#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800582 case glslang::EbvBaryCoordNoPersp:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspAMD;
585
586 case glslang::EbvBaryCoordNoPerspCentroid:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
589
590 case glslang::EbvBaryCoordNoPerspSample:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordNoPerspSampleAMD;
593
594 case glslang::EbvBaryCoordSmooth:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothAMD;
597
598 case glslang::EbvBaryCoordSmoothCentroid:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothCentroidAMD;
601
602 case glslang::EbvBaryCoordSmoothSample:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordSmoothSampleAMD;
605
606 case glslang::EbvBaryCoordPullModel:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800609#endif
chaoc771d89f2017-01-13 01:10:53 -0800610
John Kessenich6c8aaac2017-02-27 01:20:51 -0700611 case glslang::EbvDeviceIndex:
612 builder.addExtension(spv::E_SPV_KHR_device_group);
613 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700614 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700615
616 case glslang::EbvViewIndex:
617 builder.addExtension(spv::E_SPV_KHR_multiview);
618 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700619 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700620
chaoc771d89f2017-01-13 01:10:53 -0800621#ifdef NV_EXTENSIONS
622 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800623 if (!memberDeclaration) {
624 builder.addExtension(spv::E_SPV_NV_viewport_array2);
625 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
626 }
chaoc771d89f2017-01-13 01:10:53 -0800627 return spv::BuiltInViewportMaskNV;
628 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800629 if (!memberDeclaration) {
630 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
631 builder.addCapability(spv::CapabilityShaderStereoViewNV);
632 }
chaoc771d89f2017-01-13 01:10:53 -0800633 return spv::BuiltInSecondaryPositionNV;
634 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800635 if (!memberDeclaration) {
636 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
637 builder.addCapability(spv::CapabilityShaderStereoViewNV);
638 }
chaoc771d89f2017-01-13 01:10:53 -0800639 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800640 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800641 if (!memberDeclaration) {
642 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
643 builder.addCapability(spv::CapabilityPerViewAttributesNV);
644 }
chaocdf3956c2017-02-14 14:52:34 -0800645 return spv::BuiltInPositionPerViewNV;
646 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800647 if (!memberDeclaration) {
648 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
649 builder.addCapability(spv::CapabilityPerViewAttributesNV);
650 }
chaocdf3956c2017-02-14 14:52:34 -0800651 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700652 case glslang::EbvFragFullyCoveredNV:
653 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
654 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
655 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800656#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800657 default:
658 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600659 }
660}
661
Rex Xufc618912015-09-09 16:42:49 +0800662// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700663spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800664{
665 assert(type.getBasicType() == glslang::EbtSampler);
666
John Kessenich5d0fa972016-02-15 11:57:00 -0700667 // Check for capabilities
668 switch (type.getQualifier().layoutFormat) {
669 case glslang::ElfRg32f:
670 case glslang::ElfRg16f:
671 case glslang::ElfR11fG11fB10f:
672 case glslang::ElfR16f:
673 case glslang::ElfRgba16:
674 case glslang::ElfRgb10A2:
675 case glslang::ElfRg16:
676 case glslang::ElfRg8:
677 case glslang::ElfR16:
678 case glslang::ElfR8:
679 case glslang::ElfRgba16Snorm:
680 case glslang::ElfRg16Snorm:
681 case glslang::ElfRg8Snorm:
682 case glslang::ElfR16Snorm:
683 case glslang::ElfR8Snorm:
684
685 case glslang::ElfRg32i:
686 case glslang::ElfRg16i:
687 case glslang::ElfRg8i:
688 case glslang::ElfR16i:
689 case glslang::ElfR8i:
690
691 case glslang::ElfRgb10a2ui:
692 case glslang::ElfRg32ui:
693 case glslang::ElfRg16ui:
694 case glslang::ElfRg8ui:
695 case glslang::ElfR16ui:
696 case glslang::ElfR8ui:
697 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
698 break;
699
700 default:
701 break;
702 }
703
704 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800705 switch (type.getQualifier().layoutFormat) {
706 case glslang::ElfNone: return spv::ImageFormatUnknown;
707 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
708 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
709 case glslang::ElfR32f: return spv::ImageFormatR32f;
710 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
711 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
712 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
713 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
714 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
715 case glslang::ElfR16f: return spv::ImageFormatR16f;
716 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
717 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
718 case glslang::ElfRg16: return spv::ImageFormatRg16;
719 case glslang::ElfRg8: return spv::ImageFormatRg8;
720 case glslang::ElfR16: return spv::ImageFormatR16;
721 case glslang::ElfR8: return spv::ImageFormatR8;
722 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
723 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
724 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
725 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
726 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
727 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
728 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
729 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
730 case glslang::ElfR32i: return spv::ImageFormatR32i;
731 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
732 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
733 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
734 case glslang::ElfR16i: return spv::ImageFormatR16i;
735 case glslang::ElfR8i: return spv::ImageFormatR8i;
736 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
737 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
738 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
739 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
740 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
741 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
742 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
743 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
744 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
745 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600746 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800747 }
748}
749
Rex Xu57e65922017-07-04 23:23:40 +0800750spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
751{
752 switch (selectionControl) {
753 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
754 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
755 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
756 default: return spv::SelectionControlMaskNone;
757 }
758}
759
steve-lunargf1709e72017-05-02 20:14:50 -0600760spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
761{
762 switch (loopControl) {
763 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
764 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
765 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
766 // TODO: DependencyInfinite
767 // TODO: DependencyLength
768 default: return spv::LoopControlMaskNone;
769 }
770}
771
John Kessenicha5c5fb62017-05-05 05:09:58 -0600772// Translate glslang type to SPIR-V storage class.
773spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
774{
775 if (type.getQualifier().isPipeInput())
776 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600777 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600778 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600779
780 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
781 type.getQualifier().storage == glslang::EvqUniform) {
782 if (type.getBasicType() == glslang::EbtAtomicUint)
783 return spv::StorageClassAtomicCounter;
784 if (type.containsOpaque())
785 return spv::StorageClassUniformConstant;
786 }
787
788 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600789 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
790 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600791 }
792
793 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600794 if (type.getQualifier().layoutPushConstant)
795 return spv::StorageClassPushConstant;
796 if (type.getBasicType() == glslang::EbtBlock)
797 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600798 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600799 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600800
801 switch (type.getQualifier().storage) {
802 case glslang::EvqShared: return spv::StorageClassWorkgroup;
803 case glslang::EvqGlobal: return spv::StorageClassPrivate;
804 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
805 case glslang::EvqTemporary: return spv::StorageClassFunction;
806 default:
807 assert(0);
808 break;
809 }
810
811 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600812}
813
qining25262b32016-05-06 17:25:16 -0400814// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700815// descriptor set.
816bool IsDescriptorResource(const glslang::TType& type)
817{
John Kessenichf7497e22016-03-08 21:36:22 -0700818 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700819 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700820 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700821
822 // non block...
823 // basically samplerXXX/subpass/sampler/texture are all included
824 // if they are the global-scope-class, not the function parameter
825 // (or local, if they ever exist) class.
826 if (type.getBasicType() == glslang::EbtSampler)
827 return type.getQualifier().isUniformOrBuffer();
828
829 // None of the above.
830 return false;
831}
832
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
834{
835 if (child.layoutMatrix == glslang::ElmNone)
836 child.layoutMatrix = parent.layoutMatrix;
837
838 if (parent.invariant)
839 child.invariant = true;
840 if (parent.nopersp)
841 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800842#ifdef AMD_EXTENSIONS
843 if (parent.explicitInterp)
844 child.explicitInterp = true;
845#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846 if (parent.flat)
847 child.flat = true;
848 if (parent.centroid)
849 child.centroid = true;
850 if (parent.patch)
851 child.patch = true;
852 if (parent.sample)
853 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800854 if (parent.coherent)
855 child.coherent = true;
856 if (parent.volatil)
857 child.volatil = true;
858 if (parent.restrict)
859 child.restrict = true;
860 if (parent.readonly)
861 child.readonly = true;
862 if (parent.writeonly)
863 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864}
865
John Kessenichf2b7f332016-09-01 17:05:23 -0600866bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700867{
John Kessenich7b9fa252016-01-21 18:56:57 -0700868 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600869 // - struct members might inherit from a struct declaration
870 // (note that non-block structs don't explicitly inherit,
871 // only implicitly, meaning no decoration involved)
872 // - affect decorations on the struct members
873 // (note smooth does not, and expecting something like volatile
874 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700875 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600876 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700877}
878
John Kessenich140f3df2015-06-26 16:58:36 -0600879//
880// Implement the TGlslangToSpvTraverser class.
881//
882
John Kessenich121853f2017-05-31 17:11:16 -0600883TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
884 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
885 : TIntermTraverser(true, false, true),
886 options(options),
887 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600888 sequenceDepth(0), logger(buildLogger),
John Kessenicha372a3e2017-11-02 22:32:14 -0600889 builder((glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700890 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600891 glslangIntermediate(glslangIntermediate)
892{
893 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
894
895 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600896 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
897 glslangIntermediate->getVersion());
898
John Kessenich121853f2017-05-31 17:11:16 -0600899 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600900 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600901 builder.setSourceFile(glslangIntermediate->getSourceFile());
902
903 // Set the source shader's text. If for SPV version 1.0, include
904 // a preamble in comments stating the OpModuleProcessed instructions.
905 // Otherwise, emit those as actual instructions.
906 std::string text;
907 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
908 for (int p = 0; p < (int)processes.size(); ++p) {
909 if (glslangIntermediate->getSpv().spv < 0x00010100) {
910 text.append("// OpModuleProcessed ");
911 text.append(processes[p]);
912 text.append("\n");
913 } else
914 builder.addModuleProcessed(processes[p]);
915 }
916 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
917 text.append("#line 1\n");
918 text.append(glslangIntermediate->getSourceText());
919 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600920 }
John Kessenich140f3df2015-06-26 16:58:36 -0600921 stdBuiltins = builder.import("GLSL.std.450");
922 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600923 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
924 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600925
926 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600927 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
928 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600929 builder.addSourceExtension(it->c_str());
930
931 // Add the top-level modes for this shader.
932
John Kessenich92187592016-02-01 13:45:25 -0700933 if (glslangIntermediate->getXfbMode()) {
934 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600935 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700936 }
John Kessenich140f3df2015-06-26 16:58:36 -0600937
938 unsigned int mode;
939 switch (glslangIntermediate->getStage()) {
940 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600941 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 break;
943
steve-lunarge7412492017-03-23 11:56:07 -0600944 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600945 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600946 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600947
steve-lunarge7412492017-03-23 11:56:07 -0600948 glslang::TLayoutGeometry primitive;
949
950 if (glslangIntermediate->getStage() == EShLangTessControl) {
951 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
952 primitive = glslangIntermediate->getOutputPrimitive();
953 } else {
954 primitive = glslangIntermediate->getInputPrimitive();
955 }
956
957 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700958 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
959 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
960 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600961 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600962 }
John Kessenich4016e382016-07-15 11:53:56 -0600963 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600964 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
965
John Kesseniche6903322015-10-13 16:29:02 -0600966 switch (glslangIntermediate->getVertexSpacing()) {
967 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
968 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
969 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600970 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600971 }
John Kessenich4016e382016-07-15 11:53:56 -0600972 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600973 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
974
975 switch (glslangIntermediate->getVertexOrder()) {
976 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
977 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600978 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600979 }
John Kessenich4016e382016-07-15 11:53:56 -0600980 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600981 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
982
983 if (glslangIntermediate->getPointMode())
984 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600985 break;
986
987 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600988 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600989 switch (glslangIntermediate->getInputPrimitive()) {
990 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
991 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
992 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700993 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600994 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600995 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600996 }
John Kessenich4016e382016-07-15 11:53:56 -0600997 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600998 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600999
John Kessenich140f3df2015-06-26 16:58:36 -06001000 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1001
1002 switch (glslangIntermediate->getOutputPrimitive()) {
1003 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1004 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1005 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001006 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001007 }
John Kessenich4016e382016-07-15 11:53:56 -06001008 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001009 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1010 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1011 break;
1012
1013 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001014 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001015 if (glslangIntermediate->getPixelCenterInteger())
1016 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001017
John Kessenich140f3df2015-06-26 16:58:36 -06001018 if (glslangIntermediate->getOriginUpperLeft())
1019 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001020 else
1021 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001022
1023 if (glslangIntermediate->getEarlyFragmentTests())
1024 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1025
chaocc1204522017-06-30 17:14:30 -07001026 if (glslangIntermediate->getPostDepthCoverage()) {
1027 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1028 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1029 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1030 }
1031
John Kesseniche6903322015-10-13 16:29:02 -06001032 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001033 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1034 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001035 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001036 }
John Kessenich4016e382016-07-15 11:53:56 -06001037 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001038 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1039
1040 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1041 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001042 break;
1043
1044 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001045 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001046 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1047 glslangIntermediate->getLocalSize(1),
1048 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001049 break;
1050
1051 default:
1052 break;
1053 }
John Kessenich140f3df2015-06-26 16:58:36 -06001054}
1055
John Kessenichfca82622016-11-26 13:23:20 -07001056// Finish creating SPV, after the traversal is complete.
1057void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001058{
John Kessenich517fe7a2016-11-26 13:31:47 -07001059 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001060 builder.setBuildPoint(shaderEntry->getLastBlock());
1061 builder.leaveFunction();
1062 }
1063
John Kessenich7ba63412015-12-20 17:37:07 -07001064 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001065 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1066 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001067
qiningda397332016-03-09 19:54:03 -05001068 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001069}
1070
John Kessenichfca82622016-11-26 13:23:20 -07001071// Write the SPV into 'out'.
1072void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001073{
John Kessenichfca82622016-11-26 13:23:20 -07001074 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001075}
1076
1077//
1078// Implement the traversal functions.
1079//
1080// Return true from interior nodes to have the external traversal
1081// continue on to children. Return false if children were
1082// already processed.
1083//
1084
1085//
qining25262b32016-05-06 17:25:16 -04001086// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001087// - uniform/input reads
1088// - output writes
1089// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1090// - something simple that degenerates into the last bullet
1091//
1092void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1093{
qining75d1d802016-04-06 14:42:01 -04001094 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1095 if (symbol->getType().getQualifier().isSpecConstant())
1096 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1097
John Kessenich140f3df2015-06-26 16:58:36 -06001098 // getSymbolId() will set up all the IO decorations on the first call.
1099 // Formal function parameters were mapped during makeFunctions().
1100 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001101
1102 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1103 if (builder.isPointer(id)) {
1104 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001105 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1106 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1107 iOSet.insert(id);
1108 }
John Kessenich7ba63412015-12-20 17:37:07 -07001109 }
1110
1111 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001112 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001113 // Prepare to generate code for the access
1114
1115 // L-value chains will be computed left to right. We're on the symbol now,
1116 // which is the left-most part of the access chain, so now is "clear" time,
1117 // followed by setting the base.
1118 builder.clearAccessChain();
1119
1120 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001121 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001122 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001123 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001124 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001125 // These are also pure R-values.
1126 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001127 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001128 builder.setAccessChainRValue(id);
1129 else
1130 builder.setAccessChainLValue(id);
1131 }
1132}
1133
1134bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1135{
John Kesseniche485c7a2017-05-31 18:50:53 -06001136 builder.setLine(node->getLoc().line);
1137
qining40887662016-04-03 22:20:42 -04001138 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1139 if (node->getType().getQualifier().isSpecConstant())
1140 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1141
John Kessenich140f3df2015-06-26 16:58:36 -06001142 // First, handle special cases
1143 switch (node->getOp()) {
1144 case glslang::EOpAssign:
1145 case glslang::EOpAddAssign:
1146 case glslang::EOpSubAssign:
1147 case glslang::EOpMulAssign:
1148 case glslang::EOpVectorTimesMatrixAssign:
1149 case glslang::EOpVectorTimesScalarAssign:
1150 case glslang::EOpMatrixTimesScalarAssign:
1151 case glslang::EOpMatrixTimesMatrixAssign:
1152 case glslang::EOpDivAssign:
1153 case glslang::EOpModAssign:
1154 case glslang::EOpAndAssign:
1155 case glslang::EOpInclusiveOrAssign:
1156 case glslang::EOpExclusiveOrAssign:
1157 case glslang::EOpLeftShiftAssign:
1158 case glslang::EOpRightShiftAssign:
1159 // A bin-op assign "a += b" means the same thing as "a = a + b"
1160 // where a is evaluated before b. For a simple assignment, GLSL
1161 // says to evaluate the left before the right. So, always, left
1162 // node then right node.
1163 {
1164 // get the left l-value, save it away
1165 builder.clearAccessChain();
1166 node->getLeft()->traverse(this);
1167 spv::Builder::AccessChain lValue = builder.getAccessChain();
1168
1169 // evaluate the right
1170 builder.clearAccessChain();
1171 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001172 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001173
1174 if (node->getOp() != glslang::EOpAssign) {
1175 // the left is also an r-value
1176 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001177 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001178
1179 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001180 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001181 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001182 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1183 node->getType().getBasicType());
1184
1185 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001186 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001187 }
1188
1189 // store the result
1190 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001191 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001192
1193 // assignments are expressions having an rValue after they are evaluated...
1194 builder.clearAccessChain();
1195 builder.setAccessChainRValue(rValue);
1196 }
1197 return false;
1198 case glslang::EOpIndexDirect:
1199 case glslang::EOpIndexDirectStruct:
1200 {
1201 // Get the left part of the access chain.
1202 node->getLeft()->traverse(this);
1203
1204 // Add the next element in the chain
1205
David Netoa901ffe2016-06-08 14:11:40 +01001206 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001207 if (! node->getLeft()->getType().isArray() &&
1208 node->getLeft()->getType().isVector() &&
1209 node->getOp() == glslang::EOpIndexDirect) {
1210 // This is essentially a hard-coded vector swizzle of size 1,
1211 // so short circuit the access-chain stuff with a swizzle.
1212 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001213 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001214 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001215 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001216 int spvIndex = glslangIndex;
1217 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1218 node->getOp() == glslang::EOpIndexDirectStruct)
1219 {
1220 // This may be, e.g., an anonymous block-member selection, which generally need
1221 // index remapping due to hidden members in anonymous blocks.
1222 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1223 assert(remapper.size() > 0);
1224 spvIndex = remapper[glslangIndex];
1225 }
John Kessenichebb50532016-05-16 19:22:05 -06001226
David Netoa901ffe2016-06-08 14:11:40 +01001227 // normal case for indexing array or structure or block
1228 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1229
1230 // Add capabilities here for accessing PointSize and clip/cull distance.
1231 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001232 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001233 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001234 }
1235 }
1236 return false;
1237 case glslang::EOpIndexIndirect:
1238 {
1239 // Structure or array or vector indirection.
1240 // Will use native SPIR-V access-chain for struct and array indirection;
1241 // matrices are arrays of vectors, so will also work for a matrix.
1242 // Will use the access chain's 'component' for variable index into a vector.
1243
1244 // This adapter is building access chains left to right.
1245 // Set up the access chain to the left.
1246 node->getLeft()->traverse(this);
1247
1248 // save it so that computing the right side doesn't trash it
1249 spv::Builder::AccessChain partial = builder.getAccessChain();
1250
1251 // compute the next index in the chain
1252 builder.clearAccessChain();
1253 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001254 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001255
1256 // restore the saved access chain
1257 builder.setAccessChain(partial);
1258
1259 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001260 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001261 else
John Kessenichfa668da2015-09-13 14:46:30 -06001262 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001263 }
1264 return false;
1265 case glslang::EOpVectorSwizzle:
1266 {
1267 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001268 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001269 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001270 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001271 }
1272 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001273 case glslang::EOpMatrixSwizzle:
1274 logger->missingFunctionality("matrix swizzle");
1275 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001276 case glslang::EOpLogicalOr:
1277 case glslang::EOpLogicalAnd:
1278 {
1279
1280 // These may require short circuiting, but can sometimes be done as straight
1281 // binary operations. The right operand must be short circuited if it has
1282 // side effects, and should probably be if it is complex.
1283 if (isTrivial(node->getRight()->getAsTyped()))
1284 break; // handle below as a normal binary operation
1285 // otherwise, we need to do dynamic short circuiting on the right operand
1286 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1287 builder.clearAccessChain();
1288 builder.setAccessChainRValue(result);
1289 }
1290 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001291 default:
1292 break;
1293 }
1294
1295 // Assume generic binary op...
1296
John Kessenich32cfd492016-02-02 12:37:46 -07001297 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001298 builder.clearAccessChain();
1299 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001300 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001301
John Kessenich32cfd492016-02-02 12:37:46 -07001302 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001303 builder.clearAccessChain();
1304 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001305 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001306
John Kessenich32cfd492016-02-02 12:37:46 -07001307 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001308 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001309 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001310 convertGlslangToSpvType(node->getType()), left, right,
1311 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001312
John Kessenich50e57562015-12-21 21:21:11 -07001313 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001314 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001315 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001316 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001317 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001318 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001319 return false;
1320 }
John Kessenich140f3df2015-06-26 16:58:36 -06001321}
1322
1323bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1324{
John Kesseniche485c7a2017-05-31 18:50:53 -06001325 builder.setLine(node->getLoc().line);
1326
qining40887662016-04-03 22:20:42 -04001327 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1328 if (node->getType().getQualifier().isSpecConstant())
1329 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1330
John Kessenichfc51d282015-08-19 13:34:18 -06001331 spv::Id result = spv::NoResult;
1332
1333 // try texturing first
1334 result = createImageTextureFunctionCall(node);
1335 if (result != spv::NoResult) {
1336 builder.clearAccessChain();
1337 builder.setAccessChainRValue(result);
1338
1339 return false; // done with this node
1340 }
1341
1342 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001343
1344 if (node->getOp() == glslang::EOpArrayLength) {
1345 // Quite special; won't want to evaluate the operand.
1346
1347 // Normal .length() would have been constant folded by the front-end.
1348 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001349 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001350 assert(node->getOperand()->getType().isRuntimeSizedArray());
1351 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1352 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001353 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1354 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001355
1356 builder.clearAccessChain();
1357 builder.setAccessChainRValue(length);
1358
1359 return false;
1360 }
1361
John Kessenichfc51d282015-08-19 13:34:18 -06001362 // Start by evaluating the operand
1363
John Kessenich8c8505c2016-07-26 12:50:38 -06001364 // Does it need a swizzle inversion? If so, evaluation is inverted;
1365 // operate first on the swizzle base, then apply the swizzle.
1366 spv::Id invertedType = spv::NoType;
1367 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1368 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1369 invertedType = getInvertedSwizzleType(*node->getOperand());
1370
John Kessenich140f3df2015-06-26 16:58:36 -06001371 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001372 if (invertedType != spv::NoType)
1373 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1374 else
1375 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001376
Rex Xufc618912015-09-09 16:42:49 +08001377 spv::Id operand = spv::NoResult;
1378
1379 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1380 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001381 node->getOp() == glslang::EOpAtomicCounter ||
1382 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001383 operand = builder.accessChainGetLValue(); // Special case l-value operands
1384 else
John Kessenich32cfd492016-02-02 12:37:46 -07001385 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001386
John Kessenichf6640762016-08-01 19:44:00 -06001387 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001388 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001389
1390 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001391 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001392 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001393
1394 // if not, then possibly an operation
1395 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001396 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001397
1398 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001399 if (invertedType)
1400 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1401
John Kessenich140f3df2015-06-26 16:58:36 -06001402 builder.clearAccessChain();
1403 builder.setAccessChainRValue(result);
1404
1405 return false; // done with this node
1406 }
1407
1408 // it must be a special case, check...
1409 switch (node->getOp()) {
1410 case glslang::EOpPostIncrement:
1411 case glslang::EOpPostDecrement:
1412 case glslang::EOpPreIncrement:
1413 case glslang::EOpPreDecrement:
1414 {
1415 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001416 spv::Id one = 0;
1417 if (node->getBasicType() == glslang::EbtFloat)
1418 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001419 else if (node->getBasicType() == glslang::EbtDouble)
1420 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001421#ifdef AMD_EXTENSIONS
1422 else if (node->getBasicType() == glslang::EbtFloat16)
1423 one = builder.makeFloat16Constant(1.0F);
1424#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001425 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1426 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001427#ifdef AMD_EXTENSIONS
1428 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1429 one = builder.makeInt16Constant(1);
1430#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001431 else
1432 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 glslang::TOperator op;
1434 if (node->getOp() == glslang::EOpPreIncrement ||
1435 node->getOp() == glslang::EOpPostIncrement)
1436 op = glslang::EOpAdd;
1437 else
1438 op = glslang::EOpSub;
1439
John Kessenichf6640762016-08-01 19:44:00 -06001440 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001441 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001442 convertGlslangToSpvType(node->getType()), operand, one,
1443 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001444 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001445
1446 // The result of operation is always stored, but conditionally the
1447 // consumed result. The consumed result is always an r-value.
1448 builder.accessChainStore(result);
1449 builder.clearAccessChain();
1450 if (node->getOp() == glslang::EOpPreIncrement ||
1451 node->getOp() == glslang::EOpPreDecrement)
1452 builder.setAccessChainRValue(result);
1453 else
1454 builder.setAccessChainRValue(operand);
1455 }
1456
1457 return false;
1458
1459 case glslang::EOpEmitStreamVertex:
1460 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1461 return false;
1462 case glslang::EOpEndStreamPrimitive:
1463 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1464 return false;
1465
1466 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001467 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001468 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001469 }
John Kessenich140f3df2015-06-26 16:58:36 -06001470}
1471
1472bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1473{
qining27e04a02016-04-14 16:40:20 -04001474 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1475 if (node->getType().getQualifier().isSpecConstant())
1476 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1477
John Kessenichfc51d282015-08-19 13:34:18 -06001478 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001479 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1480 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001481
1482 // try texturing
1483 result = createImageTextureFunctionCall(node);
1484 if (result != spv::NoResult) {
1485 builder.clearAccessChain();
1486 builder.setAccessChainRValue(result);
1487
1488 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001489#ifdef AMD_EXTENSIONS
1490 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1491#else
John Kessenich56bab042015-09-16 10:54:31 -06001492 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001493#endif
Rex Xufc618912015-09-09 16:42:49 +08001494 // "imageStore" is a special case, which has no result
1495 return false;
1496 }
John Kessenichfc51d282015-08-19 13:34:18 -06001497
John Kessenich140f3df2015-06-26 16:58:36 -06001498 glslang::TOperator binOp = glslang::EOpNull;
1499 bool reduceComparison = true;
1500 bool isMatrix = false;
1501 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001502 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 assert(node->getOp());
1505
John Kessenichf6640762016-08-01 19:44:00 -06001506 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001507
1508 switch (node->getOp()) {
1509 case glslang::EOpSequence:
1510 {
1511 if (preVisit)
1512 ++sequenceDepth;
1513 else
1514 --sequenceDepth;
1515
1516 if (sequenceDepth == 1) {
1517 // If this is the parent node of all the functions, we want to see them
1518 // early, so all call points have actual SPIR-V functions to reference.
1519 // In all cases, still let the traverser visit the children for us.
1520 makeFunctions(node->getAsAggregate()->getSequence());
1521
John Kessenich6fccb3c2016-09-19 16:01:41 -06001522 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001523 // anything else gets there, so visit out of order, doing them all now.
1524 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1525
John Kessenich6a60c2f2016-12-08 21:01:59 -07001526 // 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 -06001527 // so do them manually.
1528 visitFunctions(node->getAsAggregate()->getSequence());
1529
1530 return false;
1531 }
1532
1533 return true;
1534 }
1535 case glslang::EOpLinkerObjects:
1536 {
1537 if (visit == glslang::EvPreVisit)
1538 linkageOnly = true;
1539 else
1540 linkageOnly = false;
1541
1542 return true;
1543 }
1544 case glslang::EOpComma:
1545 {
1546 // processing from left to right naturally leaves the right-most
1547 // lying around in the access chain
1548 glslang::TIntermSequence& glslangOperands = node->getSequence();
1549 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1550 glslangOperands[i]->traverse(this);
1551
1552 return false;
1553 }
1554 case glslang::EOpFunction:
1555 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001556 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001557 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001558 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001559 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001560 } else {
1561 handleFunctionEntry(node);
1562 }
1563 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001564 if (inEntryPoint)
1565 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001566 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001567 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001568 }
1569
1570 return true;
1571 case glslang::EOpParameters:
1572 // Parameters will have been consumed by EOpFunction processing, but not
1573 // the body, so we still visited the function node's children, making this
1574 // child redundant.
1575 return false;
1576 case glslang::EOpFunctionCall:
1577 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001578 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001579 if (node->isUserDefined())
1580 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001581 // 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 -07001582 if (result) {
1583 builder.clearAccessChain();
1584 builder.setAccessChainRValue(result);
1585 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001586 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001587
1588 return false;
1589 }
1590 case glslang::EOpConstructMat2x2:
1591 case glslang::EOpConstructMat2x3:
1592 case glslang::EOpConstructMat2x4:
1593 case glslang::EOpConstructMat3x2:
1594 case glslang::EOpConstructMat3x3:
1595 case glslang::EOpConstructMat3x4:
1596 case glslang::EOpConstructMat4x2:
1597 case glslang::EOpConstructMat4x3:
1598 case glslang::EOpConstructMat4x4:
1599 case glslang::EOpConstructDMat2x2:
1600 case glslang::EOpConstructDMat2x3:
1601 case glslang::EOpConstructDMat2x4:
1602 case glslang::EOpConstructDMat3x2:
1603 case glslang::EOpConstructDMat3x3:
1604 case glslang::EOpConstructDMat3x4:
1605 case glslang::EOpConstructDMat4x2:
1606 case glslang::EOpConstructDMat4x3:
1607 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001608 case glslang::EOpConstructIMat2x2:
1609 case glslang::EOpConstructIMat2x3:
1610 case glslang::EOpConstructIMat2x4:
1611 case glslang::EOpConstructIMat3x2:
1612 case glslang::EOpConstructIMat3x3:
1613 case glslang::EOpConstructIMat3x4:
1614 case glslang::EOpConstructIMat4x2:
1615 case glslang::EOpConstructIMat4x3:
1616 case glslang::EOpConstructIMat4x4:
1617 case glslang::EOpConstructUMat2x2:
1618 case glslang::EOpConstructUMat2x3:
1619 case glslang::EOpConstructUMat2x4:
1620 case glslang::EOpConstructUMat3x2:
1621 case glslang::EOpConstructUMat3x3:
1622 case glslang::EOpConstructUMat3x4:
1623 case glslang::EOpConstructUMat4x2:
1624 case glslang::EOpConstructUMat4x3:
1625 case glslang::EOpConstructUMat4x4:
1626 case glslang::EOpConstructBMat2x2:
1627 case glslang::EOpConstructBMat2x3:
1628 case glslang::EOpConstructBMat2x4:
1629 case glslang::EOpConstructBMat3x2:
1630 case glslang::EOpConstructBMat3x3:
1631 case glslang::EOpConstructBMat3x4:
1632 case glslang::EOpConstructBMat4x2:
1633 case glslang::EOpConstructBMat4x3:
1634 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001635#ifdef AMD_EXTENSIONS
1636 case glslang::EOpConstructF16Mat2x2:
1637 case glslang::EOpConstructF16Mat2x3:
1638 case glslang::EOpConstructF16Mat2x4:
1639 case glslang::EOpConstructF16Mat3x2:
1640 case glslang::EOpConstructF16Mat3x3:
1641 case glslang::EOpConstructF16Mat3x4:
1642 case glslang::EOpConstructF16Mat4x2:
1643 case glslang::EOpConstructF16Mat4x3:
1644 case glslang::EOpConstructF16Mat4x4:
1645#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001646 isMatrix = true;
1647 // fall through
1648 case glslang::EOpConstructFloat:
1649 case glslang::EOpConstructVec2:
1650 case glslang::EOpConstructVec3:
1651 case glslang::EOpConstructVec4:
1652 case glslang::EOpConstructDouble:
1653 case glslang::EOpConstructDVec2:
1654 case glslang::EOpConstructDVec3:
1655 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001656#ifdef AMD_EXTENSIONS
1657 case glslang::EOpConstructFloat16:
1658 case glslang::EOpConstructF16Vec2:
1659 case glslang::EOpConstructF16Vec3:
1660 case glslang::EOpConstructF16Vec4:
1661#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001662 case glslang::EOpConstructBool:
1663 case glslang::EOpConstructBVec2:
1664 case glslang::EOpConstructBVec3:
1665 case glslang::EOpConstructBVec4:
1666 case glslang::EOpConstructInt:
1667 case glslang::EOpConstructIVec2:
1668 case glslang::EOpConstructIVec3:
1669 case glslang::EOpConstructIVec4:
1670 case glslang::EOpConstructUint:
1671 case glslang::EOpConstructUVec2:
1672 case glslang::EOpConstructUVec3:
1673 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001674 case glslang::EOpConstructInt64:
1675 case glslang::EOpConstructI64Vec2:
1676 case glslang::EOpConstructI64Vec3:
1677 case glslang::EOpConstructI64Vec4:
1678 case glslang::EOpConstructUint64:
1679 case glslang::EOpConstructU64Vec2:
1680 case glslang::EOpConstructU64Vec3:
1681 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001682#ifdef AMD_EXTENSIONS
1683 case glslang::EOpConstructInt16:
1684 case glslang::EOpConstructI16Vec2:
1685 case glslang::EOpConstructI16Vec3:
1686 case glslang::EOpConstructI16Vec4:
1687 case glslang::EOpConstructUint16:
1688 case glslang::EOpConstructU16Vec2:
1689 case glslang::EOpConstructU16Vec3:
1690 case glslang::EOpConstructU16Vec4:
1691#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001692 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001693 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001694 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001695 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001696 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001697 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001698 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001699 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001701 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001702 std::vector<spv::Id> constituents;
1703 for (int c = 0; c < (int)arguments.size(); ++c)
1704 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001706 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001707 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001708 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001709 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001710
1711 builder.clearAccessChain();
1712 builder.setAccessChainRValue(constructed);
1713
1714 return false;
1715 }
1716
1717 // These six are component-wise compares with component-wise results.
1718 // Forward on to createBinaryOperation(), requesting a vector result.
1719 case glslang::EOpLessThan:
1720 case glslang::EOpGreaterThan:
1721 case glslang::EOpLessThanEqual:
1722 case glslang::EOpGreaterThanEqual:
1723 case glslang::EOpVectorEqual:
1724 case glslang::EOpVectorNotEqual:
1725 {
1726 // Map the operation to a binary
1727 binOp = node->getOp();
1728 reduceComparison = false;
1729 switch (node->getOp()) {
1730 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1731 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1732 default: binOp = node->getOp(); break;
1733 }
1734
1735 break;
1736 }
1737 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001738 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001739 binOp = glslang::EOpMul;
1740 break;
1741 case glslang::EOpOuterProduct:
1742 // two vectors multiplied to make a matrix
1743 binOp = glslang::EOpOuterProduct;
1744 break;
1745 case glslang::EOpDot:
1746 {
qining25262b32016-05-06 17:25:16 -04001747 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001748 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001749 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001750 binOp = glslang::EOpMul;
1751 break;
1752 }
1753 case glslang::EOpMod:
1754 // when an aggregate, this is the floating-point mod built-in function,
1755 // which can be emitted by the one in createBinaryOperation()
1756 binOp = glslang::EOpMod;
1757 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001758 case glslang::EOpEmitVertex:
1759 case glslang::EOpEndPrimitive:
1760 case glslang::EOpBarrier:
1761 case glslang::EOpMemoryBarrier:
1762 case glslang::EOpMemoryBarrierAtomicCounter:
1763 case glslang::EOpMemoryBarrierBuffer:
1764 case glslang::EOpMemoryBarrierImage:
1765 case glslang::EOpMemoryBarrierShared:
1766 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001767 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001768 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001769 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001770 case glslang::EOpWorkgroupMemoryBarrier:
1771 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001772 noReturnValue = true;
1773 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1774 break;
1775
John Kessenich426394d2015-07-23 10:22:48 -06001776 case glslang::EOpAtomicAdd:
1777 case glslang::EOpAtomicMin:
1778 case glslang::EOpAtomicMax:
1779 case glslang::EOpAtomicAnd:
1780 case glslang::EOpAtomicOr:
1781 case glslang::EOpAtomicXor:
1782 case glslang::EOpAtomicExchange:
1783 case glslang::EOpAtomicCompSwap:
1784 atomic = true;
1785 break;
1786
John Kessenich0d0c6d32017-07-23 16:08:26 -06001787 case glslang::EOpAtomicCounterAdd:
1788 case glslang::EOpAtomicCounterSubtract:
1789 case glslang::EOpAtomicCounterMin:
1790 case glslang::EOpAtomicCounterMax:
1791 case glslang::EOpAtomicCounterAnd:
1792 case glslang::EOpAtomicCounterOr:
1793 case glslang::EOpAtomicCounterXor:
1794 case glslang::EOpAtomicCounterExchange:
1795 case glslang::EOpAtomicCounterCompSwap:
1796 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1797 builder.addCapability(spv::CapabilityAtomicStorageOps);
1798 atomic = true;
1799 break;
1800
John Kessenich140f3df2015-06-26 16:58:36 -06001801 default:
1802 break;
1803 }
1804
1805 //
1806 // See if it maps to a regular operation.
1807 //
John Kessenich140f3df2015-06-26 16:58:36 -06001808 if (binOp != glslang::EOpNull) {
1809 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1810 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1811 assert(left && right);
1812
1813 builder.clearAccessChain();
1814 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001815 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001816
1817 builder.clearAccessChain();
1818 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001819 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001820
John Kesseniche485c7a2017-05-31 18:50:53 -06001821 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001822 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001823 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001824 left->getType().getBasicType(), reduceComparison);
1825
1826 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001827 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001828 builder.clearAccessChain();
1829 builder.setAccessChainRValue(result);
1830
1831 return false;
1832 }
1833
John Kessenich426394d2015-07-23 10:22:48 -06001834 //
1835 // Create the list of operands.
1836 //
John Kessenich140f3df2015-06-26 16:58:36 -06001837 glslang::TIntermSequence& glslangOperands = node->getSequence();
1838 std::vector<spv::Id> operands;
1839 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001840 // special case l-value operands; there are just a few
1841 bool lvalue = false;
1842 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001843 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001844 case glslang::EOpModf:
1845 if (arg == 1)
1846 lvalue = true;
1847 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001848 case glslang::EOpInterpolateAtSample:
1849 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001850#ifdef AMD_EXTENSIONS
1851 case glslang::EOpInterpolateAtVertex:
1852#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001853 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001854 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001855
1856 // Does it need a swizzle inversion? If so, evaluation is inverted;
1857 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001858 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001859 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1860 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1861 }
Rex Xu7a26c172015-12-08 17:12:09 +08001862 break;
Rex Xud4782c12015-09-06 16:30:11 +08001863 case glslang::EOpAtomicAdd:
1864 case glslang::EOpAtomicMin:
1865 case glslang::EOpAtomicMax:
1866 case glslang::EOpAtomicAnd:
1867 case glslang::EOpAtomicOr:
1868 case glslang::EOpAtomicXor:
1869 case glslang::EOpAtomicExchange:
1870 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001871 case glslang::EOpAtomicCounterAdd:
1872 case glslang::EOpAtomicCounterSubtract:
1873 case glslang::EOpAtomicCounterMin:
1874 case glslang::EOpAtomicCounterMax:
1875 case glslang::EOpAtomicCounterAnd:
1876 case glslang::EOpAtomicCounterOr:
1877 case glslang::EOpAtomicCounterXor:
1878 case glslang::EOpAtomicCounterExchange:
1879 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001880 if (arg == 0)
1881 lvalue = true;
1882 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001883 case glslang::EOpAddCarry:
1884 case glslang::EOpSubBorrow:
1885 if (arg == 2)
1886 lvalue = true;
1887 break;
1888 case glslang::EOpUMulExtended:
1889 case glslang::EOpIMulExtended:
1890 if (arg >= 2)
1891 lvalue = true;
1892 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001893 default:
1894 break;
1895 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001896 builder.clearAccessChain();
1897 if (invertedType != spv::NoType && arg == 0)
1898 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1899 else
1900 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001901 if (lvalue)
1902 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001903 else {
1904 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001905 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001906 }
John Kessenich140f3df2015-06-26 16:58:36 -06001907 }
John Kessenich426394d2015-07-23 10:22:48 -06001908
John Kesseniche485c7a2017-05-31 18:50:53 -06001909 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001910 if (atomic) {
1911 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001912 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001913 } else {
1914 // Pass through to generic operations.
1915 switch (glslangOperands.size()) {
1916 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001917 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001918 break;
1919 case 1:
qining25262b32016-05-06 17:25:16 -04001920 result = createUnaryOperation(
1921 node->getOp(), precision,
1922 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001923 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001924 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001925 break;
1926 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001927 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001928 break;
1929 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001930 if (invertedType)
1931 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001932 }
1933
1934 if (noReturnValue)
1935 return false;
1936
1937 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001938 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001939 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001940 } else {
1941 builder.clearAccessChain();
1942 builder.setAccessChainRValue(result);
1943 return false;
1944 }
1945}
1946
John Kessenich433e9ff2017-01-26 20:31:11 -07001947// This path handles both if-then-else and ?:
1948// The if-then-else has a node type of void, while
1949// ?: has either a void or a non-void node type
1950//
1951// Leaving the result, when not void:
1952// GLSL only has r-values as the result of a :?, but
1953// if we have an l-value, that can be more efficient if it will
1954// become the base of a complex r-value expression, because the
1955// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001956bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1957{
John Kessenich433e9ff2017-01-26 20:31:11 -07001958 // See if it simple and safe to generate OpSelect instead of using control flow.
1959 // Crucially, side effects must be avoided, and there are performance trade-offs.
1960 // Return true if good idea (and safe) for OpSelect, false otherwise.
1961 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001962 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1963 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001964 return false;
1965
1966 if (node->getTrueBlock() == nullptr ||
1967 node->getFalseBlock() == nullptr)
1968 return false;
1969
1970 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1971 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1972
1973 // return true if a single operand to ? : is okay for OpSelect
1974 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001975 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001976 };
1977
1978 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1979 operandOkay(node->getFalseBlock()->getAsTyped());
1980 };
1981
1982 // Emit OpSelect for this selection.
1983 const auto handleAsOpSelect = [&]() {
1984 node->getCondition()->traverse(this);
1985 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1986 node->getTrueBlock()->traverse(this);
1987 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1988 node->getFalseBlock()->traverse(this);
1989 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1990
John Kesseniche485c7a2017-05-31 18:50:53 -06001991 builder.setLine(node->getLoc().line);
1992
John Kesseniche434ad92017-03-30 10:09:28 -06001993 // smear condition to vector, if necessary (AST is always scalar)
1994 if (builder.isVector(trueValue))
1995 condition = builder.smearScalar(spv::NoPrecision, condition,
1996 builder.makeVectorType(builder.makeBoolType(),
1997 builder.getNumComponents(trueValue)));
1998
1999 spv::Id select = builder.createTriOp(spv::OpSelect,
2000 convertGlslangToSpvType(node->getType()), condition,
2001 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002002 builder.clearAccessChain();
2003 builder.setAccessChainRValue(select);
2004 };
2005
2006 // Try for OpSelect
2007
2008 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002009 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2010 if (node->getType().getQualifier().isSpecConstant())
2011 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2012
John Kessenich433e9ff2017-01-26 20:31:11 -07002013 handleAsOpSelect();
2014 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002015 }
2016
Rex Xu57e65922017-07-04 23:23:40 +08002017 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002018 // Don't handle results as temporaries, because there will be two names
2019 // and better to leave SSA to later passes.
2020 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2021 ? spv::NoResult
2022 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2023
John Kessenich140f3df2015-06-26 16:58:36 -06002024 // emit the condition before doing anything with selection
2025 node->getCondition()->traverse(this);
2026
Rex Xu57e65922017-07-04 23:23:40 +08002027 // Selection control:
2028 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2029
John Kessenich140f3df2015-06-26 16:58:36 -06002030 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002031 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002032
John Kessenich433e9ff2017-01-26 20:31:11 -07002033 // emit the "then" statement
2034 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002035 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002036 if (result != spv::NoResult)
2037 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002038 }
2039
John Kessenich433e9ff2017-01-26 20:31:11 -07002040 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002041 ifBuilder.makeBeginElse();
2042 // emit the "else" statement
2043 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002044 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002045 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002046 }
2047
John Kessenich433e9ff2017-01-26 20:31:11 -07002048 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002049 ifBuilder.makeEndIf();
2050
John Kessenich433e9ff2017-01-26 20:31:11 -07002051 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002052 // GLSL only has r-values as the result of a :?, but
2053 // if we have an l-value, that can be more efficient if it will
2054 // become the base of a complex r-value expression, because the
2055 // next layer copies r-values into memory to use the access-chain mechanism
2056 builder.clearAccessChain();
2057 builder.setAccessChainLValue(result);
2058 }
2059
2060 return false;
2061}
2062
2063bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2064{
2065 // emit and get the condition before doing anything with switch
2066 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002067 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002068
Rex Xu57e65922017-07-04 23:23:40 +08002069 // Selection control:
2070 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2071
John Kessenich140f3df2015-06-26 16:58:36 -06002072 // browse the children to sort out code segments
2073 int defaultSegment = -1;
2074 std::vector<TIntermNode*> codeSegments;
2075 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2076 std::vector<int> caseValues;
2077 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2078 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2079 TIntermNode* child = *c;
2080 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002081 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002082 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002083 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002084 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2085 } else
2086 codeSegments.push_back(child);
2087 }
2088
qining25262b32016-05-06 17:25:16 -04002089 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002090 // statements between the last case and the end of the switch statement
2091 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2092 (int)codeSegments.size() == defaultSegment)
2093 codeSegments.push_back(nullptr);
2094
2095 // make the switch statement
2096 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002097 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002098
2099 // emit all the code in the segments
2100 breakForLoop.push(false);
2101 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2102 builder.nextSwitchSegment(segmentBlocks, s);
2103 if (codeSegments[s])
2104 codeSegments[s]->traverse(this);
2105 else
2106 builder.addSwitchBreak();
2107 }
2108 breakForLoop.pop();
2109
2110 builder.endSwitch(segmentBlocks);
2111
2112 return false;
2113}
2114
2115void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2116{
2117 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002118 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002119
2120 builder.clearAccessChain();
2121 builder.setAccessChainRValue(constant);
2122}
2123
2124bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2125{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002126 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002127 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002128
2129 // Loop control:
2130 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2131
2132 // TODO: dependency length
2133
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002134 // Spec requires back edges to target header blocks, and every header block
2135 // must dominate its merge block. Make a header block first to ensure these
2136 // conditions are met. By definition, it will contain OpLoopMerge, followed
2137 // by a block-ending branch. But we don't want to put any other body/test
2138 // instructions in it, since the body/test may have arbitrary instructions,
2139 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002140 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002141 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002142 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002143 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002144 spv::Block& test = builder.makeNewBlock();
2145 builder.createBranch(&test);
2146
2147 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002148 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002149 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002150 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2151
2152 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002153 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002155 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002156 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002157 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002158
2159 builder.setBuildPoint(&blocks.continue_target);
2160 if (node->getTerminal())
2161 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002162 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002163 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002164 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002165 builder.createBranch(&blocks.body);
2166
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002167 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002168 builder.setBuildPoint(&blocks.body);
2169 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002170 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002171 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002172 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002173
2174 builder.setBuildPoint(&blocks.continue_target);
2175 if (node->getTerminal())
2176 node->getTerminal()->traverse(this);
2177 if (node->getTest()) {
2178 node->getTest()->traverse(this);
2179 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002180 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002181 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002182 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002183 // TODO: unless there was a break/return/discard instruction
2184 // somewhere in the body, this is an infinite loop, so we should
2185 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002186 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002187 }
John Kessenich140f3df2015-06-26 16:58:36 -06002188 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002189 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002190 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002191 return false;
2192}
2193
2194bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2195{
2196 if (node->getExpression())
2197 node->getExpression()->traverse(this);
2198
John Kesseniche485c7a2017-05-31 18:50:53 -06002199 builder.setLine(node->getLoc().line);
2200
John Kessenich140f3df2015-06-26 16:58:36 -06002201 switch (node->getFlowOp()) {
2202 case glslang::EOpKill:
2203 builder.makeDiscard();
2204 break;
2205 case glslang::EOpBreak:
2206 if (breakForLoop.top())
2207 builder.createLoopExit();
2208 else
2209 builder.addSwitchBreak();
2210 break;
2211 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002212 builder.createLoopContinue();
2213 break;
2214 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002215 if (node->getExpression()) {
2216 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2217 spv::Id returnId = accessChainLoad(glslangReturnType);
2218 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2219 builder.clearAccessChain();
2220 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2221 builder.setAccessChainLValue(copyId);
2222 multiTypeStore(glslangReturnType, returnId);
2223 returnId = builder.createLoad(copyId);
2224 }
2225 builder.makeReturn(false, returnId);
2226 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002227 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002228
2229 builder.clearAccessChain();
2230 break;
2231
2232 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002233 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002234 break;
2235 }
2236
2237 return false;
2238}
2239
2240spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2241{
qining25262b32016-05-06 17:25:16 -04002242 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002243 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002244 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002245 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002246 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002247 }
2248
2249 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002250 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002251 spv::Id spvType = convertGlslangToSpvType(node->getType());
2252
Rex Xuf89ad982017-04-07 23:22:33 +08002253#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002254 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2255 node->getType().containsBasicType(glslang::EbtInt16) ||
2256 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002257 if (contains16BitType) {
2258 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2259 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2260 builder.addCapability(spv::CapabilityStorageInputOutput16);
2261 } else if (storageClass == spv::StorageClassPushConstant) {
2262 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2263 builder.addCapability(spv::CapabilityStoragePushConstant16);
2264 } else if (storageClass == spv::StorageClassUniform) {
2265 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2266 builder.addCapability(spv::CapabilityStorageUniform16);
2267 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2268 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2269 }
2270 }
2271#endif
2272
John Kessenich140f3df2015-06-26 16:58:36 -06002273 const char* name = node->getName().c_str();
2274 if (glslang::IsAnonymous(name))
2275 name = "";
2276
2277 return builder.createVariable(storageClass, spvType, name);
2278}
2279
2280// Return type Id of the sampled type.
2281spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2282{
2283 switch (sampler.type) {
2284 case glslang::EbtFloat: return builder.makeFloatType(32);
2285 case glslang::EbtInt: return builder.makeIntType(32);
2286 case glslang::EbtUint: return builder.makeUintType(32);
2287 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002288 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002289 return builder.makeFloatType(32);
2290 }
2291}
2292
John Kessenich8c8505c2016-07-26 12:50:38 -06002293// If node is a swizzle operation, return the type that should be used if
2294// the swizzle base is first consumed by another operation, before the swizzle
2295// is applied.
2296spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2297{
John Kessenichecba76f2017-01-06 00:34:48 -07002298 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002299 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2300 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2301 else
2302 return spv::NoType;
2303}
2304
2305// When inverting a swizzle with a parent op, this function
2306// will apply the swizzle operation to a completed parent operation.
2307spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2308{
2309 std::vector<unsigned> swizzle;
2310 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2311 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2312}
2313
John Kessenich8c8505c2016-07-26 12:50:38 -06002314// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2315void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2316{
2317 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2318 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2319 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2320}
2321
John Kessenich3ac051e2015-12-20 11:29:16 -07002322// Convert from a glslang type to an SPV type, by calling into a
2323// recursive version of this function. This establishes the inherited
2324// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002325spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2326{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002327 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002328}
2329
2330// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002331// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002332// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002333spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002334{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002335 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002336
2337 switch (type.getBasicType()) {
2338 case glslang::EbtVoid:
2339 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002340 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002341 break;
2342 case glslang::EbtFloat:
2343 spvType = builder.makeFloatType(32);
2344 break;
2345 case glslang::EbtDouble:
2346 spvType = builder.makeFloatType(64);
2347 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002348#ifdef AMD_EXTENSIONS
2349 case glslang::EbtFloat16:
2350 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002351 spvType = builder.makeFloatType(16);
2352 break;
2353#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002354 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002355 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2356 // a 32-bit int where non-0 means true.
2357 if (explicitLayout != glslang::ElpNone)
2358 spvType = builder.makeUintType(32);
2359 else
2360 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002361 break;
2362 case glslang::EbtInt:
2363 spvType = builder.makeIntType(32);
2364 break;
2365 case glslang::EbtUint:
2366 spvType = builder.makeUintType(32);
2367 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002368 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002369 spvType = builder.makeIntType(64);
2370 break;
2371 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002372 spvType = builder.makeUintType(64);
2373 break;
Rex Xucabbb782017-03-24 13:41:14 +08002374#ifdef AMD_EXTENSIONS
2375 case glslang::EbtInt16:
2376 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2377 spvType = builder.makeIntType(16);
2378 break;
2379 case glslang::EbtUint16:
2380 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2381 spvType = builder.makeUintType(16);
2382 break;
2383#endif
John Kessenich426394d2015-07-23 10:22:48 -06002384 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002385 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002386 spvType = builder.makeUintType(32);
2387 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002388 case glslang::EbtSampler:
2389 {
2390 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002391 if (sampler.sampler) {
2392 // pure sampler
2393 spvType = builder.makeSamplerType();
2394 } else {
2395 // an image is present, make its type
2396 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2397 sampler.image ? 2 : 1, TranslateImageFormat(type));
2398 if (sampler.combined) {
2399 // already has both image and sampler, make the combined type
2400 spvType = builder.makeSampledImageType(spvType);
2401 }
John Kessenich55e7d112015-11-15 21:33:39 -07002402 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002403 }
John Kessenich140f3df2015-06-26 16:58:36 -06002404 break;
2405 case glslang::EbtStruct:
2406 case glslang::EbtBlock:
2407 {
2408 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002409 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002410
2411 // Try to share structs for different layouts, but not yet for other
2412 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002413 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002414 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002415 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002416 break;
2417
2418 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002419 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002420 memberRemapper[glslangMembers].resize(glslangMembers->size());
2421 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002422 }
2423 break;
2424 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002425 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002426 break;
2427 }
2428
2429 if (type.isMatrix())
2430 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2431 else {
2432 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2433 if (type.getVectorSize() > 1)
2434 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2435 }
2436
2437 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002438 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2439
John Kessenichc9a80832015-09-12 12:17:44 -06002440 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002441 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002442 // We need to decorate array strides for types needing explicit layout, except blocks.
2443 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002444 // Use a dummy glslang type for querying internal strides of
2445 // arrays of arrays, but using just a one-dimensional array.
2446 glslang::TType simpleArrayType(type, 0); // deference type of the array
2447 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2448 simpleArrayType.getArraySizes().dereference();
2449
2450 // Will compute the higher-order strides here, rather than making a whole
2451 // pile of types and doing repetitive recursion on their contents.
2452 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2453 }
John Kessenichf8842e52016-01-04 19:22:56 -07002454
2455 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002456 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002457 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 if (stride > 0)
2459 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002460 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002461 }
2462 } else {
2463 // single-dimensional array, and don't yet have stride
2464
John Kessenichf8842e52016-01-04 19:22:56 -07002465 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002466 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2467 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002468 }
John Kessenich31ed4832015-09-09 17:51:38 -06002469
John Kessenichc9a80832015-09-12 12:17:44 -06002470 // Do the outer dimension, which might not be known for a runtime-sized array
2471 if (type.isRuntimeSizedArray()) {
2472 spvType = builder.makeRuntimeArray(spvType);
2473 } else {
2474 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002475 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002476 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002477 if (stride > 0)
2478 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002479 }
2480
2481 return spvType;
2482}
2483
John Kessenich0e737842017-03-24 18:38:16 -06002484// TODO: this functionality should exist at a higher level, in creating the AST
2485//
2486// Identify interface members that don't have their required extension turned on.
2487//
2488bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2489{
2490 auto& extensions = glslangIntermediate->getRequestedExtensions();
2491
Rex Xubcf291a2017-03-29 23:01:36 +08002492 if (member.getFieldName() == "gl_ViewportMask" &&
2493 extensions.find("GL_NV_viewport_array2") == extensions.end())
2494 return true;
2495 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2496 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2497 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002498 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2499 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2500 return true;
2501 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2502 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2503 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002504 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2505 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2506 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002507
2508 return false;
2509};
2510
John Kessenich6090df02016-06-30 21:18:02 -06002511// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2512// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2513// Mutually recursive with convertGlslangToSpvType().
2514spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2515 const glslang::TTypeList* glslangMembers,
2516 glslang::TLayoutPacking explicitLayout,
2517 const glslang::TQualifier& qualifier)
2518{
2519 // Create a vector of struct types for SPIR-V to consume
2520 std::vector<spv::Id> spvMembers;
2521 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 -06002522 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2523 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2524 if (glslangMember.hiddenMember()) {
2525 ++memberDelta;
2526 if (type.getBasicType() == glslang::EbtBlock)
2527 memberRemapper[glslangMembers][i] = -1;
2528 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002529 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002530 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002531 if (filterMember(glslangMember))
2532 continue;
2533 }
John Kessenich6090df02016-06-30 21:18:02 -06002534 // modify just this child's view of the qualifier
2535 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2536 InheritQualifiers(memberQualifier, qualifier);
2537
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002538 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002539 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002540 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002541
2542 // recurse
2543 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2544 }
2545 }
2546
2547 // Make the SPIR-V type
2548 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002549 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002550 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2551
2552 // Decorate it
2553 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2554
2555 return spvType;
2556}
2557
2558void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2559 const glslang::TTypeList* glslangMembers,
2560 glslang::TLayoutPacking explicitLayout,
2561 const glslang::TQualifier& qualifier,
2562 spv::Id spvType)
2563{
2564 // Name and decorate the non-hidden members
2565 int offset = -1;
2566 int locationOffset = 0; // for use within the members of this struct
2567 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2568 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2569 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002570 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002571 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002572 if (filterMember(glslangMember))
2573 continue;
2574 }
John Kessenich6090df02016-06-30 21:18:02 -06002575
2576 // modify just this child's view of the qualifier
2577 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2578 InheritQualifiers(memberQualifier, qualifier);
2579
2580 // using -1 above to indicate a hidden member
2581 if (member >= 0) {
2582 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2583 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2584 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2585 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002586 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2587 type.getQualifier().storage == glslang::EvqVaryingOut) {
2588 if (type.getBasicType() == glslang::EbtBlock ||
2589 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002590 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2591 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2592 }
2593 }
2594 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2595
Rex Xu286ca432017-07-27 14:33:16 +08002596 if (type.getBasicType() == glslang::EbtBlock &&
2597 qualifier.storage == glslang::EvqBuffer) {
2598 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002599 std::vector<spv::Decoration> memory;
2600 TranslateMemoryDecoration(memberQualifier, memory);
2601 for (unsigned int i = 0; i < memory.size(); ++i)
2602 addMemberDecoration(spvType, member, memory[i]);
2603 }
2604
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002605 // Location assignment was already completed correctly by the front end,
2606 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002607 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002608 // ill-specified and decisions have been made to not allow this.
2609 if (! type.isArray() && memberQualifier.hasLocation())
2610 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002611
John Kessenich2f47bc92016-06-30 21:47:35 -06002612 if (qualifier.hasLocation()) // track for upcoming inheritance
2613 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2614
John Kessenich6090df02016-06-30 21:18:02 -06002615 // component, XFB, others
2616 if (glslangMember.getQualifier().hasComponent())
2617 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2618 if (glslangMember.getQualifier().hasXfbOffset())
2619 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2620 else if (explicitLayout != glslang::ElpNone) {
2621 // figure out what to do with offset, which is accumulating
2622 int nextOffset;
2623 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2624 if (offset >= 0)
2625 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2626 offset = nextOffset;
2627 }
2628
2629 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2630 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2631
2632 // built-in variable decorations
2633 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002634 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002635 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002636
2637#ifdef NV_EXTENSIONS
2638 if (builtIn == spv::BuiltInLayer) {
2639 // SPV_NV_viewport_array2 extension
2640 if (glslangMember.getQualifier().layoutViewportRelative){
2641 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2642 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2643 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2644 }
2645 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2646 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2647 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2648 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2649 }
2650 }
chaocdf3956c2017-02-14 14:52:34 -08002651 if (glslangMember.getQualifier().layoutPassthrough) {
2652 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2653 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2654 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2655 }
chaoc771d89f2017-01-13 01:10:53 -08002656#endif
John Kessenich6090df02016-06-30 21:18:02 -06002657 }
2658 }
2659
2660 // Decorate the structure
2661 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002662 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002663 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2664 builder.addCapability(spv::CapabilityGeometryStreams);
2665 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2666 }
John Kessenich6090df02016-06-30 21:18:02 -06002667}
2668
John Kessenich6c292d32016-02-15 20:58:50 -07002669// Turn the expression forming the array size into an id.
2670// This is not quite trivial, because of specialization constants.
2671// Sometimes, a raw constant is turned into an Id, and sometimes
2672// a specialization constant expression is.
2673spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2674{
2675 // First, see if this is sized with a node, meaning a specialization constant:
2676 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2677 if (specNode != nullptr) {
2678 builder.clearAccessChain();
2679 specNode->traverse(this);
2680 return accessChainLoad(specNode->getAsTyped()->getType());
2681 }
qining25262b32016-05-06 17:25:16 -04002682
John Kessenich6c292d32016-02-15 20:58:50 -07002683 // Otherwise, need a compile-time (front end) size, get it:
2684 int size = arraySizes.getDimSize(dim);
2685 assert(size > 0);
2686 return builder.makeUintConstant(size);
2687}
2688
John Kessenich103bef92016-02-08 21:38:15 -07002689// Wrap the builder's accessChainLoad to:
2690// - localize handling of RelaxedPrecision
2691// - use the SPIR-V inferred type instead of another conversion of the glslang type
2692// (avoids unnecessary work and possible type punning for structures)
2693// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002694spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2695{
John Kessenich103bef92016-02-08 21:38:15 -07002696 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2697 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2698
2699 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002700 if (type.getBasicType() == glslang::EbtBool) {
2701 if (builder.isScalarType(nominalTypeId)) {
2702 // Conversion for bool
2703 spv::Id boolType = builder.makeBoolType();
2704 if (nominalTypeId != boolType)
2705 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2706 } else if (builder.isVectorType(nominalTypeId)) {
2707 // Conversion for bvec
2708 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2709 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2710 if (nominalTypeId != bvecType)
2711 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2712 }
2713 }
John Kessenich103bef92016-02-08 21:38:15 -07002714
2715 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002716}
2717
Rex Xu27253232016-02-23 17:51:09 +08002718// Wrap the builder's accessChainStore to:
2719// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002720//
2721// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002722void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2723{
2724 // Need to convert to abstract types when necessary
2725 if (type.getBasicType() == glslang::EbtBool) {
2726 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2727
2728 if (builder.isScalarType(nominalTypeId)) {
2729 // Conversion for bool
2730 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002731 if (nominalTypeId != boolType) {
2732 // keep these outside arguments, for determinant order-of-evaluation
2733 spv::Id one = builder.makeUintConstant(1);
2734 spv::Id zero = builder.makeUintConstant(0);
2735 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2736 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002737 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002738 } else if (builder.isVectorType(nominalTypeId)) {
2739 // Conversion for bvec
2740 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2741 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002742 if (nominalTypeId != bvecType) {
2743 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002744 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2745 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2746 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002747 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002748 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2749 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002750 }
2751 }
2752
2753 builder.accessChainStore(rvalue);
2754}
2755
John Kessenich4bf71552016-09-02 11:20:21 -06002756// For storing when types match at the glslang level, but not might match at the
2757// SPIR-V level.
2758//
2759// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002760// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002761// as in a member-decorated way.
2762//
2763// NOTE: This function can handle any store request; if it's not special it
2764// simplifies to a simple OpStore.
2765//
2766// Implicitly uses the existing builder.accessChain as the storage target.
2767void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2768{
John Kessenichb3e24e42016-09-11 12:33:43 -06002769 // we only do the complex path here if it's an aggregate
2770 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002771 accessChainStore(type, rValue);
2772 return;
2773 }
2774
John Kessenichb3e24e42016-09-11 12:33:43 -06002775 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002776 spv::Id rType = builder.getTypeId(rValue);
2777 spv::Id lValue = builder.accessChainGetLValue();
2778 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2779 if (lType == rType) {
2780 accessChainStore(type, rValue);
2781 return;
2782 }
2783
John Kessenichb3e24e42016-09-11 12:33:43 -06002784 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002785 // where the two types were the same type in GLSL. This requires member
2786 // by member copy, recursively.
2787
John Kessenichb3e24e42016-09-11 12:33:43 -06002788 // If an array, copy element by element.
2789 if (type.isArray()) {
2790 glslang::TType glslangElementType(type, 0);
2791 spv::Id elementRType = builder.getContainedTypeId(rType);
2792 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2793 // get the source member
2794 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002795
John Kessenichb3e24e42016-09-11 12:33:43 -06002796 // set up the target storage
2797 builder.clearAccessChain();
2798 builder.setAccessChainLValue(lValue);
2799 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002800
John Kessenichb3e24e42016-09-11 12:33:43 -06002801 // store the member
2802 multiTypeStore(glslangElementType, elementRValue);
2803 }
2804 } else {
2805 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002806
John Kessenichb3e24e42016-09-11 12:33:43 -06002807 // loop over structure members
2808 const glslang::TTypeList& members = *type.getStruct();
2809 for (int m = 0; m < (int)members.size(); ++m) {
2810 const glslang::TType& glslangMemberType = *members[m].type;
2811
2812 // get the source member
2813 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2814 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2815
2816 // set up the target storage
2817 builder.clearAccessChain();
2818 builder.setAccessChainLValue(lValue);
2819 builder.accessChainPush(builder.makeIntConstant(m));
2820
2821 // store the member
2822 multiTypeStore(glslangMemberType, memberRValue);
2823 }
John Kessenich4bf71552016-09-02 11:20:21 -06002824 }
2825}
2826
John Kessenichf85e8062015-12-19 13:57:10 -07002827// Decide whether or not this type should be
2828// decorated with offsets and strides, and if so
2829// whether std140 or std430 rules should be applied.
2830glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002831{
John Kessenichf85e8062015-12-19 13:57:10 -07002832 // has to be a block
2833 if (type.getBasicType() != glslang::EbtBlock)
2834 return glslang::ElpNone;
2835
2836 // has to be a uniform or buffer block
2837 if (type.getQualifier().storage != glslang::EvqUniform &&
2838 type.getQualifier().storage != glslang::EvqBuffer)
2839 return glslang::ElpNone;
2840
2841 // return the layout to use
2842 switch (type.getQualifier().layoutPacking) {
2843 case glslang::ElpStd140:
2844 case glslang::ElpStd430:
2845 return type.getQualifier().layoutPacking;
2846 default:
2847 return glslang::ElpNone;
2848 }
John Kessenich31ed4832015-09-09 17:51:38 -06002849}
2850
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002851// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002852int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002853{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002854 int size;
John Kessenich49987892015-12-29 17:11:44 -07002855 int stride;
2856 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002857
2858 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002859}
2860
John Kessenich49987892015-12-29 17:11:44 -07002861// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002862// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002863int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002864{
John Kessenich49987892015-12-29 17:11:44 -07002865 glslang::TType elementType;
2866 elementType.shallowCopy(matrixType);
2867 elementType.clearArraySizes();
2868
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002869 int size;
John Kessenich49987892015-12-29 17:11:44 -07002870 int stride;
2871 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2872
2873 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002874}
2875
John Kessenich5e4b1242015-08-06 22:53:06 -06002876// Given a member type of a struct, realign the current offset for it, and compute
2877// the next (not yet aligned) offset for the next member, which will get aligned
2878// on the next call.
2879// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2880// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2881// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002882void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002883 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002884{
2885 // this will get a positive value when deemed necessary
2886 nextOffset = -1;
2887
John Kessenich5e4b1242015-08-06 22:53:06 -06002888 // override anything in currentOffset with user-set offset
2889 if (memberType.getQualifier().hasOffset())
2890 currentOffset = memberType.getQualifier().layoutOffset;
2891
2892 // It could be that current linker usage in glslang updated all the layoutOffset,
2893 // in which case the following code does not matter. But, that's not quite right
2894 // once cross-compilation unit GLSL validation is done, as the original user
2895 // settings are needed in layoutOffset, and then the following will come into play.
2896
John Kessenichf85e8062015-12-19 13:57:10 -07002897 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002898 if (! memberType.getQualifier().hasOffset())
2899 currentOffset = -1;
2900
2901 return;
2902 }
2903
John Kessenichf85e8062015-12-19 13:57:10 -07002904 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 if (currentOffset < 0)
2906 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002907
John Kessenich5e4b1242015-08-06 22:53:06 -06002908 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2909 // but possibly not yet correctly aligned.
2910
2911 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002912 int dummyStride;
2913 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002914
2915 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002916 // TODO: make this consistent in early phases of code:
2917 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2918 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2919 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002920 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002921 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002922 int dummySize;
2923 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2924 if (componentAlignment <= 4)
2925 memberAlignment = componentAlignment;
2926 }
2927
2928 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002930
2931 // Bump up to vec4 if there is a bad straddle
2932 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2933 glslang::RoundToPow2(currentOffset, 16);
2934
John Kessenich5e4b1242015-08-06 22:53:06 -06002935 nextOffset = currentOffset + memberSize;
2936}
2937
David Netoa901ffe2016-06-08 14:11:40 +01002938void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002939{
David Netoa901ffe2016-06-08 14:11:40 +01002940 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2941 switch (glslangBuiltIn)
2942 {
2943 case glslang::EbvClipDistance:
2944 case glslang::EbvCullDistance:
2945 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002946#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002947 case glslang::EbvViewportMaskNV:
2948 case glslang::EbvSecondaryPositionNV:
2949 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002950 case glslang::EbvPositionPerViewNV:
2951 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002952#endif
David Netoa901ffe2016-06-08 14:11:40 +01002953 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2954 // Alternately, we could just call this for any glslang built-in, since the
2955 // capability already guards against duplicates.
2956 TranslateBuiltInDecoration(glslangBuiltIn, false);
2957 break;
2958 default:
2959 // Capabilities were already generated when the struct was declared.
2960 break;
2961 }
John Kessenichebb50532016-05-16 19:22:05 -06002962}
2963
John Kessenich6fccb3c2016-09-19 16:01:41 -06002964bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002965{
John Kessenicheee9d532016-09-19 18:09:30 -06002966 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002967}
2968
John Kessenichd41993d2017-09-10 15:21:05 -06002969// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002970// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2971// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002972bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2973{
John Kessenich6a14f782017-12-04 02:48:10 -07002974 assert(qualifier == glslang::EvqIn ||
2975 qualifier == glslang::EvqOut ||
2976 qualifier == glslang::EvqInOut ||
2977 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002978 return qualifier != glslang::EvqConstReadOnly;
2979}
2980
2981// Is parameter pass-by-original?
2982bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2983 bool implicitThisParam)
2984{
2985 if (implicitThisParam) // implicit this
2986 return true;
2987 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07002988 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06002989 return paramType.containsOpaque() || // sampler, etc.
2990 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
2991}
2992
John Kessenich140f3df2015-06-26 16:58:36 -06002993// Make all the functions, skeletally, without actually visiting their bodies.
2994void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2995{
John Kessenichfad62972017-07-18 02:35:46 -06002996 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2997 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2998 if (paramPrecision != spv::NoPrecision)
2999 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003000 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003001 };
3002
John Kessenich140f3df2015-06-26 16:58:36 -06003003 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3004 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003005 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003006 continue;
3007
3008 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003009 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003010 //
qining25262b32016-05-06 17:25:16 -04003011 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003012 // function. What it is an address of varies:
3013 //
John Kessenich4bf71552016-09-02 11:20:21 -06003014 // - "in" parameters not marked as "const" can be written to without modifying the calling
3015 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003016 //
3017 // - "const in" parameters can just be the r-value, as no writes need occur.
3018 //
John Kessenich4bf71552016-09-02 11:20:21 -06003019 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3020 // 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 -06003021
3022 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003023 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003024 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3025
John Kessenichfad62972017-07-18 02:35:46 -06003026 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3027 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003028
John Kessenichfad62972017-07-18 02:35:46 -06003029 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003030 for (int p = 0; p < (int)parameters.size(); ++p) {
3031 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3032 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003033 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003034 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003035 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003036 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3037 else
John Kessenich4bf71552016-09-02 11:20:21 -06003038 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003039 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003040 paramTypes.push_back(typeId);
3041 }
3042
3043 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003044 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3045 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003046 glslFunction->getName().c_str(), paramTypes,
3047 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003048 if (implicitThis)
3049 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003050
3051 // Track function to emit/call later
3052 functionMap[glslFunction->getName().c_str()] = function;
3053
3054 // Set the parameter id's
3055 for (int p = 0; p < (int)parameters.size(); ++p) {
3056 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3057 // give a name too
3058 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3059 }
3060 }
3061}
3062
3063// Process all the initializers, while skipping the functions and link objects
3064void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3065{
3066 builder.setBuildPoint(shaderEntry->getLastBlock());
3067 for (int i = 0; i < (int)initializers.size(); ++i) {
3068 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3069 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3070
3071 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003072 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003073 initializer->traverse(this);
3074 }
3075 }
3076}
3077
3078// Process all the functions, while skipping initializers.
3079void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3080{
3081 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3082 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003083 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003084 node->traverse(this);
3085 }
3086}
3087
3088void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3089{
qining25262b32016-05-06 17:25:16 -04003090 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003091 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003092 currentFunction = functionMap[node->getName().c_str()];
3093 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003094 builder.setBuildPoint(functionBlock);
3095}
3096
Rex Xu04db3f52015-09-16 11:44:02 +08003097void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003098{
Rex Xufc618912015-09-09 16:42:49 +08003099 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003100
3101 glslang::TSampler sampler = {};
3102 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003103 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003104 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3105 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3106 }
3107
John Kessenich140f3df2015-06-26 16:58:36 -06003108 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3109 builder.clearAccessChain();
3110 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003111
3112 // Special case l-value operands
3113 bool lvalue = false;
3114 switch (node.getOp()) {
3115 case glslang::EOpImageAtomicAdd:
3116 case glslang::EOpImageAtomicMin:
3117 case glslang::EOpImageAtomicMax:
3118 case glslang::EOpImageAtomicAnd:
3119 case glslang::EOpImageAtomicOr:
3120 case glslang::EOpImageAtomicXor:
3121 case glslang::EOpImageAtomicExchange:
3122 case glslang::EOpImageAtomicCompSwap:
3123 if (i == 0)
3124 lvalue = true;
3125 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003126 case glslang::EOpSparseImageLoad:
3127 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3128 lvalue = true;
3129 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003130 case glslang::EOpSparseTexture:
3131 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3132 lvalue = true;
3133 break;
3134 case glslang::EOpSparseTextureClamp:
3135 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3136 lvalue = true;
3137 break;
3138 case glslang::EOpSparseTextureLod:
3139 case glslang::EOpSparseTextureOffset:
3140 if (i == 3)
3141 lvalue = true;
3142 break;
3143 case glslang::EOpSparseTextureFetch:
3144 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3145 lvalue = true;
3146 break;
3147 case glslang::EOpSparseTextureFetchOffset:
3148 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3149 lvalue = true;
3150 break;
3151 case glslang::EOpSparseTextureLodOffset:
3152 case glslang::EOpSparseTextureGrad:
3153 case glslang::EOpSparseTextureOffsetClamp:
3154 if (i == 4)
3155 lvalue = true;
3156 break;
3157 case glslang::EOpSparseTextureGradOffset:
3158 case glslang::EOpSparseTextureGradClamp:
3159 if (i == 5)
3160 lvalue = true;
3161 break;
3162 case glslang::EOpSparseTextureGradOffsetClamp:
3163 if (i == 6)
3164 lvalue = true;
3165 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003166 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003167 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3168 lvalue = true;
3169 break;
3170 case glslang::EOpSparseTextureGatherOffset:
3171 case glslang::EOpSparseTextureGatherOffsets:
3172 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3173 lvalue = true;
3174 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003175#ifdef AMD_EXTENSIONS
3176 case glslang::EOpSparseTextureGatherLod:
3177 if (i == 3)
3178 lvalue = true;
3179 break;
3180 case glslang::EOpSparseTextureGatherLodOffset:
3181 case glslang::EOpSparseTextureGatherLodOffsets:
3182 if (i == 4)
3183 lvalue = true;
3184 break;
Rex Xu129799a2017-07-05 17:23:28 +08003185 case glslang::EOpSparseImageLoadLod:
3186 if (i == 3)
3187 lvalue = true;
3188 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003189#endif
Rex Xufc618912015-09-09 16:42:49 +08003190 default:
3191 break;
3192 }
3193
Rex Xu6b86d492015-09-16 17:48:22 +08003194 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003195 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003196 else
John Kessenich32cfd492016-02-02 12:37:46 -07003197 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003198 }
3199}
3200
John Kessenichfc51d282015-08-19 13:34:18 -06003201void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003202{
John Kessenichfc51d282015-08-19 13:34:18 -06003203 builder.clearAccessChain();
3204 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003205 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003206}
John Kessenich140f3df2015-06-26 16:58:36 -06003207
John Kessenichfc51d282015-08-19 13:34:18 -06003208spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3209{
John Kesseniche485c7a2017-05-31 18:50:53 -06003210 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003211 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003212
3213 builder.setLine(node->getLoc().line);
3214
John Kessenich8c8505c2016-07-26 12:50:38 -06003215 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003216
John Kessenichfc51d282015-08-19 13:34:18 -06003217 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003218 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3219 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3220 std::vector<spv::Id> arguments;
3221 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003222 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003223 else
3224 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003225 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003226
3227 spv::Builder::TextureParameters params = { };
3228 params.sampler = arguments[0];
3229
Rex Xu04db3f52015-09-16 11:44:02 +08003230 glslang::TCrackedTextureOp cracked;
3231 node->crackTexture(sampler, cracked);
3232
amhagan05506bb2017-06-13 16:53:02 -04003233 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003234
John Kessenichfc51d282015-08-19 13:34:18 -06003235 // Check for queries
3236 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003237 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3238 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003239 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003240
John Kessenichfc51d282015-08-19 13:34:18 -06003241 switch (node->getOp()) {
3242 case glslang::EOpImageQuerySize:
3243 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003244 if (arguments.size() > 1) {
3245 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003246 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003247 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003248 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003249 case glslang::EOpImageQuerySamples:
3250 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003251 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003252 case glslang::EOpTextureQueryLod:
3253 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003254 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003255 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003256 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003257 case glslang::EOpSparseTexelsResident:
3258 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003259 default:
3260 assert(0);
3261 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003262 }
John Kessenich140f3df2015-06-26 16:58:36 -06003263 }
3264
Rex Xufc618912015-09-09 16:42:49 +08003265 // Check for image functions other than queries
3266 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003267 std::vector<spv::Id> operands;
3268 auto opIt = arguments.begin();
3269 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003270
3271 // Handle subpass operations
3272 // TODO: GLSL should change to have the "MS" only on the type rather than the
3273 // built-in function.
3274 if (cracked.subpass) {
3275 // add on the (0,0) coordinate
3276 spv::Id zero = builder.makeIntConstant(0);
3277 std::vector<spv::Id> comps;
3278 comps.push_back(zero);
3279 comps.push_back(zero);
3280 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3281 if (sampler.ms) {
3282 operands.push_back(spv::ImageOperandsSampleMask);
3283 operands.push_back(*(opIt++));
3284 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003285 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3286 builder.setPrecision(result, precision);
3287 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003288 }
3289
John Kessenich56bab042015-09-16 10:54:31 -06003290 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003291#ifdef AMD_EXTENSIONS
3292 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3293#else
John Kessenich56bab042015-09-16 10:54:31 -06003294 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003295#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003296 if (sampler.ms) {
3297 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003298 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003299#ifdef AMD_EXTENSIONS
3300 } else if (cracked.lod) {
3301 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3302 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3303
3304 operands.push_back(spv::ImageOperandsLodMask);
3305 operands.push_back(*opIt);
3306#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003307 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003308 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3309 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003310
3311 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3312 builder.setPrecision(result, precision);
3313 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003314#ifdef AMD_EXTENSIONS
3315 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3316#else
John Kessenich56bab042015-09-16 10:54:31 -06003317 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003318#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003319 if (sampler.ms) {
3320 operands.push_back(*(opIt + 1));
3321 operands.push_back(spv::ImageOperandsSampleMask);
3322 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003323#ifdef AMD_EXTENSIONS
3324 } else if (cracked.lod) {
3325 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3326 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3327
3328 operands.push_back(*(opIt + 1));
3329 operands.push_back(spv::ImageOperandsLodMask);
3330 operands.push_back(*opIt);
3331#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003332 } else
3333 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003334 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003335 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3336 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003337 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003338#ifdef AMD_EXTENSIONS
3339 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3340#else
Rex Xu5eafa472016-02-19 22:24:03 +08003341 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003342#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003343 builder.addCapability(spv::CapabilitySparseResidency);
3344 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3345 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3346
3347 if (sampler.ms) {
3348 operands.push_back(spv::ImageOperandsSampleMask);
3349 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003350#ifdef AMD_EXTENSIONS
3351 } else if (cracked.lod) {
3352 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3353 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3354
3355 operands.push_back(spv::ImageOperandsLodMask);
3356 operands.push_back(*opIt++);
3357#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003358 }
3359
3360 // Create the return type that was a special structure
3361 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003362 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003363 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3364 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3365
3366 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3367
3368 // Decode the return type
3369 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3370 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003371 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003372 // Process image atomic operations
3373
3374 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3375 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003376 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003377
John Kessenich8c8505c2016-07-26 12:50:38 -06003378 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003379 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003380
3381 std::vector<spv::Id> operands;
3382 operands.push_back(pointer);
3383 for (; opIt != arguments.end(); ++opIt)
3384 operands.push_back(*opIt);
3385
John Kessenich8c8505c2016-07-26 12:50:38 -06003386 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003387 }
3388 }
3389
amhagan05506bb2017-06-13 16:53:02 -04003390#ifdef AMD_EXTENSIONS
3391 // Check for fragment mask functions other than queries
3392 if (cracked.fragMask) {
3393 assert(sampler.ms);
3394
3395 auto opIt = arguments.begin();
3396 std::vector<spv::Id> operands;
3397
3398 // Extract the image if necessary
3399 if (builder.isSampledImage(params.sampler))
3400 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3401
3402 operands.push_back(params.sampler);
3403 ++opIt;
3404
3405 if (sampler.isSubpass()) {
3406 // add on the (0,0) coordinate
3407 spv::Id zero = builder.makeIntConstant(0);
3408 std::vector<spv::Id> comps;
3409 comps.push_back(zero);
3410 comps.push_back(zero);
3411 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3412 }
3413
3414 for (; opIt != arguments.end(); ++opIt)
3415 operands.push_back(*opIt);
3416
3417 spv::Op fragMaskOp = spv::OpNop;
3418 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3419 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3420 else if (node->getOp() == glslang::EOpFragmentFetch)
3421 fragMaskOp = spv::OpFragmentFetchAMD;
3422
3423 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3424 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3425 return builder.createOp(fragMaskOp, resultType(), operands);
3426 }
3427#endif
3428
Rex Xufc618912015-09-09 16:42:49 +08003429 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003430 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003431 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3432
John Kessenichfc51d282015-08-19 13:34:18 -06003433 // check for bias argument
3434 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003435#ifdef AMD_EXTENSIONS
3436 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3437#else
Rex Xu71519fe2015-11-11 15:35:47 +08003438 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003439#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003440 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003441#ifdef AMD_EXTENSIONS
3442 if (cracked.gather)
3443 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3444#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003445 if (cracked.offset)
3446 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003447#ifdef AMD_EXTENSIONS
3448 else if (cracked.offsets)
3449 ++nonBiasArgCount;
3450#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003451 if (cracked.grad)
3452 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003453 if (cracked.lodClamp)
3454 ++nonBiasArgCount;
3455 if (sparse)
3456 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003457
3458 if ((int)arguments.size() > nonBiasArgCount)
3459 bias = true;
3460 }
3461
John Kessenicha5c33d62016-06-02 23:45:21 -06003462 // See if the sampler param should really be just the SPV image part
3463 if (cracked.fetch) {
3464 // a fetch needs to have the image extracted first
3465 if (builder.isSampledImage(params.sampler))
3466 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3467 }
3468
Rex Xu225e0fc2016-11-17 17:47:59 +08003469#ifdef AMD_EXTENSIONS
3470 if (cracked.gather) {
3471 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3472 if (bias || cracked.lod ||
3473 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3474 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003475 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003476 }
3477 }
3478#endif
3479
John Kessenichfc51d282015-08-19 13:34:18 -06003480 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003481
John Kessenichfc51d282015-08-19 13:34:18 -06003482 params.coords = arguments[1];
3483 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003484 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003485
3486 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003487 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003488 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003489 ++extraArgs;
3490 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003491 params.Dref = arguments[2];
3492 ++extraArgs;
3493 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003494 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003495 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003496 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003497 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003498 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003499 dRefComp = builder.getNumComponents(params.coords) - 1;
3500 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003501 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3502 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003503
3504 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003505 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003506 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003507 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003508 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3509 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3510 noImplicitLod = true;
3511 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003512
3513 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003514 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003515 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003516 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003517 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003518
3519 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003520 if (cracked.grad) {
3521 params.gradX = arguments[2 + extraArgs];
3522 params.gradY = arguments[3 + extraArgs];
3523 extraArgs += 2;
3524 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003525
3526 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003527 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003528 params.offset = arguments[2 + extraArgs];
3529 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003530 } else if (cracked.offsets) {
3531 params.offsets = arguments[2 + extraArgs];
3532 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003533 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003534
3535 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003536 if (cracked.lodClamp) {
3537 params.lodClamp = arguments[2 + extraArgs];
3538 ++extraArgs;
3539 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003540
3541 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003542 if (sparse) {
3543 params.texelOut = arguments[2 + extraArgs];
3544 ++extraArgs;
3545 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003546
John Kessenich76d4dfc2016-06-16 12:43:23 -06003547 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003548 if (cracked.gather && ! sampler.shadow) {
3549 // default component is 0, if missing, otherwise an argument
3550 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003551 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003552 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003553 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003554 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003555 }
3556
3557 // bias
3558 if (bias) {
3559 params.bias = arguments[2 + extraArgs];
3560 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003561 }
John Kessenichfc51d282015-08-19 13:34:18 -06003562
John Kessenich65336482016-06-16 14:06:26 -06003563 // projective component (might not to move)
3564 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3565 // are divided by the last component of P."
3566 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3567 // unused components will appear after all used components."
3568 if (cracked.proj) {
3569 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3570 int projTargetComp;
3571 switch (sampler.dim) {
3572 case glslang::Esd1D: projTargetComp = 1; break;
3573 case glslang::Esd2D: projTargetComp = 2; break;
3574 case glslang::EsdRect: projTargetComp = 2; break;
3575 default: projTargetComp = projSourceComp; break;
3576 }
3577 // copy the projective coordinate if we have to
3578 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003579 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003580 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3581 projSourceComp);
3582 params.coords = builder.createCompositeInsert(projComp, params.coords,
3583 builder.getTypeId(params.coords), projTargetComp);
3584 }
3585 }
3586
John Kessenich8c8505c2016-07-26 12:50:38 -06003587 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003588}
3589
3590spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3591{
3592 // Grab the function's pointer from the previously created function
3593 spv::Function* function = functionMap[node->getName().c_str()];
3594 if (! function)
3595 return 0;
3596
3597 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3598 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3599
3600 // See comments in makeFunctions() for details about the semantics for parameter passing.
3601 //
3602 // These imply we need a four step process:
3603 // 1. Evaluate the arguments
3604 // 2. Allocate and make copies of in, out, and inout arguments
3605 // 3. Make the call
3606 // 4. Copy back the results
3607
3608 // 1. Evaluate the arguments
3609 std::vector<spv::Builder::AccessChain> lValues;
3610 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003611 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003612 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003613 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003614 // build l-value
3615 builder.clearAccessChain();
3616 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003617 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003618 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003619 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3620 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003621 // save l-value
3622 lValues.push_back(builder.getAccessChain());
3623 } else {
3624 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003625 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003626 }
3627 }
3628
3629 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3630 // copy the original into that space.
3631 //
3632 // Also, build up the list of actual arguments to pass in for the call
3633 int lValueCount = 0;
3634 int rValueCount = 0;
3635 std::vector<spv::Id> spvArgs;
3636 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003637 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003638 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003639 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003640 builder.setAccessChain(lValues[lValueCount]);
3641 arg = builder.accessChainGetLValue();
3642 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003643 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003644 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003645 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3646 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3647 // need to copy the input into output space
3648 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003649 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003650 builder.clearAccessChain();
3651 builder.setAccessChainLValue(arg);
3652 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003653 }
3654 ++lValueCount;
3655 } else {
3656 arg = rValues[rValueCount];
3657 ++rValueCount;
3658 }
3659 spvArgs.push_back(arg);
3660 }
3661
3662 // 3. Make the call.
3663 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003664 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003665
3666 // 4. Copy back out an "out" arguments.
3667 lValueCount = 0;
3668 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003669 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003670 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3671 ++lValueCount;
3672 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003673 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3674 spv::Id copy = builder.createLoad(spvArgs[a]);
3675 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003676 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003677 }
3678 ++lValueCount;
3679 }
3680 }
3681
3682 return result;
3683}
3684
3685// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003686spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3687 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003688 spv::Id typeId, spv::Id left, spv::Id right,
3689 glslang::TBasicType typeProxy, bool reduceComparison)
3690{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003691#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003692 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003693 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3694#else
Rex Xucabbb782017-03-24 13:41:14 +08003695 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003696 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003697#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003698 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003699
3700 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003701 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003702 bool comparison = false;
3703
3704 switch (op) {
3705 case glslang::EOpAdd:
3706 case glslang::EOpAddAssign:
3707 if (isFloat)
3708 binOp = spv::OpFAdd;
3709 else
3710 binOp = spv::OpIAdd;
3711 break;
3712 case glslang::EOpSub:
3713 case glslang::EOpSubAssign:
3714 if (isFloat)
3715 binOp = spv::OpFSub;
3716 else
3717 binOp = spv::OpISub;
3718 break;
3719 case glslang::EOpMul:
3720 case glslang::EOpMulAssign:
3721 if (isFloat)
3722 binOp = spv::OpFMul;
3723 else
3724 binOp = spv::OpIMul;
3725 break;
3726 case glslang::EOpVectorTimesScalar:
3727 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003728 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003729 if (builder.isVector(right))
3730 std::swap(left, right);
3731 assert(builder.isScalar(right));
3732 needMatchingVectors = false;
3733 binOp = spv::OpVectorTimesScalar;
3734 } else
3735 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003736 break;
3737 case glslang::EOpVectorTimesMatrix:
3738 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003739 binOp = spv::OpVectorTimesMatrix;
3740 break;
3741 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003742 binOp = spv::OpMatrixTimesVector;
3743 break;
3744 case glslang::EOpMatrixTimesScalar:
3745 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003746 binOp = spv::OpMatrixTimesScalar;
3747 break;
3748 case glslang::EOpMatrixTimesMatrix:
3749 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003750 binOp = spv::OpMatrixTimesMatrix;
3751 break;
3752 case glslang::EOpOuterProduct:
3753 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003754 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756
3757 case glslang::EOpDiv:
3758 case glslang::EOpDivAssign:
3759 if (isFloat)
3760 binOp = spv::OpFDiv;
3761 else if (isUnsigned)
3762 binOp = spv::OpUDiv;
3763 else
3764 binOp = spv::OpSDiv;
3765 break;
3766 case glslang::EOpMod:
3767 case glslang::EOpModAssign:
3768 if (isFloat)
3769 binOp = spv::OpFMod;
3770 else if (isUnsigned)
3771 binOp = spv::OpUMod;
3772 else
3773 binOp = spv::OpSMod;
3774 break;
3775 case glslang::EOpRightShift:
3776 case glslang::EOpRightShiftAssign:
3777 if (isUnsigned)
3778 binOp = spv::OpShiftRightLogical;
3779 else
3780 binOp = spv::OpShiftRightArithmetic;
3781 break;
3782 case glslang::EOpLeftShift:
3783 case glslang::EOpLeftShiftAssign:
3784 binOp = spv::OpShiftLeftLogical;
3785 break;
3786 case glslang::EOpAnd:
3787 case glslang::EOpAndAssign:
3788 binOp = spv::OpBitwiseAnd;
3789 break;
3790 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003791 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003792 binOp = spv::OpLogicalAnd;
3793 break;
3794 case glslang::EOpInclusiveOr:
3795 case glslang::EOpInclusiveOrAssign:
3796 binOp = spv::OpBitwiseOr;
3797 break;
3798 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003799 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003800 binOp = spv::OpLogicalOr;
3801 break;
3802 case glslang::EOpExclusiveOr:
3803 case glslang::EOpExclusiveOrAssign:
3804 binOp = spv::OpBitwiseXor;
3805 break;
3806 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003807 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003808 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003809 break;
3810
3811 case glslang::EOpLessThan:
3812 case glslang::EOpGreaterThan:
3813 case glslang::EOpLessThanEqual:
3814 case glslang::EOpGreaterThanEqual:
3815 case glslang::EOpEqual:
3816 case glslang::EOpNotEqual:
3817 case glslang::EOpVectorEqual:
3818 case glslang::EOpVectorNotEqual:
3819 comparison = true;
3820 break;
3821 default:
3822 break;
3823 }
3824
John Kessenich7c1aa102015-10-15 13:29:11 -06003825 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003826 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003827 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003828 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003829 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003830
3831 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003832 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003833 builder.promoteScalar(precision, left, right);
3834
qining25262b32016-05-06 17:25:16 -04003835 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3836 addDecoration(result, noContraction);
3837 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 }
3839
3840 if (! comparison)
3841 return 0;
3842
John Kessenich7c1aa102015-10-15 13:29:11 -06003843 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003844
John Kessenich4583b612016-08-07 19:14:22 -06003845 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3846 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003847 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003848
3849 switch (op) {
3850 case glslang::EOpLessThan:
3851 if (isFloat)
3852 binOp = spv::OpFOrdLessThan;
3853 else if (isUnsigned)
3854 binOp = spv::OpULessThan;
3855 else
3856 binOp = spv::OpSLessThan;
3857 break;
3858 case glslang::EOpGreaterThan:
3859 if (isFloat)
3860 binOp = spv::OpFOrdGreaterThan;
3861 else if (isUnsigned)
3862 binOp = spv::OpUGreaterThan;
3863 else
3864 binOp = spv::OpSGreaterThan;
3865 break;
3866 case glslang::EOpLessThanEqual:
3867 if (isFloat)
3868 binOp = spv::OpFOrdLessThanEqual;
3869 else if (isUnsigned)
3870 binOp = spv::OpULessThanEqual;
3871 else
3872 binOp = spv::OpSLessThanEqual;
3873 break;
3874 case glslang::EOpGreaterThanEqual:
3875 if (isFloat)
3876 binOp = spv::OpFOrdGreaterThanEqual;
3877 else if (isUnsigned)
3878 binOp = spv::OpUGreaterThanEqual;
3879 else
3880 binOp = spv::OpSGreaterThanEqual;
3881 break;
3882 case glslang::EOpEqual:
3883 case glslang::EOpVectorEqual:
3884 if (isFloat)
3885 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003886 else if (isBool)
3887 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003888 else
3889 binOp = spv::OpIEqual;
3890 break;
3891 case glslang::EOpNotEqual:
3892 case glslang::EOpVectorNotEqual:
3893 if (isFloat)
3894 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003895 else if (isBool)
3896 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003897 else
3898 binOp = spv::OpINotEqual;
3899 break;
3900 default:
3901 break;
3902 }
3903
qining25262b32016-05-06 17:25:16 -04003904 if (binOp != spv::OpNop) {
3905 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3906 addDecoration(result, noContraction);
3907 return builder.setPrecision(result, precision);
3908 }
John Kessenich140f3df2015-06-26 16:58:36 -06003909
3910 return 0;
3911}
3912
John Kessenich04bb8a02015-12-12 12:28:14 -07003913//
3914// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3915// These can be any of:
3916//
3917// matrix * scalar
3918// scalar * matrix
3919// matrix * matrix linear algebraic
3920// matrix * vector
3921// vector * matrix
3922// matrix * matrix componentwise
3923// matrix op matrix op in {+, -, /}
3924// matrix op scalar op in {+, -, /}
3925// scalar op matrix op in {+, -, /}
3926//
qining25262b32016-05-06 17:25:16 -04003927spv::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 -07003928{
3929 bool firstClass = true;
3930
3931 // First, handle first-class matrix operations (* and matrix/scalar)
3932 switch (op) {
3933 case spv::OpFDiv:
3934 if (builder.isMatrix(left) && builder.isScalar(right)) {
3935 // turn matrix / scalar into a multiply...
3936 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3937 op = spv::OpMatrixTimesScalar;
3938 } else
3939 firstClass = false;
3940 break;
3941 case spv::OpMatrixTimesScalar:
3942 if (builder.isMatrix(right))
3943 std::swap(left, right);
3944 assert(builder.isScalar(right));
3945 break;
3946 case spv::OpVectorTimesMatrix:
3947 assert(builder.isVector(left));
3948 assert(builder.isMatrix(right));
3949 break;
3950 case spv::OpMatrixTimesVector:
3951 assert(builder.isMatrix(left));
3952 assert(builder.isVector(right));
3953 break;
3954 case spv::OpMatrixTimesMatrix:
3955 assert(builder.isMatrix(left));
3956 assert(builder.isMatrix(right));
3957 break;
3958 default:
3959 firstClass = false;
3960 break;
3961 }
3962
qining25262b32016-05-06 17:25:16 -04003963 if (firstClass) {
3964 spv::Id result = builder.createBinOp(op, typeId, left, right);
3965 addDecoration(result, noContraction);
3966 return builder.setPrecision(result, precision);
3967 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003968
LoopDawg592860c2016-06-09 08:57:35 -06003969 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003970 // The result type of all of them is the same type as the (a) matrix operand.
3971 // The algorithm is to:
3972 // - break the matrix(es) into vectors
3973 // - smear any scalar to a vector
3974 // - do vector operations
3975 // - make a matrix out the vector results
3976 switch (op) {
3977 case spv::OpFAdd:
3978 case spv::OpFSub:
3979 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003980 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003981 case spv::OpFMul:
3982 {
3983 // one time set up...
3984 bool leftMat = builder.isMatrix(left);
3985 bool rightMat = builder.isMatrix(right);
3986 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3987 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3988 spv::Id scalarType = builder.getScalarTypeId(typeId);
3989 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3990 std::vector<spv::Id> results;
3991 spv::Id smearVec = spv::NoResult;
3992 if (builder.isScalar(left))
3993 smearVec = builder.smearScalar(precision, left, vecType);
3994 else if (builder.isScalar(right))
3995 smearVec = builder.smearScalar(precision, right, vecType);
3996
3997 // do each vector op
3998 for (unsigned int c = 0; c < numCols; ++c) {
3999 std::vector<unsigned int> indexes;
4000 indexes.push_back(c);
4001 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4002 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004003 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4004 addDecoration(result, noContraction);
4005 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004006 }
4007
4008 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004009 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004010 }
4011 default:
4012 assert(0);
4013 return spv::NoResult;
4014 }
4015}
4016
qining25262b32016-05-06 17:25:16 -04004017spv::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 -06004018{
4019 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004020 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004021 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004022#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004023 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004024 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4025#else
Rex Xucabbb782017-03-24 13:41:14 +08004026 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004027 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004028#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004029
4030 switch (op) {
4031 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004032 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004033 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004034 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004035 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004036 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004037 unaryOp = spv::OpSNegate;
4038 break;
4039
4040 case glslang::EOpLogicalNot:
4041 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004042 unaryOp = spv::OpLogicalNot;
4043 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004044 case glslang::EOpBitwiseNot:
4045 unaryOp = spv::OpNot;
4046 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004047
John Kessenich140f3df2015-06-26 16:58:36 -06004048 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004049 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004053 break;
4054 case glslang::EOpTranspose:
4055 unaryOp = spv::OpTranspose;
4056 break;
4057
4058 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004077 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004078 break;
4079 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004080 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082
4083 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004096 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004097 break;
4098 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004099 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004100 break;
4101
4102 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 break;
4105 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004106 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004107 break;
4108
4109 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004110 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004119 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004120 break;
4121 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004122 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004123 break;
4124 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004125 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004126 break;
4127
4128 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004138 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004141 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004142 break;
4143 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004144 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004145 break;
4146
4147 case glslang::EOpIsNan:
4148 unaryOp = spv::OpIsNan;
4149 break;
4150 case glslang::EOpIsInf:
4151 unaryOp = spv::OpIsInf;
4152 break;
LoopDawg592860c2016-06-09 08:57:35 -06004153 case glslang::EOpIsFinite:
4154 unaryOp = spv::OpIsFinite;
4155 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004156
Rex Xucbc426e2015-12-15 16:03:10 +08004157 case glslang::EOpFloatBitsToInt:
4158 case glslang::EOpFloatBitsToUint:
4159 case glslang::EOpIntBitsToFloat:
4160 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004161 case glslang::EOpDoubleBitsToInt64:
4162 case glslang::EOpDoubleBitsToUint64:
4163 case glslang::EOpInt64BitsToDouble:
4164 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004165#ifdef AMD_EXTENSIONS
4166 case glslang::EOpFloat16BitsToInt16:
4167 case glslang::EOpFloat16BitsToUint16:
4168 case glslang::EOpInt16BitsToFloat16:
4169 case glslang::EOpUint16BitsToFloat16:
4170#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004171 unaryOp = spv::OpBitcast;
4172 break;
4173
John Kessenich140f3df2015-06-26 16:58:36 -06004174 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004175 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
4177 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004178 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 break;
4180 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004181 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004185 break;
4186 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004187 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004188 break;
4189 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004190 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004191 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004192 case glslang::EOpPackSnorm4x8:
4193 libCall = spv::GLSLstd450PackSnorm4x8;
4194 break;
4195 case glslang::EOpUnpackSnorm4x8:
4196 libCall = spv::GLSLstd450UnpackSnorm4x8;
4197 break;
4198 case glslang::EOpPackUnorm4x8:
4199 libCall = spv::GLSLstd450PackUnorm4x8;
4200 break;
4201 case glslang::EOpUnpackUnorm4x8:
4202 libCall = spv::GLSLstd450UnpackUnorm4x8;
4203 break;
4204 case glslang::EOpPackDouble2x32:
4205 libCall = spv::GLSLstd450PackDouble2x32;
4206 break;
4207 case glslang::EOpUnpackDouble2x32:
4208 libCall = spv::GLSLstd450UnpackDouble2x32;
4209 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004210
Rex Xu8ff43de2016-04-22 16:51:45 +08004211 case glslang::EOpPackInt2x32:
4212 case glslang::EOpUnpackInt2x32:
4213 case glslang::EOpPackUint2x32:
4214 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004215 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004216 break;
4217
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004218#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004219 case glslang::EOpPackInt2x16:
4220 case glslang::EOpUnpackInt2x16:
4221 case glslang::EOpPackUint2x16:
4222 case glslang::EOpUnpackUint2x16:
4223 case glslang::EOpPackInt4x16:
4224 case glslang::EOpUnpackInt4x16:
4225 case glslang::EOpPackUint4x16:
4226 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004227 case glslang::EOpPackFloat2x16:
4228 case glslang::EOpUnpackFloat2x16:
4229 unaryOp = spv::OpBitcast;
4230 break;
4231#endif
4232
John Kessenich140f3df2015-06-26 16:58:36 -06004233 case glslang::EOpDPdx:
4234 unaryOp = spv::OpDPdx;
4235 break;
4236 case glslang::EOpDPdy:
4237 unaryOp = spv::OpDPdy;
4238 break;
4239 case glslang::EOpFwidth:
4240 unaryOp = spv::OpFwidth;
4241 break;
4242 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004243 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004244 unaryOp = spv::OpDPdxFine;
4245 break;
4246 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004247 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004248 unaryOp = spv::OpDPdyFine;
4249 break;
4250 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004251 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004252 unaryOp = spv::OpFwidthFine;
4253 break;
4254 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004255 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004256 unaryOp = spv::OpDPdxCoarse;
4257 break;
4258 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004259 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004260 unaryOp = spv::OpDPdyCoarse;
4261 break;
4262 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004263 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004264 unaryOp = spv::OpFwidthCoarse;
4265 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004266 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004267 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004268 libCall = spv::GLSLstd450InterpolateAtCentroid;
4269 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004270 case glslang::EOpAny:
4271 unaryOp = spv::OpAny;
4272 break;
4273 case glslang::EOpAll:
4274 unaryOp = spv::OpAll;
4275 break;
4276
4277 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004278 if (isFloat)
4279 libCall = spv::GLSLstd450FAbs;
4280 else
4281 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004282 break;
4283 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004284 if (isFloat)
4285 libCall = spv::GLSLstd450FSign;
4286 else
4287 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004288 break;
4289
John Kessenichfc51d282015-08-19 13:34:18 -06004290 case glslang::EOpAtomicCounterIncrement:
4291 case glslang::EOpAtomicCounterDecrement:
4292 case glslang::EOpAtomicCounter:
4293 {
4294 // Handle all of the atomics in one place, in createAtomicOperation()
4295 std::vector<spv::Id> operands;
4296 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004297 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004298 }
4299
John Kessenichfc51d282015-08-19 13:34:18 -06004300 case glslang::EOpBitFieldReverse:
4301 unaryOp = spv::OpBitReverse;
4302 break;
4303 case glslang::EOpBitCount:
4304 unaryOp = spv::OpBitCount;
4305 break;
4306 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004307 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004308 break;
4309 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004310 if (isUnsigned)
4311 libCall = spv::GLSLstd450FindUMsb;
4312 else
4313 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004314 break;
4315
Rex Xu574ab042016-04-14 16:53:07 +08004316 case glslang::EOpBallot:
4317 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004318 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004319 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004320 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004321#ifdef AMD_EXTENSIONS
4322 case glslang::EOpMinInvocations:
4323 case glslang::EOpMaxInvocations:
4324 case glslang::EOpAddInvocations:
4325 case glslang::EOpMinInvocationsNonUniform:
4326 case glslang::EOpMaxInvocationsNonUniform:
4327 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004328 case glslang::EOpMinInvocationsInclusiveScan:
4329 case glslang::EOpMaxInvocationsInclusiveScan:
4330 case glslang::EOpAddInvocationsInclusiveScan:
4331 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4332 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4333 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4334 case glslang::EOpMinInvocationsExclusiveScan:
4335 case glslang::EOpMaxInvocationsExclusiveScan:
4336 case glslang::EOpAddInvocationsExclusiveScan:
4337 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4338 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4339 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004340#endif
Rex Xu51596642016-09-21 18:56:12 +08004341 {
4342 std::vector<spv::Id> operands;
4343 operands.push_back(operand);
4344 return createInvocationsOperation(op, typeId, operands, typeProxy);
4345 }
Rex Xu9d93a232016-05-05 12:30:44 +08004346
4347#ifdef AMD_EXTENSIONS
4348 case glslang::EOpMbcnt:
4349 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4350 libCall = spv::MbcntAMD;
4351 break;
4352
4353 case glslang::EOpCubeFaceIndex:
4354 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4355 libCall = spv::CubeFaceIndexAMD;
4356 break;
4357
4358 case glslang::EOpCubeFaceCoord:
4359 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4360 libCall = spv::CubeFaceCoordAMD;
4361 break;
4362#endif
Rex Xu338b1852016-05-05 20:38:33 +08004363
John Kessenich140f3df2015-06-26 16:58:36 -06004364 default:
4365 return 0;
4366 }
4367
4368 spv::Id id;
4369 if (libCall >= 0) {
4370 std::vector<spv::Id> args;
4371 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004372 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004373 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004374 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004375 }
John Kessenich140f3df2015-06-26 16:58:36 -06004376
qining25262b32016-05-06 17:25:16 -04004377 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004378 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004379}
4380
John Kessenich7a53f762016-01-20 11:19:27 -07004381// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004382spv::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 -07004383{
4384 // Handle unary operations vector by vector.
4385 // The result type is the same type as the original type.
4386 // The algorithm is to:
4387 // - break the matrix into vectors
4388 // - apply the operation to each vector
4389 // - make a matrix out the vector results
4390
4391 // get the types sorted out
4392 int numCols = builder.getNumColumns(operand);
4393 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004394 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4395 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004396 std::vector<spv::Id> results;
4397
4398 // do each vector op
4399 for (int c = 0; c < numCols; ++c) {
4400 std::vector<unsigned int> indexes;
4401 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004402 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4403 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4404 addDecoration(destVec, noContraction);
4405 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004406 }
4407
4408 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004409 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004410}
4411
Rex Xu73e3ce72016-04-27 18:48:17 +08004412spv::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 -06004413{
4414 spv::Op convOp = spv::OpNop;
4415 spv::Id zero = 0;
4416 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004417 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004418
4419 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4420
4421 switch (op) {
4422 case glslang::EOpConvIntToBool:
4423 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004424 case glslang::EOpConvInt64ToBool:
4425 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004426#ifdef AMD_EXTENSIONS
4427 case glslang::EOpConvInt16ToBool:
4428 case glslang::EOpConvUint16ToBool:
4429#endif
4430 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4431 zero = builder.makeUint64Constant(0);
4432#ifdef AMD_EXTENSIONS
4433 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4434 zero = builder.makeUint16Constant(0);
4435#endif
4436 else
4437 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004438 zero = makeSmearedConstant(zero, vectorSize);
4439 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4440
4441 case glslang::EOpConvFloatToBool:
4442 zero = builder.makeFloatConstant(0.0F);
4443 zero = makeSmearedConstant(zero, vectorSize);
4444 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4445
4446 case glslang::EOpConvDoubleToBool:
4447 zero = builder.makeDoubleConstant(0.0);
4448 zero = makeSmearedConstant(zero, vectorSize);
4449 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4450
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004451#ifdef AMD_EXTENSIONS
4452 case glslang::EOpConvFloat16ToBool:
4453 zero = builder.makeFloat16Constant(0.0F);
4454 zero = makeSmearedConstant(zero, vectorSize);
4455 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4456#endif
4457
John Kessenich140f3df2015-06-26 16:58:36 -06004458 case glslang::EOpConvBoolToFloat:
4459 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004460 zero = builder.makeFloatConstant(0.0F);
4461 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004462 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004463
John Kessenich140f3df2015-06-26 16:58:36 -06004464 case glslang::EOpConvBoolToDouble:
4465 convOp = spv::OpSelect;
4466 zero = builder.makeDoubleConstant(0.0);
4467 one = builder.makeDoubleConstant(1.0);
4468 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004469
4470#ifdef AMD_EXTENSIONS
4471 case glslang::EOpConvBoolToFloat16:
4472 convOp = spv::OpSelect;
4473 zero = builder.makeFloat16Constant(0.0F);
4474 one = builder.makeFloat16Constant(1.0F);
4475 break;
4476#endif
4477
John Kessenich140f3df2015-06-26 16:58:36 -06004478 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004479 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004480#ifdef AMD_EXTENSIONS
4481 case glslang::EOpConvBoolToInt16:
4482#endif
4483 if (op == glslang::EOpConvBoolToInt64)
4484 zero = builder.makeInt64Constant(0);
4485#ifdef AMD_EXTENSIONS
4486 else if (op == glslang::EOpConvBoolToInt16)
4487 zero = builder.makeInt16Constant(0);
4488#endif
4489 else
4490 zero = builder.makeIntConstant(0);
4491
4492 if (op == glslang::EOpConvBoolToInt64)
4493 one = builder.makeInt64Constant(1);
4494#ifdef AMD_EXTENSIONS
4495 else if (op == glslang::EOpConvBoolToInt16)
4496 one = builder.makeInt16Constant(1);
4497#endif
4498 else
4499 one = builder.makeIntConstant(1);
4500
John Kessenich140f3df2015-06-26 16:58:36 -06004501 convOp = spv::OpSelect;
4502 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004503
John Kessenich140f3df2015-06-26 16:58:36 -06004504 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004505 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004506#ifdef AMD_EXTENSIONS
4507 case glslang::EOpConvBoolToUint16:
4508#endif
4509 if (op == glslang::EOpConvBoolToUint64)
4510 zero = builder.makeUint64Constant(0);
4511#ifdef AMD_EXTENSIONS
4512 else if (op == glslang::EOpConvBoolToUint16)
4513 zero = builder.makeUint16Constant(0);
4514#endif
4515 else
4516 zero = builder.makeUintConstant(0);
4517
4518 if (op == glslang::EOpConvBoolToUint64)
4519 one = builder.makeUint64Constant(1);
4520#ifdef AMD_EXTENSIONS
4521 else if (op == glslang::EOpConvBoolToUint16)
4522 one = builder.makeUint16Constant(1);
4523#endif
4524 else
4525 one = builder.makeUintConstant(1);
4526
John Kessenich140f3df2015-06-26 16:58:36 -06004527 convOp = spv::OpSelect;
4528 break;
4529
4530 case glslang::EOpConvIntToFloat:
4531 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004532 case glslang::EOpConvInt64ToFloat:
4533 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004534#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004535 case glslang::EOpConvInt16ToFloat:
4536 case glslang::EOpConvInt16ToDouble:
4537 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004538 case glslang::EOpConvIntToFloat16:
4539 case glslang::EOpConvInt64ToFloat16:
4540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004541 convOp = spv::OpConvertSToF;
4542 break;
4543
4544 case glslang::EOpConvUintToFloat:
4545 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004546 case glslang::EOpConvUint64ToFloat:
4547 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004548#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004549 case glslang::EOpConvUint16ToFloat:
4550 case glslang::EOpConvUint16ToDouble:
4551 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004552 case glslang::EOpConvUintToFloat16:
4553 case glslang::EOpConvUint64ToFloat16:
4554#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004555 convOp = spv::OpConvertUToF;
4556 break;
4557
4558 case glslang::EOpConvDoubleToFloat:
4559 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004560#ifdef AMD_EXTENSIONS
4561 case glslang::EOpConvDoubleToFloat16:
4562 case glslang::EOpConvFloat16ToDouble:
4563 case glslang::EOpConvFloatToFloat16:
4564 case glslang::EOpConvFloat16ToFloat:
4565#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004566 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004567 if (builder.isMatrixType(destType))
4568 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004569 break;
4570
4571 case glslang::EOpConvFloatToInt:
4572 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004573 case glslang::EOpConvFloatToInt64:
4574 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004575#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004576 case glslang::EOpConvFloatToInt16:
4577 case glslang::EOpConvDoubleToInt16:
4578 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004579 case glslang::EOpConvFloat16ToInt:
4580 case glslang::EOpConvFloat16ToInt64:
4581#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004582 convOp = spv::OpConvertFToS;
4583 break;
4584
4585 case glslang::EOpConvUintToInt:
4586 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004587 case glslang::EOpConvUint64ToInt64:
4588 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004589#ifdef AMD_EXTENSIONS
4590 case glslang::EOpConvUint16ToInt16:
4591 case glslang::EOpConvInt16ToUint16:
4592#endif
qininge24aa5e2016-04-07 15:40:27 -04004593 if (builder.isInSpecConstCodeGenMode()) {
4594 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004595 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4596 zero = builder.makeUint64Constant(0);
4597#ifdef AMD_EXTENSIONS
4598 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4599 zero = builder.makeUint16Constant(0);
4600#endif
4601 else
4602 zero = builder.makeUintConstant(0);
4603
qining189b2032016-04-12 23:16:20 -04004604 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004605 // Use OpIAdd, instead of OpBitcast to do the conversion when
4606 // generating for OpSpecConstantOp instruction.
4607 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4608 }
4609 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004610 convOp = spv::OpBitcast;
4611 break;
4612
4613 case glslang::EOpConvFloatToUint:
4614 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004615 case glslang::EOpConvFloatToUint64:
4616 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004617#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004618 case glslang::EOpConvFloatToUint16:
4619 case glslang::EOpConvDoubleToUint16:
4620 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004621 case glslang::EOpConvFloat16ToUint:
4622 case glslang::EOpConvFloat16ToUint64:
4623#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004624 convOp = spv::OpConvertFToU;
4625 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004626
4627 case glslang::EOpConvIntToInt64:
4628 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004629#ifdef AMD_EXTENSIONS
4630 case glslang::EOpConvIntToInt16:
4631 case glslang::EOpConvInt16ToInt:
4632 case glslang::EOpConvInt64ToInt16:
4633 case glslang::EOpConvInt16ToInt64:
4634#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004635 convOp = spv::OpSConvert;
4636 break;
4637
4638 case glslang::EOpConvUintToUint64:
4639 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004640#ifdef AMD_EXTENSIONS
4641 case glslang::EOpConvUintToUint16:
4642 case glslang::EOpConvUint16ToUint:
4643 case glslang::EOpConvUint64ToUint16:
4644 case glslang::EOpConvUint16ToUint64:
4645#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004646 convOp = spv::OpUConvert;
4647 break;
4648
4649 case glslang::EOpConvIntToUint64:
4650 case glslang::EOpConvInt64ToUint:
4651 case glslang::EOpConvUint64ToInt:
4652 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004653#ifdef AMD_EXTENSIONS
4654 case glslang::EOpConvInt16ToUint:
4655 case glslang::EOpConvUintToInt16:
4656 case glslang::EOpConvInt16ToUint64:
4657 case glslang::EOpConvUint64ToInt16:
4658 case glslang::EOpConvUint16ToInt:
4659 case glslang::EOpConvIntToUint16:
4660 case glslang::EOpConvUint16ToInt64:
4661 case glslang::EOpConvInt64ToUint16:
4662#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004663 // OpSConvert/OpUConvert + OpBitCast
4664 switch (op) {
4665 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004666#ifdef AMD_EXTENSIONS
4667 case glslang::EOpConvInt16ToUint64:
4668#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004669 convOp = spv::OpSConvert;
4670 type = builder.makeIntType(64);
4671 break;
4672 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004673#ifdef AMD_EXTENSIONS
4674 case glslang::EOpConvInt16ToUint:
4675#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004676 convOp = spv::OpSConvert;
4677 type = builder.makeIntType(32);
4678 break;
4679 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004680#ifdef AMD_EXTENSIONS
4681 case glslang::EOpConvUint16ToInt:
4682#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004683 convOp = spv::OpUConvert;
4684 type = builder.makeUintType(32);
4685 break;
4686 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004687#ifdef AMD_EXTENSIONS
4688 case glslang::EOpConvUint16ToInt64:
4689#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004690 convOp = spv::OpUConvert;
4691 type = builder.makeUintType(64);
4692 break;
Rex Xucabbb782017-03-24 13:41:14 +08004693#ifdef AMD_EXTENSIONS
4694 case glslang::EOpConvUintToInt16:
4695 case glslang::EOpConvUint64ToInt16:
4696 convOp = spv::OpUConvert;
4697 type = builder.makeUintType(16);
4698 break;
4699 case glslang::EOpConvIntToUint16:
4700 case glslang::EOpConvInt64ToUint16:
4701 convOp = spv::OpSConvert;
4702 type = builder.makeIntType(16);
4703 break;
4704#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004705 default:
4706 assert(0);
4707 break;
4708 }
4709
4710 if (vectorSize > 0)
4711 type = builder.makeVectorType(type, vectorSize);
4712
4713 operand = builder.createUnaryOp(convOp, type, operand);
4714
4715 if (builder.isInSpecConstCodeGenMode()) {
4716 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004717#ifdef AMD_EXTENSIONS
4718 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4719 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4720 zero = builder.makeUint64Constant(0);
4721 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4722 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4723 zero = builder.makeUint16Constant(0);
4724 else
4725 zero = builder.makeUintConstant(0);
4726#else
4727 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4728 zero = builder.makeUint64Constant(0);
4729 else
4730 zero = builder.makeUintConstant(0);
4731#endif
4732
Rex Xu8ff43de2016-04-22 16:51:45 +08004733 zero = makeSmearedConstant(zero, vectorSize);
4734 // Use OpIAdd, instead of OpBitcast to do the conversion when
4735 // generating for OpSpecConstantOp instruction.
4736 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4737 }
4738 // For normal run-time conversion instruction, use OpBitcast.
4739 convOp = spv::OpBitcast;
4740 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004741 default:
4742 break;
4743 }
4744
4745 spv::Id result = 0;
4746 if (convOp == spv::OpNop)
4747 return result;
4748
4749 if (convOp == spv::OpSelect) {
4750 zero = makeSmearedConstant(zero, vectorSize);
4751 one = makeSmearedConstant(one, vectorSize);
4752 result = builder.createTriOp(convOp, destType, operand, one, zero);
4753 } else
4754 result = builder.createUnaryOp(convOp, destType, operand);
4755
John Kessenich32cfd492016-02-02 12:37:46 -07004756 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004757}
4758
4759spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4760{
4761 if (vectorSize == 0)
4762 return constant;
4763
4764 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4765 std::vector<spv::Id> components;
4766 for (int c = 0; c < vectorSize; ++c)
4767 components.push_back(constant);
4768 return builder.makeCompositeConstant(vectorTypeId, components);
4769}
4770
John Kessenich426394d2015-07-23 10:22:48 -06004771// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004772spv::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 -06004773{
4774 spv::Op opCode = spv::OpNop;
4775
4776 switch (op) {
4777 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004778 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004779 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004780 opCode = spv::OpAtomicIAdd;
4781 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004782 case glslang::EOpAtomicCounterSubtract:
4783 opCode = spv::OpAtomicISub;
4784 break;
John Kessenich426394d2015-07-23 10:22:48 -06004785 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004786 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004787 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004788 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004789 break;
4790 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004791 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004792 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004793 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004794 break;
4795 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004796 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004797 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004798 opCode = spv::OpAtomicAnd;
4799 break;
4800 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004801 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004802 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004803 opCode = spv::OpAtomicOr;
4804 break;
4805 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004806 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004807 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004808 opCode = spv::OpAtomicXor;
4809 break;
4810 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004811 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004812 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004813 opCode = spv::OpAtomicExchange;
4814 break;
4815 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004816 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004817 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004818 opCode = spv::OpAtomicCompareExchange;
4819 break;
4820 case glslang::EOpAtomicCounterIncrement:
4821 opCode = spv::OpAtomicIIncrement;
4822 break;
4823 case glslang::EOpAtomicCounterDecrement:
4824 opCode = spv::OpAtomicIDecrement;
4825 break;
4826 case glslang::EOpAtomicCounter:
4827 opCode = spv::OpAtomicLoad;
4828 break;
4829 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004830 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004831 break;
4832 }
4833
Rex Xue8fe8b02017-09-26 15:42:56 +08004834 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4835 builder.addCapability(spv::CapabilityInt64Atomics);
4836
John Kessenich426394d2015-07-23 10:22:48 -06004837 // Sort out the operands
4838 // - mapping from glslang -> SPV
4839 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004840 // - compare-exchange swaps the value and comparator
4841 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004842 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004843 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4844 auto opIt = operands.begin(); // walk the glslang operands
4845 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004846 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4847 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4848 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004849 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4850 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004851 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004852 spvAtomicOperands.push_back(*(opIt + 1));
4853 spvAtomicOperands.push_back(*opIt);
4854 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004855 }
John Kessenich426394d2015-07-23 10:22:48 -06004856
John Kessenich3e60a6f2015-09-14 22:45:16 -06004857 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004858 for (; opIt != operands.end(); ++opIt)
4859 spvAtomicOperands.push_back(*opIt);
4860
John Kessenich48d6e792017-10-06 21:21:48 -06004861 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4862
4863 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4864 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4865 if (op == glslang::EOpAtomicCounterDecrement)
4866 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4867
4868 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004869}
4870
John Kessenich91cef522016-05-05 16:45:40 -06004871// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004872spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004873{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004874#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004875 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004876 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004877#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004878
Rex Xu51596642016-09-21 18:56:12 +08004879 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004880 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004881 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4882
chaocf200da82016-12-20 12:44:35 -08004883 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4884 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004885 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4886 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004887 } else if (op == glslang::EOpAnyInvocation ||
4888 op == glslang::EOpAllInvocations ||
4889 op == glslang::EOpAllInvocationsEqual) {
4890 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4891 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004892 } else {
4893 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004894#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004895 if (op == glslang::EOpMinInvocationsNonUniform ||
4896 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004897 op == glslang::EOpAddInvocationsNonUniform ||
4898 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4899 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4900 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4901 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4902 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4903 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004904 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004905#endif
Rex Xu51596642016-09-21 18:56:12 +08004906
4907 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004908#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004909 switch (op) {
4910 case glslang::EOpMinInvocations:
4911 case glslang::EOpMaxInvocations:
4912 case glslang::EOpAddInvocations:
4913 case glslang::EOpMinInvocationsNonUniform:
4914 case glslang::EOpMaxInvocationsNonUniform:
4915 case glslang::EOpAddInvocationsNonUniform:
4916 groupOperation = spv::GroupOperationReduce;
4917 spvGroupOperands.push_back(groupOperation);
4918 break;
4919 case glslang::EOpMinInvocationsInclusiveScan:
4920 case glslang::EOpMaxInvocationsInclusiveScan:
4921 case glslang::EOpAddInvocationsInclusiveScan:
4922 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4923 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4924 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4925 groupOperation = spv::GroupOperationInclusiveScan;
4926 spvGroupOperands.push_back(groupOperation);
4927 break;
4928 case glslang::EOpMinInvocationsExclusiveScan:
4929 case glslang::EOpMaxInvocationsExclusiveScan:
4930 case glslang::EOpAddInvocationsExclusiveScan:
4931 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4932 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4933 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4934 groupOperation = spv::GroupOperationExclusiveScan;
4935 spvGroupOperands.push_back(groupOperation);
4936 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004937 default:
4938 break;
Rex Xu430ef402016-10-14 17:22:23 +08004939 }
Rex Xu9d93a232016-05-05 12:30:44 +08004940#endif
Rex Xu51596642016-09-21 18:56:12 +08004941 }
4942
4943 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4944 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004945
4946 switch (op) {
4947 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004948 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004949 break;
John Kessenich91cef522016-05-05 16:45:40 -06004950 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004951 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004952 break;
John Kessenich91cef522016-05-05 16:45:40 -06004953 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004954 opCode = spv::OpSubgroupAllEqualKHR;
4955 break;
Rex Xu51596642016-09-21 18:56:12 +08004956 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004957 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004958 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004959 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004960 break;
4961 case glslang::EOpReadFirstInvocation:
4962 opCode = spv::OpSubgroupFirstInvocationKHR;
4963 break;
4964 case glslang::EOpBallot:
4965 {
4966 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4967 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4968 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4969 //
4970 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4971 //
4972 spv::Id uintType = builder.makeUintType(32);
4973 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4974 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4975
4976 std::vector<spv::Id> components;
4977 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4978 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4979
4980 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4981 return builder.createUnaryOp(spv::OpBitcast, typeId,
4982 builder.createCompositeConstruct(uvec2Type, components));
4983 }
4984
Rex Xu9d93a232016-05-05 12:30:44 +08004985#ifdef AMD_EXTENSIONS
4986 case glslang::EOpMinInvocations:
4987 case glslang::EOpMaxInvocations:
4988 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004989 case glslang::EOpMinInvocationsInclusiveScan:
4990 case glslang::EOpMaxInvocationsInclusiveScan:
4991 case glslang::EOpAddInvocationsInclusiveScan:
4992 case glslang::EOpMinInvocationsExclusiveScan:
4993 case glslang::EOpMaxInvocationsExclusiveScan:
4994 case glslang::EOpAddInvocationsExclusiveScan:
4995 if (op == glslang::EOpMinInvocations ||
4996 op == glslang::EOpMinInvocationsInclusiveScan ||
4997 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004998 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004999 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005000 else {
5001 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005002 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005003 else
Rex Xu51596642016-09-21 18:56:12 +08005004 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005005 }
Rex Xu430ef402016-10-14 17:22:23 +08005006 } else if (op == glslang::EOpMaxInvocations ||
5007 op == glslang::EOpMaxInvocationsInclusiveScan ||
5008 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005009 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005010 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005011 else {
5012 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005013 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005014 else
Rex Xu51596642016-09-21 18:56:12 +08005015 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005016 }
5017 } else {
5018 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005019 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005020 else
Rex Xu51596642016-09-21 18:56:12 +08005021 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005022 }
5023
Rex Xu2bbbe062016-08-23 15:41:05 +08005024 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005025 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005026
5027 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005028 case glslang::EOpMinInvocationsNonUniform:
5029 case glslang::EOpMaxInvocationsNonUniform:
5030 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005031 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5032 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5033 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5034 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5035 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5036 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5037 if (op == glslang::EOpMinInvocationsNonUniform ||
5038 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5039 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005040 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005041 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005042 else {
5043 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005044 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005045 else
Rex Xu51596642016-09-21 18:56:12 +08005046 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005047 }
5048 }
Rex Xu430ef402016-10-14 17:22:23 +08005049 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5050 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5051 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005052 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005053 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005054 else {
5055 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005056 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005057 else
Rex Xu51596642016-09-21 18:56:12 +08005058 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005059 }
5060 }
5061 else {
5062 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005063 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005064 else
Rex Xu51596642016-09-21 18:56:12 +08005065 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005066 }
5067
Rex Xu2bbbe062016-08-23 15:41:05 +08005068 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005069 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005070
5071 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005072#endif
John Kessenich91cef522016-05-05 16:45:40 -06005073 default:
5074 logger->missingFunctionality("invocation operation");
5075 return spv::NoResult;
5076 }
Rex Xu51596642016-09-21 18:56:12 +08005077
5078 assert(opCode != spv::OpNop);
5079 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005080}
5081
Rex Xu2bbbe062016-08-23 15:41:05 +08005082// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005083spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005084{
Rex Xub7072052016-09-26 15:53:40 +08005085#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005086 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5087 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005088 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005089 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005090 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5091 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5092 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005093#else
5094 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5095 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005096 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5097 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005098#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005099
5100 // Handle group invocation operations scalar by scalar.
5101 // The result type is the same type as the original type.
5102 // The algorithm is to:
5103 // - break the vector into scalars
5104 // - apply the operation to each scalar
5105 // - make a vector out the scalar results
5106
5107 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005108 int numComponents = builder.getNumComponents(operands[0]);
5109 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005110 std::vector<spv::Id> results;
5111
5112 // do each scalar op
5113 for (int comp = 0; comp < numComponents; ++comp) {
5114 std::vector<unsigned int> indexes;
5115 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005116 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005117 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005118 if (op == spv::OpSubgroupReadInvocationKHR) {
5119 spvGroupOperands.push_back(scalar);
5120 spvGroupOperands.push_back(operands[1]);
5121 } else if (op == spv::OpGroupBroadcast) {
5122 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005123 spvGroupOperands.push_back(scalar);
5124 spvGroupOperands.push_back(operands[1]);
5125 } else {
chaocf200da82016-12-20 12:44:35 -08005126 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005127 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005128 spvGroupOperands.push_back(scalar);
5129 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005130
Rex Xub7072052016-09-26 15:53:40 +08005131 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005132 }
5133
5134 // put the pieces together
5135 return builder.createCompositeConstruct(typeId, results);
5136}
Rex Xu2bbbe062016-08-23 15:41:05 +08005137
John Kessenich5e4b1242015-08-06 22:53:06 -06005138spv::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 -06005139{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005140#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005141 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005142 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5143#else
Rex Xucabbb782017-03-24 13:41:14 +08005144 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005145 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005146#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005147
John Kessenich140f3df2015-06-26 16:58:36 -06005148 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005149 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005150 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005151 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005152 spv::Id typeId0 = 0;
5153 if (consumedOperands > 0)
5154 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005155 spv::Id typeId1 = 0;
5156 if (consumedOperands > 1)
5157 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005158 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005159
5160 switch (op) {
5161 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005162 if (isFloat)
5163 libCall = spv::GLSLstd450FMin;
5164 else if (isUnsigned)
5165 libCall = spv::GLSLstd450UMin;
5166 else
5167 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005168 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005169 break;
5170 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005171 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005172 break;
5173 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005174 if (isFloat)
5175 libCall = spv::GLSLstd450FMax;
5176 else if (isUnsigned)
5177 libCall = spv::GLSLstd450UMax;
5178 else
5179 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005180 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005181 break;
5182 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005183 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005184 break;
5185 case glslang::EOpDot:
5186 opCode = spv::OpDot;
5187 break;
5188 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005189 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005190 break;
5191
5192 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005193 if (isFloat)
5194 libCall = spv::GLSLstd450FClamp;
5195 else if (isUnsigned)
5196 libCall = spv::GLSLstd450UClamp;
5197 else
5198 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005199 builder.promoteScalar(precision, operands.front(), operands[1]);
5200 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005201 break;
5202 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005203 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5204 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005205 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005206 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005207 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005208 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005209 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005210 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005211 break;
5212 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005213 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005214 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005215 break;
5216 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005217 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005218 builder.promoteScalar(precision, operands[0], operands[2]);
5219 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005220 break;
5221
5222 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005223 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005224 break;
5225 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005226 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005227 break;
5228 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005229 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005230 break;
5231 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005232 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005233 break;
5234 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005235 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005236 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005237 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005238 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005239 libCall = spv::GLSLstd450InterpolateAtSample;
5240 break;
5241 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005242 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005243 libCall = spv::GLSLstd450InterpolateAtOffset;
5244 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005245 case glslang::EOpAddCarry:
5246 opCode = spv::OpIAddCarry;
5247 typeId = builder.makeStructResultType(typeId0, typeId0);
5248 consumedOperands = 2;
5249 break;
5250 case glslang::EOpSubBorrow:
5251 opCode = spv::OpISubBorrow;
5252 typeId = builder.makeStructResultType(typeId0, typeId0);
5253 consumedOperands = 2;
5254 break;
5255 case glslang::EOpUMulExtended:
5256 opCode = spv::OpUMulExtended;
5257 typeId = builder.makeStructResultType(typeId0, typeId0);
5258 consumedOperands = 2;
5259 break;
5260 case glslang::EOpIMulExtended:
5261 opCode = spv::OpSMulExtended;
5262 typeId = builder.makeStructResultType(typeId0, typeId0);
5263 consumedOperands = 2;
5264 break;
5265 case glslang::EOpBitfieldExtract:
5266 if (isUnsigned)
5267 opCode = spv::OpBitFieldUExtract;
5268 else
5269 opCode = spv::OpBitFieldSExtract;
5270 break;
5271 case glslang::EOpBitfieldInsert:
5272 opCode = spv::OpBitFieldInsert;
5273 break;
5274
5275 case glslang::EOpFma:
5276 libCall = spv::GLSLstd450Fma;
5277 break;
5278 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005279 {
5280 libCall = spv::GLSLstd450FrexpStruct;
5281 assert(builder.isPointerType(typeId1));
5282 typeId1 = builder.getContainedTypeId(typeId1);
5283#ifdef AMD_EXTENSIONS
5284 int width = builder.getScalarTypeWidth(typeId1);
5285#else
5286 int width = 32;
5287#endif
5288 if (builder.getNumComponents(operands[0]) == 1)
5289 frexpIntType = builder.makeIntegerType(width, true);
5290 else
5291 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5292 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5293 consumedOperands = 1;
5294 }
John Kessenich55e7d112015-11-15 21:33:39 -07005295 break;
5296 case glslang::EOpLdexp:
5297 libCall = spv::GLSLstd450Ldexp;
5298 break;
5299
Rex Xu574ab042016-04-14 16:53:07 +08005300 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005301 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005302
Rex Xu9d93a232016-05-05 12:30:44 +08005303#ifdef AMD_EXTENSIONS
5304 case glslang::EOpSwizzleInvocations:
5305 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5306 libCall = spv::SwizzleInvocationsAMD;
5307 break;
5308 case glslang::EOpSwizzleInvocationsMasked:
5309 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5310 libCall = spv::SwizzleInvocationsMaskedAMD;
5311 break;
5312 case glslang::EOpWriteInvocation:
5313 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5314 libCall = spv::WriteInvocationAMD;
5315 break;
5316
5317 case glslang::EOpMin3:
5318 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5319 if (isFloat)
5320 libCall = spv::FMin3AMD;
5321 else {
5322 if (isUnsigned)
5323 libCall = spv::UMin3AMD;
5324 else
5325 libCall = spv::SMin3AMD;
5326 }
5327 break;
5328 case glslang::EOpMax3:
5329 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5330 if (isFloat)
5331 libCall = spv::FMax3AMD;
5332 else {
5333 if (isUnsigned)
5334 libCall = spv::UMax3AMD;
5335 else
5336 libCall = spv::SMax3AMD;
5337 }
5338 break;
5339 case glslang::EOpMid3:
5340 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5341 if (isFloat)
5342 libCall = spv::FMid3AMD;
5343 else {
5344 if (isUnsigned)
5345 libCall = spv::UMid3AMD;
5346 else
5347 libCall = spv::SMid3AMD;
5348 }
5349 break;
5350
5351 case glslang::EOpInterpolateAtVertex:
5352 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5353 libCall = spv::InterpolateAtVertexAMD;
5354 break;
5355#endif
5356
John Kessenich140f3df2015-06-26 16:58:36 -06005357 default:
5358 return 0;
5359 }
5360
5361 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005362 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005363 // Use an extended instruction from the standard library.
5364 // Construct the call arguments, without modifying the original operands vector.
5365 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5366 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005367 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005368 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005369 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005370 case 0:
5371 // should all be handled by visitAggregate and createNoArgOperation
5372 assert(0);
5373 return 0;
5374 case 1:
5375 // should all be handled by createUnaryOperation
5376 assert(0);
5377 return 0;
5378 case 2:
5379 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5380 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005381 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005382 // anything 3 or over doesn't have l-value operands, so all should be consumed
5383 assert(consumedOperands == operands.size());
5384 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005385 break;
5386 }
5387 }
5388
John Kessenich55e7d112015-11-15 21:33:39 -07005389 // Decode the return types that were structures
5390 switch (op) {
5391 case glslang::EOpAddCarry:
5392 case glslang::EOpSubBorrow:
5393 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5394 id = builder.createCompositeExtract(id, typeId0, 0);
5395 break;
5396 case glslang::EOpUMulExtended:
5397 case glslang::EOpIMulExtended:
5398 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5399 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5400 break;
5401 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005402 {
5403 assert(operands.size() == 2);
5404 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5405 // "exp" is floating-point type (from HLSL intrinsic)
5406 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5407 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5408 builder.createStore(member1, operands[1]);
5409 } else
5410 // "exp" is integer type (from GLSL built-in function)
5411 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5412 id = builder.createCompositeExtract(id, typeId0, 0);
5413 }
John Kessenich55e7d112015-11-15 21:33:39 -07005414 break;
5415 default:
5416 break;
5417 }
5418
John Kessenich32cfd492016-02-02 12:37:46 -07005419 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005420}
5421
Rex Xu9d93a232016-05-05 12:30:44 +08005422// Intrinsics with no arguments (or no return value, and no precision).
5423spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005424{
5425 // TODO: get the barrier operands correct
5426
5427 switch (op) {
5428 case glslang::EOpEmitVertex:
5429 builder.createNoResultOp(spv::OpEmitVertex);
5430 return 0;
5431 case glslang::EOpEndPrimitive:
5432 builder.createNoResultOp(spv::OpEndPrimitive);
5433 return 0;
5434 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005435 if (glslangIntermediate->getStage() == EShLangTessControl) {
5436 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5437 // TODO: prefer the following, when available:
5438 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5439 // spv::MemorySemanticsPatchMask |
5440 // spv::MemorySemanticsAcquireReleaseMask);
5441 } else {
5442 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5443 spv::MemorySemanticsWorkgroupMemoryMask |
5444 spv::MemorySemanticsAcquireReleaseMask);
5445 }
John Kessenich140f3df2015-06-26 16:58:36 -06005446 return 0;
5447 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005448 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5449 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005450 return 0;
5451 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005452 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5453 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005454 return 0;
5455 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005456 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5457 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005458 return 0;
5459 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005460 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5461 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005462 return 0;
5463 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005464 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5465 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005466 return 0;
5467 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005468 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5469 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005470 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005471 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005472 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005473 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005474 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005475 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005476 case glslang::EOpDeviceMemoryBarrier:
5477 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5478 spv::MemorySemanticsImageMemoryMask |
5479 spv::MemorySemanticsAcquireReleaseMask);
5480 return 0;
5481 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5482 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5483 spv::MemorySemanticsImageMemoryMask |
5484 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005485 return 0;
5486 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005487 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5488 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005489 return 0;
5490 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005491 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5492 spv::MemorySemanticsWorkgroupMemoryMask |
5493 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005494 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005495#ifdef AMD_EXTENSIONS
5496 case glslang::EOpTime:
5497 {
5498 std::vector<spv::Id> args; // Dummy arguments
5499 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5500 return builder.setPrecision(id, precision);
5501 }
5502#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005503 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005504 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005505 return 0;
5506 }
5507}
5508
5509spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5510{
John Kessenich2f273362015-07-18 22:34:27 -06005511 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005512 spv::Id id;
5513 if (symbolValues.end() != iter) {
5514 id = iter->second;
5515 return id;
5516 }
5517
5518 // it was not found, create it
5519 id = createSpvVariable(symbol);
5520 symbolValues[symbol->getId()] = id;
5521
Rex Xuc884b4a2016-06-29 15:03:44 +08005522 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005523 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005524 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005525 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005526 if (symbol->getType().getQualifier().hasSpecConstantId())
5527 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005528 if (symbol->getQualifier().hasIndex())
5529 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5530 if (symbol->getQualifier().hasComponent())
5531 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005532 // atomic counters use this:
5533 if (symbol->getQualifier().hasOffset())
5534 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005535 }
5536
scygan2c864272016-05-18 18:09:17 +02005537 if (symbol->getQualifier().hasLocation())
5538 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005539 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005540 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005541 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005542 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005543 }
John Kessenich140f3df2015-06-26 16:58:36 -06005544 if (symbol->getQualifier().hasSet())
5545 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005546 else if (IsDescriptorResource(symbol->getType())) {
5547 // default to 0
5548 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5549 }
John Kessenich140f3df2015-06-26 16:58:36 -06005550 if (symbol->getQualifier().hasBinding())
5551 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005552 if (symbol->getQualifier().hasAttachment())
5553 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005554 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005555 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005556 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005557 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005558 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005559 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005560 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5561 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5562 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5563 }
5564 if (symbol->getQualifier().hasXfbOffset())
5565 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005566 }
5567
Rex Xu1da878f2016-02-21 20:59:01 +08005568 if (symbol->getType().isImage()) {
5569 std::vector<spv::Decoration> memory;
5570 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5571 for (unsigned int i = 0; i < memory.size(); ++i)
5572 addDecoration(id, memory[i]);
5573 }
5574
John Kessenich140f3df2015-06-26 16:58:36 -06005575 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005576 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005577 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005578 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005579
John Kessenichecba76f2017-01-06 00:34:48 -07005580#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005581 if (builtIn == spv::BuiltInSampleMask) {
5582 spv::Decoration decoration;
5583 // GL_NV_sample_mask_override_coverage extension
5584 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005585 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005586 else
5587 decoration = (spv::Decoration)spv::DecorationMax;
5588 addDecoration(id, decoration);
5589 if (decoration != spv::DecorationMax) {
5590 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5591 }
5592 }
chaoc771d89f2017-01-13 01:10:53 -08005593 else if (builtIn == spv::BuiltInLayer) {
5594 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005595 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005596 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5597 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5598 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5599 }
John Kessenichb41bff62017-08-11 13:07:17 -06005600 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005601 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5602 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5603 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5604 }
5605 }
5606
chaoc6e5acae2016-12-20 13:28:52 -08005607 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005608 addDecoration(id, spv::DecorationPassthroughNV);
5609 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005610 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5611 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005612#endif
5613
John Kessenich140f3df2015-06-26 16:58:36 -06005614 return id;
5615}
5616
John Kessenich55e7d112015-11-15 21:33:39 -07005617// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005618void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5619{
John Kessenich4016e382016-07-15 11:53:56 -06005620 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005621 builder.addDecoration(id, dec);
5622}
5623
John Kessenich55e7d112015-11-15 21:33:39 -07005624// If 'dec' is valid, add a one-operand decoration to an object
5625void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5626{
John Kessenich4016e382016-07-15 11:53:56 -06005627 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005628 builder.addDecoration(id, dec, value);
5629}
5630
5631// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005632void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5633{
John Kessenich4016e382016-07-15 11:53:56 -06005634 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005635 builder.addMemberDecoration(id, (unsigned)member, dec);
5636}
5637
John Kessenich92187592016-02-01 13:45:25 -07005638// If 'dec' is valid, add a one-operand decoration to a struct member
5639void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5640{
John Kessenich4016e382016-07-15 11:53:56 -06005641 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005642 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5643}
5644
John Kessenich55e7d112015-11-15 21:33:39 -07005645// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005646// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005647//
5648// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5649//
5650// Recursively walk the nodes. The nodes form a tree whose leaves are
5651// regular constants, which themselves are trees that createSpvConstant()
5652// recursively walks. So, this function walks the "top" of the tree:
5653// - emit specialization constant-building instructions for specConstant
5654// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005655spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005656{
John Kessenich7cc0e282016-03-20 00:46:02 -06005657 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005658
qining4f4bb812016-04-03 23:55:17 -04005659 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005660 if (! node.getQualifier().specConstant) {
5661 // hand off to the non-spec-constant path
5662 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5663 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005664 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005665 nextConst, false);
5666 }
5667
5668 // We now know we have a specialization constant to build
5669
John Kessenichd94c0032016-05-30 19:29:40 -06005670 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005671 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5672 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5673 std::vector<spv::Id> dimConstId;
5674 for (int dim = 0; dim < 3; ++dim) {
5675 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5676 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5677 if (specConst)
5678 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5679 }
5680 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5681 }
5682
5683 // An AST node labelled as specialization constant should be a symbol node.
5684 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5685 if (auto* sn = node.getAsSymbolNode()) {
5686 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005687 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5688 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5689 // will set the builder into spec constant op instruction generating mode.
5690 sub_tree->traverse(this);
5691 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005692 } else if (auto* const_union_array = &sn->getConstArray()){
5693 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005694 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5695 builder.addName(id, sn->getName().c_str());
5696 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005697 }
5698 }
qining4f4bb812016-04-03 23:55:17 -04005699
5700 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5701 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005702 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005703 exit(1);
5704 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005705}
5706
John Kessenich140f3df2015-06-26 16:58:36 -06005707// Use 'consts' as the flattened glslang source of scalar constants to recursively
5708// build the aggregate SPIR-V constant.
5709//
5710// If there are not enough elements present in 'consts', 0 will be substituted;
5711// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5712//
qining08408382016-03-21 09:51:37 -04005713spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005714{
5715 // vector of constants for SPIR-V
5716 std::vector<spv::Id> spvConsts;
5717
5718 // Type is used for struct and array constants
5719 spv::Id typeId = convertGlslangToSpvType(glslangType);
5720
5721 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005722 glslang::TType elementType(glslangType, 0);
5723 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005724 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005725 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005726 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005727 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005728 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005729 } else if (glslangType.getStruct()) {
5730 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5731 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005732 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005733 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005734 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5735 bool zero = nextConst >= consts.size();
5736 switch (glslangType.getBasicType()) {
5737 case glslang::EbtInt:
5738 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5739 break;
5740 case glslang::EbtUint:
5741 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5742 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005743 case glslang::EbtInt64:
5744 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5745 break;
5746 case glslang::EbtUint64:
5747 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5748 break;
Rex Xucabbb782017-03-24 13:41:14 +08005749#ifdef AMD_EXTENSIONS
5750 case glslang::EbtInt16:
5751 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5752 break;
5753 case glslang::EbtUint16:
5754 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5755 break;
5756#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005757 case glslang::EbtFloat:
5758 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5759 break;
5760 case glslang::EbtDouble:
5761 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5762 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005763#ifdef AMD_EXTENSIONS
5764 case glslang::EbtFloat16:
5765 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5766 break;
5767#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005768 case glslang::EbtBool:
5769 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5770 break;
5771 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005772 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005773 break;
5774 }
5775 ++nextConst;
5776 }
5777 } else {
5778 // we have a non-aggregate (scalar) constant
5779 bool zero = nextConst >= consts.size();
5780 spv::Id scalar = 0;
5781 switch (glslangType.getBasicType()) {
5782 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005783 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005784 break;
5785 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005786 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005788 case glslang::EbtInt64:
5789 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5790 break;
5791 case glslang::EbtUint64:
5792 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5793 break;
Rex Xucabbb782017-03-24 13:41:14 +08005794#ifdef AMD_EXTENSIONS
5795 case glslang::EbtInt16:
5796 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5797 break;
5798 case glslang::EbtUint16:
5799 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5800 break;
5801#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005802 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005803 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005804 break;
5805 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005806 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005807 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005808#ifdef AMD_EXTENSIONS
5809 case glslang::EbtFloat16:
5810 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5811 break;
5812#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005813 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005814 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005815 break;
5816 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005817 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005818 break;
5819 }
5820 ++nextConst;
5821 return scalar;
5822 }
5823
5824 return builder.makeCompositeConstant(typeId, spvConsts);
5825}
5826
John Kessenich7c1aa102015-10-15 13:29:11 -06005827// Return true if the node is a constant or symbol whose reading has no
5828// non-trivial observable cost or effect.
5829bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5830{
5831 // don't know what this is
5832 if (node == nullptr)
5833 return false;
5834
5835 // a constant is safe
5836 if (node->getAsConstantUnion() != nullptr)
5837 return true;
5838
5839 // not a symbol means non-trivial
5840 if (node->getAsSymbolNode() == nullptr)
5841 return false;
5842
5843 // a symbol, depends on what's being read
5844 switch (node->getType().getQualifier().storage) {
5845 case glslang::EvqTemporary:
5846 case glslang::EvqGlobal:
5847 case glslang::EvqIn:
5848 case glslang::EvqInOut:
5849 case glslang::EvqConst:
5850 case glslang::EvqConstReadOnly:
5851 case glslang::EvqUniform:
5852 return true;
5853 default:
5854 return false;
5855 }
qining25262b32016-05-06 17:25:16 -04005856}
John Kessenich7c1aa102015-10-15 13:29:11 -06005857
5858// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005859// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005860// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005861// Return true if trivial.
5862bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5863{
5864 if (node == nullptr)
5865 return false;
5866
John Kessenich84cc15f2017-05-24 16:44:47 -06005867 // count non scalars as trivial, as well as anything coming from HLSL
5868 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005869 return true;
5870
John Kessenich7c1aa102015-10-15 13:29:11 -06005871 // symbols and constants are trivial
5872 if (isTrivialLeaf(node))
5873 return true;
5874
5875 // otherwise, it needs to be a simple operation or one or two leaf nodes
5876
5877 // not a simple operation
5878 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5879 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5880 if (binaryNode == nullptr && unaryNode == nullptr)
5881 return false;
5882
5883 // not on leaf nodes
5884 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5885 return false;
5886
5887 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5888 return false;
5889 }
5890
5891 switch (node->getAsOperator()->getOp()) {
5892 case glslang::EOpLogicalNot:
5893 case glslang::EOpConvIntToBool:
5894 case glslang::EOpConvUintToBool:
5895 case glslang::EOpConvFloatToBool:
5896 case glslang::EOpConvDoubleToBool:
5897 case glslang::EOpEqual:
5898 case glslang::EOpNotEqual:
5899 case glslang::EOpLessThan:
5900 case glslang::EOpGreaterThan:
5901 case glslang::EOpLessThanEqual:
5902 case glslang::EOpGreaterThanEqual:
5903 case glslang::EOpIndexDirect:
5904 case glslang::EOpIndexDirectStruct:
5905 case glslang::EOpLogicalXor:
5906 case glslang::EOpAny:
5907 case glslang::EOpAll:
5908 return true;
5909 default:
5910 return false;
5911 }
5912}
5913
5914// Emit short-circuiting code, where 'right' is never evaluated unless
5915// the left side is true (for &&) or false (for ||).
5916spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5917{
5918 spv::Id boolTypeId = builder.makeBoolType();
5919
5920 // emit left operand
5921 builder.clearAccessChain();
5922 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005923 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005924
5925 // Operands to accumulate OpPhi operands
5926 std::vector<spv::Id> phiOperands;
5927 // accumulate left operand's phi information
5928 phiOperands.push_back(leftId);
5929 phiOperands.push_back(builder.getBuildPoint()->getId());
5930
5931 // Make the two kinds of operation symmetric with a "!"
5932 // || => emit "if (! left) result = right"
5933 // && => emit "if ( left) result = right"
5934 //
5935 // TODO: this runtime "not" for || could be avoided by adding functionality
5936 // to 'builder' to have an "else" without an "then"
5937 if (op == glslang::EOpLogicalOr)
5938 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5939
5940 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005941 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005942
5943 // emit right operand as the "then" part of the "if"
5944 builder.clearAccessChain();
5945 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005946 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005947
5948 // accumulate left operand's phi information
5949 phiOperands.push_back(rightId);
5950 phiOperands.push_back(builder.getBuildPoint()->getId());
5951
5952 // finish the "if"
5953 ifBuilder.makeEndIf();
5954
5955 // phi together the two results
5956 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5957}
5958
Frank Henigman541f7bb2018-01-16 00:18:26 -05005959#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08005960// Return type Id of the imported set of extended instructions corresponds to the name.
5961// Import this set if it has not been imported yet.
5962spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5963{
5964 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5965 return extBuiltinMap[name];
5966 else {
Rex Xu51596642016-09-21 18:56:12 +08005967 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005968 spv::Id extBuiltins = builder.import(name);
5969 extBuiltinMap[name] = extBuiltins;
5970 return extBuiltins;
5971 }
5972}
Frank Henigman541f7bb2018-01-16 00:18:26 -05005973#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005974
John Kessenich140f3df2015-06-26 16:58:36 -06005975}; // end anonymous namespace
5976
5977namespace glslang {
5978
John Kessenich68d78fd2015-07-12 19:28:10 -06005979void GetSpirvVersion(std::string& version)
5980{
John Kessenich9e55f632015-07-15 10:03:39 -06005981 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005982 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005983 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005984 version = buf;
5985}
5986
John Kessenicha372a3e2017-11-02 22:32:14 -06005987// For low-order part of the generator's magic number. Bump up
5988// when there is a change in the style (e.g., if SSA form changes,
5989// or a different instruction sequence to do something gets used).
5990int GetSpirvGeneratorVersion()
5991{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07005992 // return 1; // start
5993 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
5994 return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenicha372a3e2017-11-02 22:32:14 -06005995}
5996
John Kessenich140f3df2015-06-26 16:58:36 -06005997// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005998void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005999{
6000 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006001 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006002 if (out.fail())
6003 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006004 for (int i = 0; i < (int)spirv.size(); ++i) {
6005 unsigned int word = spirv[i];
6006 out.write((const char*)&word, 4);
6007 }
6008 out.close();
6009}
6010
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006011// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006012void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006013{
6014 std::ofstream out;
6015 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006016 if (out.fail())
6017 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006018 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006019 if (varName != nullptr) {
6020 out << "\t #pragma once" << std::endl;
6021 out << "const uint32_t " << varName << "[] = {" << std::endl;
6022 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006023 const int WORDS_PER_LINE = 8;
6024 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6025 out << "\t";
6026 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6027 const unsigned int word = spirv[i + j];
6028 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6029 if (i + j + 1 < (int)spirv.size()) {
6030 out << ",";
6031 }
6032 }
6033 out << std::endl;
6034 }
Flavio15017db2017-02-15 14:29:33 -08006035 if (varName != nullptr) {
6036 out << "};";
6037 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006038 out.close();
6039}
6040
GregFcd1f1692017-09-21 18:40:22 -06006041#ifdef ENABLE_OPT
6042void errHandler(const std::string& str) {
6043 std::cerr << str << std::endl;
6044}
6045#endif
6046
John Kessenich140f3df2015-06-26 16:58:36 -06006047//
6048// Set up the glslang traversal
6049//
John Kessenich121853f2017-05-31 17:11:16 -06006050void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006051{
Lei Zhang17535f72016-05-04 15:55:59 -04006052 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006053 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006054}
6055
John Kessenich121853f2017-05-31 17:11:16 -06006056void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6057 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006058{
John Kessenich140f3df2015-06-26 16:58:36 -06006059 TIntermNode* root = intermediate.getTreeRoot();
6060
6061 if (root == 0)
6062 return;
6063
John Kessenich121853f2017-05-31 17:11:16 -06006064 glslang::SpvOptions defaultOptions;
6065 if (options == nullptr)
6066 options = &defaultOptions;
6067
John Kessenich140f3df2015-06-26 16:58:36 -06006068 glslang::GetThreadPoolAllocator().push();
6069
John Kessenich121853f2017-05-31 17:11:16 -06006070 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006071 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006072 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006073 it.dumpSpv(spirv);
6074
GregFcd1f1692017-09-21 18:40:22 -06006075#ifdef ENABLE_OPT
6076 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6077 // eg. forward and remove memory writes of opaque types.
6078 if ((intermediate.getSource() == EShSourceHlsl ||
6079 options->optimizeSize) &&
6080 !options->disableOptimizer) {
6081 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6082
6083 spvtools::Optimizer optimizer(target_env);
6084 optimizer.SetMessageConsumer([](spv_message_level_t level,
6085 const char* source,
6086 const spv_position_t& position,
6087 const char* message) {
6088 std::cerr << StringifyMessage(level, source, position, message)
6089 << std::endl;
6090 });
6091
6092 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006093 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6094 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006095 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6096 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6097 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6098 optimizer.RegisterPass(CreateInsertExtractElimPass());
6099 optimizer.RegisterPass(CreateAggressiveDCEPass());
6100 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006101 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006102 optimizer.RegisterPass(CreateBlockMergePass());
6103 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6104 optimizer.RegisterPass(CreateInsertExtractElimPass());
6105 optimizer.RegisterPass(CreateAggressiveDCEPass());
6106 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6107 // if (options->optimizeSize)
6108 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6109
6110 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6111 return;
6112
6113 // Remove dead module-level objects: functions, types, vars
6114 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6115 spv::spirvbin_t Remapper(0);
6116 Remapper.registerErrorHandler(errHandler);
6117 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6118 }
6119#endif
6120
John Kessenich140f3df2015-06-26 16:58:36 -06006121 glslang::GetThreadPoolAllocator().pop();
6122}
6123
6124}; // end namespace glslang