blob: dc644e560b230a6a193e48af0d6e6c96e0929ea2 [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 Kessenich2b5ea9f2018-01-31 18:35:56 -0700110 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
111 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700112 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600113
114 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
115 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
116 void visitConstantUnion(glslang::TIntermConstantUnion*);
117 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
118 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
119 void visitSymbol(glslang::TIntermSymbol* symbol);
120 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
121 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
122 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
123
John Kessenichfca82622016-11-26 13:23:20 -0700124 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700125 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800128 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800129 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100130 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700131 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700132 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
133 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700134 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600135 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
137 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600138 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
139 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
140 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700142 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600143 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600144 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
145 glslang::TLayoutPacking, const glslang::TQualifier&);
146 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
147 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700148 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700149 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800150 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600151 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700152 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
154 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
155 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 +0100156 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
John Kessenich6fccb3c2016-09-19 16:01:41 -0600158 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600159 bool writableParam(glslang::TStorageQualifier);
160 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 void makeFunctions(const glslang::TIntermSequence&);
162 void makeGlobalInitializers(const glslang::TIntermSequence&);
163 void visitFunctions(const glslang::TIntermSequence&);
164 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600166 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
167 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
169
qining25262b32016-05-06 17:25:16 -0400170 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
171 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
172 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800173 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800174 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800176 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800177 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800178 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600179 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
182 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700183 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600184 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700185 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400186 spv::Id createSpvConstant(const glslang::TIntermTyped&);
187 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600188 bool isTrivialLeaf(const glslang::TIntermTyped* node);
189 bool isTrivial(const glslang::TIntermTyped* node);
190 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500191#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800192 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500193#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600194
John Kessenich121853f2017-05-31 17:11:16 -0600195 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600197 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700198 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600199 int sequenceDepth;
200
Lei Zhang17535f72016-05-04 15:55:59 -0400201 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400202
John Kessenich140f3df2015-06-26 16:58:36 -0600203 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
204 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700205 bool inEntryPoint;
206 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700207 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700208 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600209 const glslang::TIntermediate* glslangIntermediate;
210 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800211 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600212
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600214 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600215 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700216 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600217 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600218 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600219};
220
221//
222// Helper functions for translating glslang representations to SPIR-V enumerants.
223//
224
225// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700226spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600227{
John Kessenich66e2faf2016-03-12 18:34:36 -0700228 switch (source) {
229 case glslang::EShSourceGlsl:
230 switch (profile) {
231 case ENoProfile:
232 case ECoreProfile:
233 case ECompatibilityProfile:
234 return spv::SourceLanguageGLSL;
235 case EEsProfile:
236 return spv::SourceLanguageESSL;
237 default:
238 return spv::SourceLanguageUnknown;
239 }
240 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600241 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 default:
243 return spv::SourceLanguageUnknown;
244 }
245}
246
247// Translate glslang language (stage) to SPIR-V execution model.
248spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
249{
250 switch (stage) {
251 case EShLangVertex: return spv::ExecutionModelVertex;
252 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
253 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
254 case EShLangGeometry: return spv::ExecutionModelGeometry;
255 case EShLangFragment: return spv::ExecutionModelFragment;
256 case EShLangCompute: return spv::ExecutionModelGLCompute;
257 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700258 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600259 return spv::ExecutionModelFragment;
260 }
261}
262
John Kessenich140f3df2015-06-26 16:58:36 -0600263// Translate glslang sampler type to SPIR-V dimensionality.
264spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
265{
266 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::Esd1D: return spv::Dim1D;
268 case glslang::Esd2D: return spv::Dim2D;
269 case glslang::Esd3D: return spv::Dim3D;
270 case glslang::EsdCube: return spv::DimCube;
271 case glslang::EsdRect: return spv::DimRect;
272 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700273 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700275 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::Dim2D;
277 }
278}
279
John Kessenichf6640762016-08-01 19:44:00 -0600280// Translate glslang precision to SPIR-V precision decorations.
281spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600282{
John Kessenichf6640762016-08-01 19:44:00 -0600283 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700284 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
287 return spv::NoPrecision;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang type to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
293{
294 return TranslatePrecisionDecoration(type.getQualifier().precision);
295}
296
John Kessenich140f3df2015-06-26 16:58:36 -0600297// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600298spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600299{
300 if (type.getBasicType() == glslang::EbtBlock) {
301 switch (type.getQualifier().storage) {
302 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600303 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 case glslang::EvqVaryingIn: return spv::DecorationBlock;
305 case glslang::EvqVaryingOut: return spv::DecorationBlock;
306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 break;
309 }
310 }
311
John Kessenich4016e382016-07-15 11:53:56 -0600312 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600313}
314
Rex Xu1da878f2016-02-21 20:59:01 +0800315// Translate glslang type to SPIR-V memory decorations.
316void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
317{
318 if (qualifier.coherent)
319 memory.push_back(spv::DecorationCoherent);
320 if (qualifier.volatil)
321 memory.push_back(spv::DecorationVolatile);
322 if (qualifier.restrict)
323 memory.push_back(spv::DecorationRestrict);
324 if (qualifier.readonly)
325 memory.push_back(spv::DecorationNonWritable);
326 if (qualifier.writeonly)
327 memory.push_back(spv::DecorationNonReadable);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700331spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElmRowMajor:
336 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700339 default:
340 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 } else {
344 switch (type.getBasicType()) {
345 default:
John Kessenich4016e382016-07-15 11:53:56 -0600346 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 case glslang::EbtBlock:
349 switch (type.getQualifier().storage) {
350 case glslang::EvqUniform:
351 case glslang::EvqBuffer:
352 switch (type.getQualifier().layoutPacking) {
353 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 case glslang::EvqVaryingIn:
359 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700363 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 }
367 }
368}
369
370// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600371// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700372// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800373spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
Rex Xubbceed72016-05-21 09:40:44 +0800375 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700379 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800382#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800383 else if (qualifier.explicitInterp) {
384 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800385 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800386 }
Rex Xu9d93a232016-05-05 12:30:44 +0800387#endif
Rex Xubbceed72016-05-21 09:40:44 +0800388 else
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800390}
391
392// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800394// should be applied.
395spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
396{
397 if (qualifier.patch)
398 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700401 else if (qualifier.sample) {
402 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700404 } else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600406}
407
John Kessenich92187592016-02-01 13:45:25 -0700408// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600410{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700411 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationInvariant;
413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
qining9220dbb2016-05-04 17:34:38 -0400417// If glslang type is noContraction, return SPIR-V NoContraction decoration.
418spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
419{
420 if (qualifier.noContraction)
421 return spv::DecorationNoContraction;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400424}
425
David Netoa901ffe2016-06-08 14:11:40 +0100426// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
427// associated capabilities when required. For some built-in variables, a capability
428// is generated only when using the variable in an executable instruction, but not when
429// just declaring a struct member variable with it. This is true for PointSize,
430// ClipDistance, and CullDistance.
431spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
433 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700434 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600435 // Defer adding the capability until the built-in is actually used.
436 if (! memberDeclaration) {
437 switch (glslangIntermediate->getStage()) {
438 case EShLangGeometry:
439 builder.addCapability(spv::CapabilityGeometryPointSize);
440 break;
441 case EShLangTessControl:
442 case EShLangTessEvaluation:
443 builder.addCapability(spv::CapabilityTessellationPointSize);
444 break;
445 default:
446 break;
447 }
John Kessenich92187592016-02-01 13:45:25 -0700448 }
449 return spv::BuiltInPointSize;
450
John Kessenichebb50532016-05-16 19:22:05 -0600451 // These *Distance capabilities logically belong here, but if the member is declared and
452 // then never used, consumers of SPIR-V prefer the capability not be declared.
453 // They are now generated when used, rather than here when declared.
454 // Potentially, the specification should be more clear what the minimum
455 // use needed is to trigger the capability.
456 //
John Kessenich92187592016-02-01 13:45:25 -0700457 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800459 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInClipDistance;
461
462 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100463 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800464 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700465 return spv::BuiltInCullDistance;
466
467 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600468 builder.addCapability(spv::CapabilityMultiViewport);
469 if (glslangIntermediate->getStage() == EShLangVertex ||
470 glslangIntermediate->getStage() == EShLangTessControl ||
471 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800472
John Kessenichba6a3c22017-09-13 13:22:50 -0600473 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
474 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800475 }
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInViewportIndex;
477
John Kessenich5e801132016-02-15 11:09:46 -0700478 case glslang::EbvSampleId:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleId;
481
482 case glslang::EbvSamplePosition:
483 builder.addCapability(spv::CapabilitySampleRateShading);
484 return spv::BuiltInSamplePosition;
485
486 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700487 return spv::BuiltInSampleMask;
488
John Kessenich78a45572016-07-08 14:05:15 -0600489 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600490 builder.addCapability(spv::CapabilityGeometry);
491 if (glslangIntermediate->getStage() == EShLangVertex ||
492 glslangIntermediate->getStage() == EShLangTessControl ||
493 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800494
John Kessenichba6a3c22017-09-13 13:22:50 -0600495 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
496 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800497 }
John Kessenich78a45572016-07-08 14:05:15 -0600498 return spv::BuiltInLayer;
499
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600501 case glslang::EbvVertexId: return spv::BuiltInVertexId;
502 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700503 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
504 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800505
John Kessenichda581a22015-10-14 14:10:30 -0600506 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800507 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
508 builder.addCapability(spv::CapabilityDrawParameters);
509 return spv::BuiltInBaseVertex;
510
John Kessenichda581a22015-10-14 14:10:30 -0600511 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800512 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
513 builder.addCapability(spv::CapabilityDrawParameters);
514 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200515
John Kessenichda581a22015-10-14 14:10:30 -0600516 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800517 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
518 builder.addCapability(spv::CapabilityDrawParameters);
519 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200520
521 case glslang::EbvPrimitiveId:
522 if (glslangIntermediate->getStage() == EShLangFragment)
523 builder.addCapability(spv::CapabilityGeometry);
524 return spv::BuiltInPrimitiveId;
525
Rex Xu37cdcee2017-06-29 17:46:34 +0800526 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800527 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
528 builder.addCapability(spv::CapabilityStencilExportEXT);
529 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800530
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600532 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
533 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
534 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
535 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
536 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
537 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
538 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600539 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
540 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
541 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
542 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
543 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
544 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
545 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
546 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800547
Rex Xu574ab042016-04-14 16:53:07 +0800548 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800549 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
551 return spv::BuiltInSubgroupSize;
552
Rex Xu574ab042016-04-14 16:53:07 +0800553 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800554 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
556 return spv::BuiltInSubgroupLocalInvocationId;
557
Rex Xu574ab042016-04-14 16:53:07 +0800558 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800559 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
560 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
561 return spv::BuiltInSubgroupEqMaskKHR;
562
Rex Xu574ab042016-04-14 16:53:07 +0800563 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800564 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
565 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
566 return spv::BuiltInSubgroupGeMaskKHR;
567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupGtMaskKHR;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLeMaskKHR;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupLtMaskKHR;
582
Rex Xu9d93a232016-05-05 12:30:44 +0800583#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800584 case glslang::EbvBaryCoordNoPersp:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspAMD;
587
588 case glslang::EbvBaryCoordNoPerspCentroid:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
591
592 case glslang::EbvBaryCoordNoPerspSample:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordNoPerspSampleAMD;
595
596 case glslang::EbvBaryCoordSmooth:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothAMD;
599
600 case glslang::EbvBaryCoordSmoothCentroid:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothCentroidAMD;
603
604 case glslang::EbvBaryCoordSmoothSample:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordSmoothSampleAMD;
607
608 case glslang::EbvBaryCoordPullModel:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800611#endif
chaoc771d89f2017-01-13 01:10:53 -0800612
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613 case glslang::EbvDeviceIndex:
614 builder.addExtension(spv::E_SPV_KHR_device_group);
615 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700616 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700617
618 case glslang::EbvViewIndex:
619 builder.addExtension(spv::E_SPV_KHR_multiview);
620 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700621 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700622
chaoc771d89f2017-01-13 01:10:53 -0800623#ifdef NV_EXTENSIONS
624 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800625 if (!memberDeclaration) {
626 builder.addExtension(spv::E_SPV_NV_viewport_array2);
627 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
628 }
chaoc771d89f2017-01-13 01:10:53 -0800629 return spv::BuiltInViewportMaskNV;
630 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800631 if (!memberDeclaration) {
632 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
633 builder.addCapability(spv::CapabilityShaderStereoViewNV);
634 }
chaoc771d89f2017-01-13 01:10:53 -0800635 return spv::BuiltInSecondaryPositionNV;
636 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800637 if (!memberDeclaration) {
638 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
640 }
chaoc771d89f2017-01-13 01:10:53 -0800641 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800642 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800643 if (!memberDeclaration) {
644 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
645 builder.addCapability(spv::CapabilityPerViewAttributesNV);
646 }
chaocdf3956c2017-02-14 14:52:34 -0800647 return spv::BuiltInPositionPerViewNV;
648 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800649 if (!memberDeclaration) {
650 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
651 builder.addCapability(spv::CapabilityPerViewAttributesNV);
652 }
chaocdf3956c2017-02-14 14:52:34 -0800653 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700654 case glslang::EbvFragFullyCoveredNV:
655 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
656 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
657 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800658#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800659 default:
660 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600661 }
662}
663
Rex Xufc618912015-09-09 16:42:49 +0800664// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700665spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800666{
667 assert(type.getBasicType() == glslang::EbtSampler);
668
John Kessenich5d0fa972016-02-15 11:57:00 -0700669 // Check for capabilities
670 switch (type.getQualifier().layoutFormat) {
671 case glslang::ElfRg32f:
672 case glslang::ElfRg16f:
673 case glslang::ElfR11fG11fB10f:
674 case glslang::ElfR16f:
675 case glslang::ElfRgba16:
676 case glslang::ElfRgb10A2:
677 case glslang::ElfRg16:
678 case glslang::ElfRg8:
679 case glslang::ElfR16:
680 case glslang::ElfR8:
681 case glslang::ElfRgba16Snorm:
682 case glslang::ElfRg16Snorm:
683 case glslang::ElfRg8Snorm:
684 case glslang::ElfR16Snorm:
685 case glslang::ElfR8Snorm:
686
687 case glslang::ElfRg32i:
688 case glslang::ElfRg16i:
689 case glslang::ElfRg8i:
690 case glslang::ElfR16i:
691 case glslang::ElfR8i:
692
693 case glslang::ElfRgb10a2ui:
694 case glslang::ElfRg32ui:
695 case glslang::ElfRg16ui:
696 case glslang::ElfRg8ui:
697 case glslang::ElfR16ui:
698 case glslang::ElfR8ui:
699 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
700 break;
701
702 default:
703 break;
704 }
705
706 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800707 switch (type.getQualifier().layoutFormat) {
708 case glslang::ElfNone: return spv::ImageFormatUnknown;
709 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
710 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
711 case glslang::ElfR32f: return spv::ImageFormatR32f;
712 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
713 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
714 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
715 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
716 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
717 case glslang::ElfR16f: return spv::ImageFormatR16f;
718 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
719 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
720 case glslang::ElfRg16: return spv::ImageFormatRg16;
721 case glslang::ElfRg8: return spv::ImageFormatRg8;
722 case glslang::ElfR16: return spv::ImageFormatR16;
723 case glslang::ElfR8: return spv::ImageFormatR8;
724 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
725 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
726 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
727 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
728 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
729 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
730 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
731 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
732 case glslang::ElfR32i: return spv::ImageFormatR32i;
733 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
734 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
735 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
736 case glslang::ElfR16i: return spv::ImageFormatR16i;
737 case glslang::ElfR8i: return spv::ImageFormatR8i;
738 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
739 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
740 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
741 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
742 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
743 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
744 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
745 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
746 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
747 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800749 }
750}
751
John Kesseniche18fd202018-01-30 11:01:39 -0700752spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800753{
John Kesseniche18fd202018-01-30 11:01:39 -0700754 if (selectionNode.getFlatten())
755 return spv::SelectionControlFlattenMask;
756 if (selectionNode.getDontFlatten())
757 return spv::SelectionControlDontFlattenMask;
758 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800759}
760
John Kesseniche18fd202018-01-30 11:01:39 -0700761spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600762{
John Kesseniche18fd202018-01-30 11:01:39 -0700763 if (switchNode.getFlatten())
764 return spv::SelectionControlFlattenMask;
765 if (switchNode.getDontFlatten())
766 return spv::SelectionControlDontFlattenMask;
767 return spv::SelectionControlMaskNone;
768}
769
John Kessenicha2858d92018-01-31 08:11:18 -0700770// return a non-0 dependency if the dependency argument must be set
771spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
772 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700773{
774 spv::LoopControlMask control = spv::LoopControlMaskNone;
775
776 if (loopNode.getDontUnroll())
777 control = control | spv::LoopControlDontUnrollMask;
778 if (loopNode.getUnroll())
779 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700780 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700781 control = control | spv::LoopControlDependencyInfiniteMask;
782 else if (loopNode.getLoopDependency() > 0) {
783 control = control | spv::LoopControlDependencyLengthMask;
784 dependencyLength = loopNode.getLoopDependency();
785 }
John Kesseniche18fd202018-01-30 11:01:39 -0700786
787 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600788}
789
John Kessenicha5c5fb62017-05-05 05:09:58 -0600790// Translate glslang type to SPIR-V storage class.
791spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
792{
793 if (type.getQualifier().isPipeInput())
794 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600795 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600796 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600797
798 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
799 type.getQualifier().storage == glslang::EvqUniform) {
800 if (type.getBasicType() == glslang::EbtAtomicUint)
801 return spv::StorageClassAtomicCounter;
802 if (type.containsOpaque())
803 return spv::StorageClassUniformConstant;
804 }
805
806 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600807 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
808 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600809 }
810
811 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600812 if (type.getQualifier().layoutPushConstant)
813 return spv::StorageClassPushConstant;
814 if (type.getBasicType() == glslang::EbtBlock)
815 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600816 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600817 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600818
819 switch (type.getQualifier().storage) {
820 case glslang::EvqShared: return spv::StorageClassWorkgroup;
821 case glslang::EvqGlobal: return spv::StorageClassPrivate;
822 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
823 case glslang::EvqTemporary: return spv::StorageClassFunction;
824 default:
825 assert(0);
826 break;
827 }
828
829 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600830}
831
qining25262b32016-05-06 17:25:16 -0400832// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700833// descriptor set.
834bool IsDescriptorResource(const glslang::TType& type)
835{
John Kessenichf7497e22016-03-08 21:36:22 -0700836 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700837 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700838 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700839
840 // non block...
841 // basically samplerXXX/subpass/sampler/texture are all included
842 // if they are the global-scope-class, not the function parameter
843 // (or local, if they ever exist) class.
844 if (type.getBasicType() == glslang::EbtSampler)
845 return type.getQualifier().isUniformOrBuffer();
846
847 // None of the above.
848 return false;
849}
850
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
852{
853 if (child.layoutMatrix == glslang::ElmNone)
854 child.layoutMatrix = parent.layoutMatrix;
855
856 if (parent.invariant)
857 child.invariant = true;
858 if (parent.nopersp)
859 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800860#ifdef AMD_EXTENSIONS
861 if (parent.explicitInterp)
862 child.explicitInterp = true;
863#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864 if (parent.flat)
865 child.flat = true;
866 if (parent.centroid)
867 child.centroid = true;
868 if (parent.patch)
869 child.patch = true;
870 if (parent.sample)
871 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800872 if (parent.coherent)
873 child.coherent = true;
874 if (parent.volatil)
875 child.volatil = true;
876 if (parent.restrict)
877 child.restrict = true;
878 if (parent.readonly)
879 child.readonly = true;
880 if (parent.writeonly)
881 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700882}
883
John Kessenichf2b7f332016-09-01 17:05:23 -0600884bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700885{
John Kessenich7b9fa252016-01-21 18:56:57 -0700886 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600887 // - struct members might inherit from a struct declaration
888 // (note that non-block structs don't explicitly inherit,
889 // only implicitly, meaning no decoration involved)
890 // - affect decorations on the struct members
891 // (note smooth does not, and expecting something like volatile
892 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700893 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600894 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700895}
896
John Kessenich140f3df2015-06-26 16:58:36 -0600897//
898// Implement the TGlslangToSpvTraverser class.
899//
900
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700901TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600902 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
903 : TIntermTraverser(true, false, true),
904 options(options),
905 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600906 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700907 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700908 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600909 glslangIntermediate(glslangIntermediate)
910{
911 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
912
913 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600914 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
915 glslangIntermediate->getVersion());
916
John Kessenich121853f2017-05-31 17:11:16 -0600917 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600918 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600919 builder.setSourceFile(glslangIntermediate->getSourceFile());
920
921 // Set the source shader's text. If for SPV version 1.0, include
922 // a preamble in comments stating the OpModuleProcessed instructions.
923 // Otherwise, emit those as actual instructions.
924 std::string text;
925 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
926 for (int p = 0; p < (int)processes.size(); ++p) {
927 if (glslangIntermediate->getSpv().spv < 0x00010100) {
928 text.append("// OpModuleProcessed ");
929 text.append(processes[p]);
930 text.append("\n");
931 } else
932 builder.addModuleProcessed(processes[p]);
933 }
934 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
935 text.append("#line 1\n");
936 text.append(glslangIntermediate->getSourceText());
937 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939 stdBuiltins = builder.import("GLSL.std.450");
940 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600941 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
942 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600943
944 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600945 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
946 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600947 builder.addSourceExtension(it->c_str());
948
949 // Add the top-level modes for this shader.
950
John Kessenich92187592016-02-01 13:45:25 -0700951 if (glslangIntermediate->getXfbMode()) {
952 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700954 }
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 unsigned int mode;
957 switch (glslangIntermediate->getStage()) {
958 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600959 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600960 break;
961
steve-lunarge7412492017-03-23 11:56:07 -0600962 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600963 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600965
steve-lunarge7412492017-03-23 11:56:07 -0600966 glslang::TLayoutGeometry primitive;
967
968 if (glslangIntermediate->getStage() == EShLangTessControl) {
969 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
970 primitive = glslangIntermediate->getOutputPrimitive();
971 } else {
972 primitive = glslangIntermediate->getInputPrimitive();
973 }
974
975 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700976 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
977 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
978 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600979 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600980 }
John Kessenich4016e382016-07-15 11:53:56 -0600981 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600982 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
983
John Kesseniche6903322015-10-13 16:29:02 -0600984 switch (glslangIntermediate->getVertexSpacing()) {
985 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
986 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
987 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600988 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600989 }
John Kessenich4016e382016-07-15 11:53:56 -0600990 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600991 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
992
993 switch (glslangIntermediate->getVertexOrder()) {
994 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
995 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600996 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600997 }
John Kessenich4016e382016-07-15 11:53:56 -0600998 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600999 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1000
1001 if (glslangIntermediate->getPointMode())
1002 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 break;
1004
1005 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001006 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001007 switch (glslangIntermediate->getInputPrimitive()) {
1008 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1009 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1010 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001011 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001012 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001013 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001014 }
John Kessenich4016e382016-07-15 11:53:56 -06001015 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001016 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001017
John Kessenich140f3df2015-06-26 16:58:36 -06001018 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1019
1020 switch (glslangIntermediate->getOutputPrimitive()) {
1021 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1022 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1023 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001024 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001025 }
John Kessenich4016e382016-07-15 11:53:56 -06001026 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001027 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1028 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1029 break;
1030
1031 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001032 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001033 if (glslangIntermediate->getPixelCenterInteger())
1034 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 if (glslangIntermediate->getOriginUpperLeft())
1037 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001038 else
1039 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001040
1041 if (glslangIntermediate->getEarlyFragmentTests())
1042 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1043
chaocc1204522017-06-30 17:14:30 -07001044 if (glslangIntermediate->getPostDepthCoverage()) {
1045 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1046 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1047 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1048 }
1049
John Kesseniche6903322015-10-13 16:29:02 -06001050 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001051 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1052 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001053 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001054 }
John Kessenich4016e382016-07-15 11:53:56 -06001055 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001056 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1057
1058 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1059 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001060 break;
1061
1062 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001063 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001064 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1065 glslangIntermediate->getLocalSize(1),
1066 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001067 break;
1068
1069 default:
1070 break;
1071 }
John Kessenich140f3df2015-06-26 16:58:36 -06001072}
1073
John Kessenichfca82622016-11-26 13:23:20 -07001074// Finish creating SPV, after the traversal is complete.
1075void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001076{
John Kessenich517fe7a2016-11-26 13:31:47 -07001077 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001078 builder.setBuildPoint(shaderEntry->getLastBlock());
1079 builder.leaveFunction();
1080 }
1081
John Kessenich7ba63412015-12-20 17:37:07 -07001082 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001083 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1084 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001085
qiningda397332016-03-09 19:54:03 -05001086 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001087}
1088
John Kessenichfca82622016-11-26 13:23:20 -07001089// Write the SPV into 'out'.
1090void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001091{
John Kessenichfca82622016-11-26 13:23:20 -07001092 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001093}
1094
1095//
1096// Implement the traversal functions.
1097//
1098// Return true from interior nodes to have the external traversal
1099// continue on to children. Return false if children were
1100// already processed.
1101//
1102
1103//
qining25262b32016-05-06 17:25:16 -04001104// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001105// - uniform/input reads
1106// - output writes
1107// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1108// - something simple that degenerates into the last bullet
1109//
1110void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1111{
qining75d1d802016-04-06 14:42:01 -04001112 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1113 if (symbol->getType().getQualifier().isSpecConstant())
1114 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1115
John Kessenich140f3df2015-06-26 16:58:36 -06001116 // getSymbolId() will set up all the IO decorations on the first call.
1117 // Formal function parameters were mapped during makeFunctions().
1118 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001119
1120 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1121 if (builder.isPointer(id)) {
1122 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001123 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1124 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1125 iOSet.insert(id);
1126 }
John Kessenich7ba63412015-12-20 17:37:07 -07001127 }
1128
1129 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001130 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001131 // Prepare to generate code for the access
1132
1133 // L-value chains will be computed left to right. We're on the symbol now,
1134 // which is the left-most part of the access chain, so now is "clear" time,
1135 // followed by setting the base.
1136 builder.clearAccessChain();
1137
1138 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001139 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001140 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001141 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001142 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001143 // These are also pure R-values.
1144 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001145 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001146 builder.setAccessChainRValue(id);
1147 else
1148 builder.setAccessChainLValue(id);
1149 }
1150}
1151
1152bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1153{
John Kesseniche485c7a2017-05-31 18:50:53 -06001154 builder.setLine(node->getLoc().line);
1155
qining40887662016-04-03 22:20:42 -04001156 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1157 if (node->getType().getQualifier().isSpecConstant())
1158 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1159
John Kessenich140f3df2015-06-26 16:58:36 -06001160 // First, handle special cases
1161 switch (node->getOp()) {
1162 case glslang::EOpAssign:
1163 case glslang::EOpAddAssign:
1164 case glslang::EOpSubAssign:
1165 case glslang::EOpMulAssign:
1166 case glslang::EOpVectorTimesMatrixAssign:
1167 case glslang::EOpVectorTimesScalarAssign:
1168 case glslang::EOpMatrixTimesScalarAssign:
1169 case glslang::EOpMatrixTimesMatrixAssign:
1170 case glslang::EOpDivAssign:
1171 case glslang::EOpModAssign:
1172 case glslang::EOpAndAssign:
1173 case glslang::EOpInclusiveOrAssign:
1174 case glslang::EOpExclusiveOrAssign:
1175 case glslang::EOpLeftShiftAssign:
1176 case glslang::EOpRightShiftAssign:
1177 // A bin-op assign "a += b" means the same thing as "a = a + b"
1178 // where a is evaluated before b. For a simple assignment, GLSL
1179 // says to evaluate the left before the right. So, always, left
1180 // node then right node.
1181 {
1182 // get the left l-value, save it away
1183 builder.clearAccessChain();
1184 node->getLeft()->traverse(this);
1185 spv::Builder::AccessChain lValue = builder.getAccessChain();
1186
1187 // evaluate the right
1188 builder.clearAccessChain();
1189 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001190 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 if (node->getOp() != glslang::EOpAssign) {
1193 // the left is also an r-value
1194 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001195 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001196
1197 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001198 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001199 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001200 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1201 node->getType().getBasicType());
1202
1203 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001204 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206
1207 // store the result
1208 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001209 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001210
1211 // assignments are expressions having an rValue after they are evaluated...
1212 builder.clearAccessChain();
1213 builder.setAccessChainRValue(rValue);
1214 }
1215 return false;
1216 case glslang::EOpIndexDirect:
1217 case glslang::EOpIndexDirectStruct:
1218 {
1219 // Get the left part of the access chain.
1220 node->getLeft()->traverse(this);
1221
1222 // Add the next element in the chain
1223
David Netoa901ffe2016-06-08 14:11:40 +01001224 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001225 if (! node->getLeft()->getType().isArray() &&
1226 node->getLeft()->getType().isVector() &&
1227 node->getOp() == glslang::EOpIndexDirect) {
1228 // This is essentially a hard-coded vector swizzle of size 1,
1229 // so short circuit the access-chain stuff with a swizzle.
1230 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001231 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001232 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001233 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001234 int spvIndex = glslangIndex;
1235 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1236 node->getOp() == glslang::EOpIndexDirectStruct)
1237 {
1238 // This may be, e.g., an anonymous block-member selection, which generally need
1239 // index remapping due to hidden members in anonymous blocks.
1240 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1241 assert(remapper.size() > 0);
1242 spvIndex = remapper[glslangIndex];
1243 }
John Kessenichebb50532016-05-16 19:22:05 -06001244
David Netoa901ffe2016-06-08 14:11:40 +01001245 // normal case for indexing array or structure or block
1246 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1247
1248 // Add capabilities here for accessing PointSize and clip/cull distance.
1249 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001250 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001251 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001252 }
1253 }
1254 return false;
1255 case glslang::EOpIndexIndirect:
1256 {
1257 // Structure or array or vector indirection.
1258 // Will use native SPIR-V access-chain for struct and array indirection;
1259 // matrices are arrays of vectors, so will also work for a matrix.
1260 // Will use the access chain's 'component' for variable index into a vector.
1261
1262 // This adapter is building access chains left to right.
1263 // Set up the access chain to the left.
1264 node->getLeft()->traverse(this);
1265
1266 // save it so that computing the right side doesn't trash it
1267 spv::Builder::AccessChain partial = builder.getAccessChain();
1268
1269 // compute the next index in the chain
1270 builder.clearAccessChain();
1271 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001272 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001273
1274 // restore the saved access chain
1275 builder.setAccessChain(partial);
1276
1277 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001278 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001279 else
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001281 }
1282 return false;
1283 case glslang::EOpVectorSwizzle:
1284 {
1285 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001286 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001287 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001288 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001289 }
1290 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001291 case glslang::EOpMatrixSwizzle:
1292 logger->missingFunctionality("matrix swizzle");
1293 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001294 case glslang::EOpLogicalOr:
1295 case glslang::EOpLogicalAnd:
1296 {
1297
1298 // These may require short circuiting, but can sometimes be done as straight
1299 // binary operations. The right operand must be short circuited if it has
1300 // side effects, and should probably be if it is complex.
1301 if (isTrivial(node->getRight()->getAsTyped()))
1302 break; // handle below as a normal binary operation
1303 // otherwise, we need to do dynamic short circuiting on the right operand
1304 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1305 builder.clearAccessChain();
1306 builder.setAccessChainRValue(result);
1307 }
1308 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001309 default:
1310 break;
1311 }
1312
1313 // Assume generic binary op...
1314
John Kessenich32cfd492016-02-02 12:37:46 -07001315 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001316 builder.clearAccessChain();
1317 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001318 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001319
John Kessenich32cfd492016-02-02 12:37:46 -07001320 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001321 builder.clearAccessChain();
1322 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001323 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001324
John Kessenich32cfd492016-02-02 12:37:46 -07001325 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001326 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001327 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001328 convertGlslangToSpvType(node->getType()), left, right,
1329 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001330
John Kessenich50e57562015-12-21 21:21:11 -07001331 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001332 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001333 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001334 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001335 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001336 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001337 return false;
1338 }
John Kessenich140f3df2015-06-26 16:58:36 -06001339}
1340
1341bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1342{
John Kesseniche485c7a2017-05-31 18:50:53 -06001343 builder.setLine(node->getLoc().line);
1344
qining40887662016-04-03 22:20:42 -04001345 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1346 if (node->getType().getQualifier().isSpecConstant())
1347 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1348
John Kessenichfc51d282015-08-19 13:34:18 -06001349 spv::Id result = spv::NoResult;
1350
1351 // try texturing first
1352 result = createImageTextureFunctionCall(node);
1353 if (result != spv::NoResult) {
1354 builder.clearAccessChain();
1355 builder.setAccessChainRValue(result);
1356
1357 return false; // done with this node
1358 }
1359
1360 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001361
1362 if (node->getOp() == glslang::EOpArrayLength) {
1363 // Quite special; won't want to evaluate the operand.
1364
1365 // Normal .length() would have been constant folded by the front-end.
1366 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001367 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001368 assert(node->getOperand()->getType().isRuntimeSizedArray());
1369 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1370 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001371 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1372 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001373
1374 builder.clearAccessChain();
1375 builder.setAccessChainRValue(length);
1376
1377 return false;
1378 }
1379
John Kessenichfc51d282015-08-19 13:34:18 -06001380 // Start by evaluating the operand
1381
John Kessenich8c8505c2016-07-26 12:50:38 -06001382 // Does it need a swizzle inversion? If so, evaluation is inverted;
1383 // operate first on the swizzle base, then apply the swizzle.
1384 spv::Id invertedType = spv::NoType;
1385 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1386 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1387 invertedType = getInvertedSwizzleType(*node->getOperand());
1388
John Kessenich140f3df2015-06-26 16:58:36 -06001389 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 if (invertedType != spv::NoType)
1391 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1392 else
1393 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001394
Rex Xufc618912015-09-09 16:42:49 +08001395 spv::Id operand = spv::NoResult;
1396
1397 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1398 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001399 node->getOp() == glslang::EOpAtomicCounter ||
1400 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001401 operand = builder.accessChainGetLValue(); // Special case l-value operands
1402 else
John Kessenich32cfd492016-02-02 12:37:46 -07001403 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
John Kessenichf6640762016-08-01 19:44:00 -06001405 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001406 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001407
1408 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001409 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001410 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 // if not, then possibly an operation
1413 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001414 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001415
1416 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001417 if (invertedType)
1418 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1419
John Kessenich140f3df2015-06-26 16:58:36 -06001420 builder.clearAccessChain();
1421 builder.setAccessChainRValue(result);
1422
1423 return false; // done with this node
1424 }
1425
1426 // it must be a special case, check...
1427 switch (node->getOp()) {
1428 case glslang::EOpPostIncrement:
1429 case glslang::EOpPostDecrement:
1430 case glslang::EOpPreIncrement:
1431 case glslang::EOpPreDecrement:
1432 {
1433 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001434 spv::Id one = 0;
1435 if (node->getBasicType() == glslang::EbtFloat)
1436 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001437 else if (node->getBasicType() == glslang::EbtDouble)
1438 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001439#ifdef AMD_EXTENSIONS
1440 else if (node->getBasicType() == glslang::EbtFloat16)
1441 one = builder.makeFloat16Constant(1.0F);
1442#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001443 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1444 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001445#ifdef AMD_EXTENSIONS
1446 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1447 one = builder.makeInt16Constant(1);
1448#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001449 else
1450 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001451 glslang::TOperator op;
1452 if (node->getOp() == glslang::EOpPreIncrement ||
1453 node->getOp() == glslang::EOpPostIncrement)
1454 op = glslang::EOpAdd;
1455 else
1456 op = glslang::EOpSub;
1457
John Kessenichf6640762016-08-01 19:44:00 -06001458 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001459 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001460 convertGlslangToSpvType(node->getType()), operand, one,
1461 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001462 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001463
1464 // The result of operation is always stored, but conditionally the
1465 // consumed result. The consumed result is always an r-value.
1466 builder.accessChainStore(result);
1467 builder.clearAccessChain();
1468 if (node->getOp() == glslang::EOpPreIncrement ||
1469 node->getOp() == glslang::EOpPreDecrement)
1470 builder.setAccessChainRValue(result);
1471 else
1472 builder.setAccessChainRValue(operand);
1473 }
1474
1475 return false;
1476
1477 case glslang::EOpEmitStreamVertex:
1478 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1479 return false;
1480 case glslang::EOpEndStreamPrimitive:
1481 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1482 return false;
1483
1484 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001485 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001486 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001487 }
John Kessenich140f3df2015-06-26 16:58:36 -06001488}
1489
1490bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1491{
qining27e04a02016-04-14 16:40:20 -04001492 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1493 if (node->getType().getQualifier().isSpecConstant())
1494 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1495
John Kessenichfc51d282015-08-19 13:34:18 -06001496 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001497 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1498 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001499
1500 // try texturing
1501 result = createImageTextureFunctionCall(node);
1502 if (result != spv::NoResult) {
1503 builder.clearAccessChain();
1504 builder.setAccessChainRValue(result);
1505
1506 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001507#ifdef AMD_EXTENSIONS
1508 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1509#else
John Kessenich56bab042015-09-16 10:54:31 -06001510 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001511#endif
Rex Xufc618912015-09-09 16:42:49 +08001512 // "imageStore" is a special case, which has no result
1513 return false;
1514 }
John Kessenichfc51d282015-08-19 13:34:18 -06001515
John Kessenich140f3df2015-06-26 16:58:36 -06001516 glslang::TOperator binOp = glslang::EOpNull;
1517 bool reduceComparison = true;
1518 bool isMatrix = false;
1519 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001520 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001521
1522 assert(node->getOp());
1523
John Kessenichf6640762016-08-01 19:44:00 -06001524 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001525
1526 switch (node->getOp()) {
1527 case glslang::EOpSequence:
1528 {
1529 if (preVisit)
1530 ++sequenceDepth;
1531 else
1532 --sequenceDepth;
1533
1534 if (sequenceDepth == 1) {
1535 // If this is the parent node of all the functions, we want to see them
1536 // early, so all call points have actual SPIR-V functions to reference.
1537 // In all cases, still let the traverser visit the children for us.
1538 makeFunctions(node->getAsAggregate()->getSequence());
1539
John Kessenich6fccb3c2016-09-19 16:01:41 -06001540 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001541 // anything else gets there, so visit out of order, doing them all now.
1542 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1543
John Kessenich6a60c2f2016-12-08 21:01:59 -07001544 // 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 -06001545 // so do them manually.
1546 visitFunctions(node->getAsAggregate()->getSequence());
1547
1548 return false;
1549 }
1550
1551 return true;
1552 }
1553 case glslang::EOpLinkerObjects:
1554 {
1555 if (visit == glslang::EvPreVisit)
1556 linkageOnly = true;
1557 else
1558 linkageOnly = false;
1559
1560 return true;
1561 }
1562 case glslang::EOpComma:
1563 {
1564 // processing from left to right naturally leaves the right-most
1565 // lying around in the access chain
1566 glslang::TIntermSequence& glslangOperands = node->getSequence();
1567 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1568 glslangOperands[i]->traverse(this);
1569
1570 return false;
1571 }
1572 case glslang::EOpFunction:
1573 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001574 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001575 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001577 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001578 } else {
1579 handleFunctionEntry(node);
1580 }
1581 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001582 if (inEntryPoint)
1583 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001584 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001585 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001586 }
1587
1588 return true;
1589 case glslang::EOpParameters:
1590 // Parameters will have been consumed by EOpFunction processing, but not
1591 // the body, so we still visited the function node's children, making this
1592 // child redundant.
1593 return false;
1594 case glslang::EOpFunctionCall:
1595 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001596 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001597 if (node->isUserDefined())
1598 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001599 // 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 -07001600 if (result) {
1601 builder.clearAccessChain();
1602 builder.setAccessChainRValue(result);
1603 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001604 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001605
1606 return false;
1607 }
1608 case glslang::EOpConstructMat2x2:
1609 case glslang::EOpConstructMat2x3:
1610 case glslang::EOpConstructMat2x4:
1611 case glslang::EOpConstructMat3x2:
1612 case glslang::EOpConstructMat3x3:
1613 case glslang::EOpConstructMat3x4:
1614 case glslang::EOpConstructMat4x2:
1615 case glslang::EOpConstructMat4x3:
1616 case glslang::EOpConstructMat4x4:
1617 case glslang::EOpConstructDMat2x2:
1618 case glslang::EOpConstructDMat2x3:
1619 case glslang::EOpConstructDMat2x4:
1620 case glslang::EOpConstructDMat3x2:
1621 case glslang::EOpConstructDMat3x3:
1622 case glslang::EOpConstructDMat3x4:
1623 case glslang::EOpConstructDMat4x2:
1624 case glslang::EOpConstructDMat4x3:
1625 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001626 case glslang::EOpConstructIMat2x2:
1627 case glslang::EOpConstructIMat2x3:
1628 case glslang::EOpConstructIMat2x4:
1629 case glslang::EOpConstructIMat3x2:
1630 case glslang::EOpConstructIMat3x3:
1631 case glslang::EOpConstructIMat3x4:
1632 case glslang::EOpConstructIMat4x2:
1633 case glslang::EOpConstructIMat4x3:
1634 case glslang::EOpConstructIMat4x4:
1635 case glslang::EOpConstructUMat2x2:
1636 case glslang::EOpConstructUMat2x3:
1637 case glslang::EOpConstructUMat2x4:
1638 case glslang::EOpConstructUMat3x2:
1639 case glslang::EOpConstructUMat3x3:
1640 case glslang::EOpConstructUMat3x4:
1641 case glslang::EOpConstructUMat4x2:
1642 case glslang::EOpConstructUMat4x3:
1643 case glslang::EOpConstructUMat4x4:
1644 case glslang::EOpConstructBMat2x2:
1645 case glslang::EOpConstructBMat2x3:
1646 case glslang::EOpConstructBMat2x4:
1647 case glslang::EOpConstructBMat3x2:
1648 case glslang::EOpConstructBMat3x3:
1649 case glslang::EOpConstructBMat3x4:
1650 case glslang::EOpConstructBMat4x2:
1651 case glslang::EOpConstructBMat4x3:
1652 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001653#ifdef AMD_EXTENSIONS
1654 case glslang::EOpConstructF16Mat2x2:
1655 case glslang::EOpConstructF16Mat2x3:
1656 case glslang::EOpConstructF16Mat2x4:
1657 case glslang::EOpConstructF16Mat3x2:
1658 case glslang::EOpConstructF16Mat3x3:
1659 case glslang::EOpConstructF16Mat3x4:
1660 case glslang::EOpConstructF16Mat4x2:
1661 case glslang::EOpConstructF16Mat4x3:
1662 case glslang::EOpConstructF16Mat4x4:
1663#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001664 isMatrix = true;
1665 // fall through
1666 case glslang::EOpConstructFloat:
1667 case glslang::EOpConstructVec2:
1668 case glslang::EOpConstructVec3:
1669 case glslang::EOpConstructVec4:
1670 case glslang::EOpConstructDouble:
1671 case glslang::EOpConstructDVec2:
1672 case glslang::EOpConstructDVec3:
1673 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001674#ifdef AMD_EXTENSIONS
1675 case glslang::EOpConstructFloat16:
1676 case glslang::EOpConstructF16Vec2:
1677 case glslang::EOpConstructF16Vec3:
1678 case glslang::EOpConstructF16Vec4:
1679#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001680 case glslang::EOpConstructBool:
1681 case glslang::EOpConstructBVec2:
1682 case glslang::EOpConstructBVec3:
1683 case glslang::EOpConstructBVec4:
1684 case glslang::EOpConstructInt:
1685 case glslang::EOpConstructIVec2:
1686 case glslang::EOpConstructIVec3:
1687 case glslang::EOpConstructIVec4:
1688 case glslang::EOpConstructUint:
1689 case glslang::EOpConstructUVec2:
1690 case glslang::EOpConstructUVec3:
1691 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001692 case glslang::EOpConstructInt64:
1693 case glslang::EOpConstructI64Vec2:
1694 case glslang::EOpConstructI64Vec3:
1695 case glslang::EOpConstructI64Vec4:
1696 case glslang::EOpConstructUint64:
1697 case glslang::EOpConstructU64Vec2:
1698 case glslang::EOpConstructU64Vec3:
1699 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001700#ifdef AMD_EXTENSIONS
1701 case glslang::EOpConstructInt16:
1702 case glslang::EOpConstructI16Vec2:
1703 case glslang::EOpConstructI16Vec3:
1704 case glslang::EOpConstructI16Vec4:
1705 case glslang::EOpConstructUint16:
1706 case glslang::EOpConstructU16Vec2:
1707 case glslang::EOpConstructU16Vec3:
1708 case glslang::EOpConstructU16Vec4:
1709#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001710 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001711 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001712 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001713 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001714 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001715 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001717 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001718 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001719 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001720 std::vector<spv::Id> constituents;
1721 for (int c = 0; c < (int)arguments.size(); ++c)
1722 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001723 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001724 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001725 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001726 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001727 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001728
1729 builder.clearAccessChain();
1730 builder.setAccessChainRValue(constructed);
1731
1732 return false;
1733 }
1734
1735 // These six are component-wise compares with component-wise results.
1736 // Forward on to createBinaryOperation(), requesting a vector result.
1737 case glslang::EOpLessThan:
1738 case glslang::EOpGreaterThan:
1739 case glslang::EOpLessThanEqual:
1740 case glslang::EOpGreaterThanEqual:
1741 case glslang::EOpVectorEqual:
1742 case glslang::EOpVectorNotEqual:
1743 {
1744 // Map the operation to a binary
1745 binOp = node->getOp();
1746 reduceComparison = false;
1747 switch (node->getOp()) {
1748 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1749 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1750 default: binOp = node->getOp(); break;
1751 }
1752
1753 break;
1754 }
1755 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001756 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001757 binOp = glslang::EOpMul;
1758 break;
1759 case glslang::EOpOuterProduct:
1760 // two vectors multiplied to make a matrix
1761 binOp = glslang::EOpOuterProduct;
1762 break;
1763 case glslang::EOpDot:
1764 {
qining25262b32016-05-06 17:25:16 -04001765 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001766 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001767 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001768 binOp = glslang::EOpMul;
1769 break;
1770 }
1771 case glslang::EOpMod:
1772 // when an aggregate, this is the floating-point mod built-in function,
1773 // which can be emitted by the one in createBinaryOperation()
1774 binOp = glslang::EOpMod;
1775 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001776 case glslang::EOpEmitVertex:
1777 case glslang::EOpEndPrimitive:
1778 case glslang::EOpBarrier:
1779 case glslang::EOpMemoryBarrier:
1780 case glslang::EOpMemoryBarrierAtomicCounter:
1781 case glslang::EOpMemoryBarrierBuffer:
1782 case glslang::EOpMemoryBarrierImage:
1783 case glslang::EOpMemoryBarrierShared:
1784 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001785 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001786 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001787 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001788 case glslang::EOpWorkgroupMemoryBarrier:
1789 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001790 noReturnValue = true;
1791 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1792 break;
1793
John Kessenich426394d2015-07-23 10:22:48 -06001794 case glslang::EOpAtomicAdd:
1795 case glslang::EOpAtomicMin:
1796 case glslang::EOpAtomicMax:
1797 case glslang::EOpAtomicAnd:
1798 case glslang::EOpAtomicOr:
1799 case glslang::EOpAtomicXor:
1800 case glslang::EOpAtomicExchange:
1801 case glslang::EOpAtomicCompSwap:
1802 atomic = true;
1803 break;
1804
John Kessenich0d0c6d32017-07-23 16:08:26 -06001805 case glslang::EOpAtomicCounterAdd:
1806 case glslang::EOpAtomicCounterSubtract:
1807 case glslang::EOpAtomicCounterMin:
1808 case glslang::EOpAtomicCounterMax:
1809 case glslang::EOpAtomicCounterAnd:
1810 case glslang::EOpAtomicCounterOr:
1811 case glslang::EOpAtomicCounterXor:
1812 case glslang::EOpAtomicCounterExchange:
1813 case glslang::EOpAtomicCounterCompSwap:
1814 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1815 builder.addCapability(spv::CapabilityAtomicStorageOps);
1816 atomic = true;
1817 break;
1818
John Kessenich140f3df2015-06-26 16:58:36 -06001819 default:
1820 break;
1821 }
1822
1823 //
1824 // See if it maps to a regular operation.
1825 //
John Kessenich140f3df2015-06-26 16:58:36 -06001826 if (binOp != glslang::EOpNull) {
1827 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1828 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1829 assert(left && right);
1830
1831 builder.clearAccessChain();
1832 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001833 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001834
1835 builder.clearAccessChain();
1836 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001837 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001838
John Kesseniche485c7a2017-05-31 18:50:53 -06001839 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001840 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001841 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001842 left->getType().getBasicType(), reduceComparison);
1843
1844 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001845 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 builder.clearAccessChain();
1847 builder.setAccessChainRValue(result);
1848
1849 return false;
1850 }
1851
John Kessenich426394d2015-07-23 10:22:48 -06001852 //
1853 // Create the list of operands.
1854 //
John Kessenich140f3df2015-06-26 16:58:36 -06001855 glslang::TIntermSequence& glslangOperands = node->getSequence();
1856 std::vector<spv::Id> operands;
1857 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 // special case l-value operands; there are just a few
1859 bool lvalue = false;
1860 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001861 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001862 case glslang::EOpModf:
1863 if (arg == 1)
1864 lvalue = true;
1865 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001866 case glslang::EOpInterpolateAtSample:
1867 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001868#ifdef AMD_EXTENSIONS
1869 case glslang::EOpInterpolateAtVertex:
1870#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001871 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001872 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001873
1874 // Does it need a swizzle inversion? If so, evaluation is inverted;
1875 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001876 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001877 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1878 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1879 }
Rex Xu7a26c172015-12-08 17:12:09 +08001880 break;
Rex Xud4782c12015-09-06 16:30:11 +08001881 case glslang::EOpAtomicAdd:
1882 case glslang::EOpAtomicMin:
1883 case glslang::EOpAtomicMax:
1884 case glslang::EOpAtomicAnd:
1885 case glslang::EOpAtomicOr:
1886 case glslang::EOpAtomicXor:
1887 case glslang::EOpAtomicExchange:
1888 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001889 case glslang::EOpAtomicCounterAdd:
1890 case glslang::EOpAtomicCounterSubtract:
1891 case glslang::EOpAtomicCounterMin:
1892 case glslang::EOpAtomicCounterMax:
1893 case glslang::EOpAtomicCounterAnd:
1894 case glslang::EOpAtomicCounterOr:
1895 case glslang::EOpAtomicCounterXor:
1896 case glslang::EOpAtomicCounterExchange:
1897 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001898 if (arg == 0)
1899 lvalue = true;
1900 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001901 case glslang::EOpAddCarry:
1902 case glslang::EOpSubBorrow:
1903 if (arg == 2)
1904 lvalue = true;
1905 break;
1906 case glslang::EOpUMulExtended:
1907 case glslang::EOpIMulExtended:
1908 if (arg >= 2)
1909 lvalue = true;
1910 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001911 default:
1912 break;
1913 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001914 builder.clearAccessChain();
1915 if (invertedType != spv::NoType && arg == 0)
1916 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1917 else
1918 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 if (lvalue)
1920 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001921 else {
1922 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001923 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001924 }
John Kessenich140f3df2015-06-26 16:58:36 -06001925 }
John Kessenich426394d2015-07-23 10:22:48 -06001926
John Kesseniche485c7a2017-05-31 18:50:53 -06001927 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001928 if (atomic) {
1929 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001930 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001931 } else {
1932 // Pass through to generic operations.
1933 switch (glslangOperands.size()) {
1934 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001935 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001936 break;
1937 case 1:
qining25262b32016-05-06 17:25:16 -04001938 result = createUnaryOperation(
1939 node->getOp(), precision,
1940 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001941 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001942 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001943 break;
1944 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001945 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001946 break;
1947 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001948 if (invertedType)
1949 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 }
1951
1952 if (noReturnValue)
1953 return false;
1954
1955 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001956 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001957 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001958 } else {
1959 builder.clearAccessChain();
1960 builder.setAccessChainRValue(result);
1961 return false;
1962 }
1963}
1964
John Kessenich433e9ff2017-01-26 20:31:11 -07001965// This path handles both if-then-else and ?:
1966// The if-then-else has a node type of void, while
1967// ?: has either a void or a non-void node type
1968//
1969// Leaving the result, when not void:
1970// GLSL only has r-values as the result of a :?, but
1971// if we have an l-value, that can be more efficient if it will
1972// become the base of a complex r-value expression, because the
1973// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001974bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1975{
John Kessenich433e9ff2017-01-26 20:31:11 -07001976 // See if it simple and safe to generate OpSelect instead of using control flow.
1977 // Crucially, side effects must be avoided, and there are performance trade-offs.
1978 // Return true if good idea (and safe) for OpSelect, false otherwise.
1979 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001980 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1981 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001982 return false;
1983
1984 if (node->getTrueBlock() == nullptr ||
1985 node->getFalseBlock() == nullptr)
1986 return false;
1987
1988 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1989 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1990
1991 // return true if a single operand to ? : is okay for OpSelect
1992 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001993 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 };
1995
1996 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1997 operandOkay(node->getFalseBlock()->getAsTyped());
1998 };
1999
2000 // Emit OpSelect for this selection.
2001 const auto handleAsOpSelect = [&]() {
2002 node->getCondition()->traverse(this);
2003 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2004 node->getTrueBlock()->traverse(this);
2005 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2006 node->getFalseBlock()->traverse(this);
2007 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2008
John Kesseniche485c7a2017-05-31 18:50:53 -06002009 builder.setLine(node->getLoc().line);
2010
John Kesseniche434ad92017-03-30 10:09:28 -06002011 // smear condition to vector, if necessary (AST is always scalar)
2012 if (builder.isVector(trueValue))
2013 condition = builder.smearScalar(spv::NoPrecision, condition,
2014 builder.makeVectorType(builder.makeBoolType(),
2015 builder.getNumComponents(trueValue)));
2016
2017 spv::Id select = builder.createTriOp(spv::OpSelect,
2018 convertGlslangToSpvType(node->getType()), condition,
2019 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002020 builder.clearAccessChain();
2021 builder.setAccessChainRValue(select);
2022 };
2023
2024 // Try for OpSelect
2025
2026 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002027 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2028 if (node->getType().getQualifier().isSpecConstant())
2029 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2030
John Kessenich433e9ff2017-01-26 20:31:11 -07002031 handleAsOpSelect();
2032 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002033 }
2034
Rex Xu57e65922017-07-04 23:23:40 +08002035 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002036 // Don't handle results as temporaries, because there will be two names
2037 // and better to leave SSA to later passes.
2038 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2039 ? spv::NoResult
2040 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2041
John Kessenich140f3df2015-06-26 16:58:36 -06002042 // emit the condition before doing anything with selection
2043 node->getCondition()->traverse(this);
2044
Rex Xu57e65922017-07-04 23:23:40 +08002045 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002046 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002047
John Kessenich140f3df2015-06-26 16:58:36 -06002048 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002049 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002050
John Kessenich433e9ff2017-01-26 20:31:11 -07002051 // emit the "then" statement
2052 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002053 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002054 if (result != spv::NoResult)
2055 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 }
2057
John Kessenich433e9ff2017-01-26 20:31:11 -07002058 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002059 ifBuilder.makeBeginElse();
2060 // emit the "else" statement
2061 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002062 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002063 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002064 }
2065
John Kessenich433e9ff2017-01-26 20:31:11 -07002066 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002067 ifBuilder.makeEndIf();
2068
John Kessenich433e9ff2017-01-26 20:31:11 -07002069 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002070 // GLSL only has r-values as the result of a :?, but
2071 // if we have an l-value, that can be more efficient if it will
2072 // become the base of a complex r-value expression, because the
2073 // next layer copies r-values into memory to use the access-chain mechanism
2074 builder.clearAccessChain();
2075 builder.setAccessChainLValue(result);
2076 }
2077
2078 return false;
2079}
2080
2081bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2082{
2083 // emit and get the condition before doing anything with switch
2084 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002085 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002086
Rex Xu57e65922017-07-04 23:23:40 +08002087 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002088 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002089
John Kessenich140f3df2015-06-26 16:58:36 -06002090 // browse the children to sort out code segments
2091 int defaultSegment = -1;
2092 std::vector<TIntermNode*> codeSegments;
2093 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2094 std::vector<int> caseValues;
2095 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2096 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2097 TIntermNode* child = *c;
2098 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002099 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002100 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002101 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002102 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2103 } else
2104 codeSegments.push_back(child);
2105 }
2106
qining25262b32016-05-06 17:25:16 -04002107 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002108 // statements between the last case and the end of the switch statement
2109 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2110 (int)codeSegments.size() == defaultSegment)
2111 codeSegments.push_back(nullptr);
2112
2113 // make the switch statement
2114 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002115 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002116
2117 // emit all the code in the segments
2118 breakForLoop.push(false);
2119 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2120 builder.nextSwitchSegment(segmentBlocks, s);
2121 if (codeSegments[s])
2122 codeSegments[s]->traverse(this);
2123 else
2124 builder.addSwitchBreak();
2125 }
2126 breakForLoop.pop();
2127
2128 builder.endSwitch(segmentBlocks);
2129
2130 return false;
2131}
2132
2133void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2134{
2135 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002136 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002137
2138 builder.clearAccessChain();
2139 builder.setAccessChainRValue(constant);
2140}
2141
2142bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2143{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002144 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002145 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002146
2147 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002148 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2149 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002150
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002151 // Spec requires back edges to target header blocks, and every header block
2152 // must dominate its merge block. Make a header block first to ensure these
2153 // conditions are met. By definition, it will contain OpLoopMerge, followed
2154 // by a block-ending branch. But we don't want to put any other body/test
2155 // instructions in it, since the body/test may have arbitrary instructions,
2156 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002157 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002158 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002159 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002160 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002161 spv::Block& test = builder.makeNewBlock();
2162 builder.createBranch(&test);
2163
2164 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002165 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002166 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002167 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2168
2169 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002170 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002171 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002172 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002173 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002174 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002175
2176 builder.setBuildPoint(&blocks.continue_target);
2177 if (node->getTerminal())
2178 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002179 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002180 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002181 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002182 builder.createBranch(&blocks.body);
2183
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002184 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002185 builder.setBuildPoint(&blocks.body);
2186 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002187 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002188 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002189 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002190
2191 builder.setBuildPoint(&blocks.continue_target);
2192 if (node->getTerminal())
2193 node->getTerminal()->traverse(this);
2194 if (node->getTest()) {
2195 node->getTest()->traverse(this);
2196 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002197 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002198 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002199 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002200 // TODO: unless there was a break/return/discard instruction
2201 // somewhere in the body, this is an infinite loop, so we should
2202 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002203 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002204 }
John Kessenich140f3df2015-06-26 16:58:36 -06002205 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002206 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002207 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002208 return false;
2209}
2210
2211bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2212{
2213 if (node->getExpression())
2214 node->getExpression()->traverse(this);
2215
John Kesseniche485c7a2017-05-31 18:50:53 -06002216 builder.setLine(node->getLoc().line);
2217
John Kessenich140f3df2015-06-26 16:58:36 -06002218 switch (node->getFlowOp()) {
2219 case glslang::EOpKill:
2220 builder.makeDiscard();
2221 break;
2222 case glslang::EOpBreak:
2223 if (breakForLoop.top())
2224 builder.createLoopExit();
2225 else
2226 builder.addSwitchBreak();
2227 break;
2228 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002229 builder.createLoopContinue();
2230 break;
2231 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002232 if (node->getExpression()) {
2233 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2234 spv::Id returnId = accessChainLoad(glslangReturnType);
2235 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2236 builder.clearAccessChain();
2237 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2238 builder.setAccessChainLValue(copyId);
2239 multiTypeStore(glslangReturnType, returnId);
2240 returnId = builder.createLoad(copyId);
2241 }
2242 builder.makeReturn(false, returnId);
2243 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002244 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002245
2246 builder.clearAccessChain();
2247 break;
2248
2249 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002251 break;
2252 }
2253
2254 return false;
2255}
2256
2257spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2258{
qining25262b32016-05-06 17:25:16 -04002259 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002260 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002261 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002262 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002263 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002264 }
2265
2266 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002267 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002268 spv::Id spvType = convertGlslangToSpvType(node->getType());
2269
Rex Xuf89ad982017-04-07 23:22:33 +08002270#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002271 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2272 node->getType().containsBasicType(glslang::EbtInt16) ||
2273 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002274 if (contains16BitType) {
2275 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2276 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2277 builder.addCapability(spv::CapabilityStorageInputOutput16);
2278 } else if (storageClass == spv::StorageClassPushConstant) {
2279 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2280 builder.addCapability(spv::CapabilityStoragePushConstant16);
2281 } else if (storageClass == spv::StorageClassUniform) {
2282 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2283 builder.addCapability(spv::CapabilityStorageUniform16);
2284 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2285 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2286 }
2287 }
2288#endif
2289
John Kessenich140f3df2015-06-26 16:58:36 -06002290 const char* name = node->getName().c_str();
2291 if (glslang::IsAnonymous(name))
2292 name = "";
2293
2294 return builder.createVariable(storageClass, spvType, name);
2295}
2296
2297// Return type Id of the sampled type.
2298spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2299{
2300 switch (sampler.type) {
2301 case glslang::EbtFloat: return builder.makeFloatType(32);
2302 case glslang::EbtInt: return builder.makeIntType(32);
2303 case glslang::EbtUint: return builder.makeUintType(32);
2304 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002305 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002306 return builder.makeFloatType(32);
2307 }
2308}
2309
John Kessenich8c8505c2016-07-26 12:50:38 -06002310// If node is a swizzle operation, return the type that should be used if
2311// the swizzle base is first consumed by another operation, before the swizzle
2312// is applied.
2313spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2314{
John Kessenichecba76f2017-01-06 00:34:48 -07002315 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002316 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2317 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2318 else
2319 return spv::NoType;
2320}
2321
2322// When inverting a swizzle with a parent op, this function
2323// will apply the swizzle operation to a completed parent operation.
2324spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2325{
2326 std::vector<unsigned> swizzle;
2327 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2328 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2329}
2330
John Kessenich8c8505c2016-07-26 12:50:38 -06002331// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2332void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2333{
2334 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2335 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2336 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2337}
2338
John Kessenich3ac051e2015-12-20 11:29:16 -07002339// Convert from a glslang type to an SPV type, by calling into a
2340// recursive version of this function. This establishes the inherited
2341// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002342spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2343{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002344 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002345}
2346
2347// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002348// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002349// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002350spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002351{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002352 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002353
2354 switch (type.getBasicType()) {
2355 case glslang::EbtVoid:
2356 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002357 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002358 break;
2359 case glslang::EbtFloat:
2360 spvType = builder.makeFloatType(32);
2361 break;
2362 case glslang::EbtDouble:
2363 spvType = builder.makeFloatType(64);
2364 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002365#ifdef AMD_EXTENSIONS
2366 case glslang::EbtFloat16:
2367 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002368 spvType = builder.makeFloatType(16);
2369 break;
2370#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002371 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002372 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2373 // a 32-bit int where non-0 means true.
2374 if (explicitLayout != glslang::ElpNone)
2375 spvType = builder.makeUintType(32);
2376 else
2377 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EbtInt:
2380 spvType = builder.makeIntType(32);
2381 break;
2382 case glslang::EbtUint:
2383 spvType = builder.makeUintType(32);
2384 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002385 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002386 spvType = builder.makeIntType(64);
2387 break;
2388 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002389 spvType = builder.makeUintType(64);
2390 break;
Rex Xucabbb782017-03-24 13:41:14 +08002391#ifdef AMD_EXTENSIONS
2392 case glslang::EbtInt16:
2393 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2394 spvType = builder.makeIntType(16);
2395 break;
2396 case glslang::EbtUint16:
2397 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2398 spvType = builder.makeUintType(16);
2399 break;
2400#endif
John Kessenich426394d2015-07-23 10:22:48 -06002401 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002402 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002403 spvType = builder.makeUintType(32);
2404 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002405 case glslang::EbtSampler:
2406 {
2407 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002408 if (sampler.sampler) {
2409 // pure sampler
2410 spvType = builder.makeSamplerType();
2411 } else {
2412 // an image is present, make its type
2413 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2414 sampler.image ? 2 : 1, TranslateImageFormat(type));
2415 if (sampler.combined) {
2416 // already has both image and sampler, make the combined type
2417 spvType = builder.makeSampledImageType(spvType);
2418 }
John Kessenich55e7d112015-11-15 21:33:39 -07002419 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002420 }
John Kessenich140f3df2015-06-26 16:58:36 -06002421 break;
2422 case glslang::EbtStruct:
2423 case glslang::EbtBlock:
2424 {
2425 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002426 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002427
2428 // Try to share structs for different layouts, but not yet for other
2429 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002430 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002431 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002432 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002433 break;
2434
2435 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002436 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002437 memberRemapper[glslangMembers].resize(glslangMembers->size());
2438 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002439 }
2440 break;
2441 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002442 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002443 break;
2444 }
2445
2446 if (type.isMatrix())
2447 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2448 else {
2449 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2450 if (type.getVectorSize() > 1)
2451 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2452 }
2453
2454 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002455 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2456
John Kessenichc9a80832015-09-12 12:17:44 -06002457 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002459 // We need to decorate array strides for types needing explicit layout, except blocks.
2460 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002461 // Use a dummy glslang type for querying internal strides of
2462 // arrays of arrays, but using just a one-dimensional array.
2463 glslang::TType simpleArrayType(type, 0); // deference type of the array
2464 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2465 simpleArrayType.getArraySizes().dereference();
2466
2467 // Will compute the higher-order strides here, rather than making a whole
2468 // pile of types and doing repetitive recursion on their contents.
2469 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2470 }
John Kessenichf8842e52016-01-04 19:22:56 -07002471
2472 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002473 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002474 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002475 if (stride > 0)
2476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002477 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002478 }
2479 } else {
2480 // single-dimensional array, and don't yet have stride
2481
John Kessenichf8842e52016-01-04 19:22:56 -07002482 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002483 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2484 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002485 }
John Kessenich31ed4832015-09-09 17:51:38 -06002486
John Kessenichc9a80832015-09-12 12:17:44 -06002487 // Do the outer dimension, which might not be known for a runtime-sized array
2488 if (type.isRuntimeSizedArray()) {
2489 spvType = builder.makeRuntimeArray(spvType);
2490 } else {
2491 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002492 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002493 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002494 if (stride > 0)
2495 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002496 }
2497
2498 return spvType;
2499}
2500
John Kessenich0e737842017-03-24 18:38:16 -06002501// TODO: this functionality should exist at a higher level, in creating the AST
2502//
2503// Identify interface members that don't have their required extension turned on.
2504//
2505bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2506{
2507 auto& extensions = glslangIntermediate->getRequestedExtensions();
2508
Rex Xubcf291a2017-03-29 23:01:36 +08002509 if (member.getFieldName() == "gl_ViewportMask" &&
2510 extensions.find("GL_NV_viewport_array2") == extensions.end())
2511 return true;
2512 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2513 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2514 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002515 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2516 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2517 return true;
2518 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2519 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2520 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002521 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2522 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2523 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002524
2525 return false;
2526};
2527
John Kessenich6090df02016-06-30 21:18:02 -06002528// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2529// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2530// Mutually recursive with convertGlslangToSpvType().
2531spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2532 const glslang::TTypeList* glslangMembers,
2533 glslang::TLayoutPacking explicitLayout,
2534 const glslang::TQualifier& qualifier)
2535{
2536 // Create a vector of struct types for SPIR-V to consume
2537 std::vector<spv::Id> spvMembers;
2538 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 -06002539 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2540 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2541 if (glslangMember.hiddenMember()) {
2542 ++memberDelta;
2543 if (type.getBasicType() == glslang::EbtBlock)
2544 memberRemapper[glslangMembers][i] = -1;
2545 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002546 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002547 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002548 if (filterMember(glslangMember))
2549 continue;
2550 }
John Kessenich6090df02016-06-30 21:18:02 -06002551 // modify just this child's view of the qualifier
2552 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2553 InheritQualifiers(memberQualifier, qualifier);
2554
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002555 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002556 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002557 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002558
2559 // recurse
2560 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2561 }
2562 }
2563
2564 // Make the SPIR-V type
2565 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002566 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002567 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2568
2569 // Decorate it
2570 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2571
2572 return spvType;
2573}
2574
2575void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2576 const glslang::TTypeList* glslangMembers,
2577 glslang::TLayoutPacking explicitLayout,
2578 const glslang::TQualifier& qualifier,
2579 spv::Id spvType)
2580{
2581 // Name and decorate the non-hidden members
2582 int offset = -1;
2583 int locationOffset = 0; // for use within the members of this struct
2584 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2585 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2586 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002587 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002588 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002589 if (filterMember(glslangMember))
2590 continue;
2591 }
John Kessenich6090df02016-06-30 21:18:02 -06002592
2593 // modify just this child's view of the qualifier
2594 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2595 InheritQualifiers(memberQualifier, qualifier);
2596
2597 // using -1 above to indicate a hidden member
2598 if (member >= 0) {
2599 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2600 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2601 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2602 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002603 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2604 type.getQualifier().storage == glslang::EvqVaryingOut) {
2605 if (type.getBasicType() == glslang::EbtBlock ||
2606 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002607 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2608 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2609 }
2610 }
2611 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2612
Rex Xu286ca432017-07-27 14:33:16 +08002613 if (type.getBasicType() == glslang::EbtBlock &&
2614 qualifier.storage == glslang::EvqBuffer) {
2615 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002616 std::vector<spv::Decoration> memory;
2617 TranslateMemoryDecoration(memberQualifier, memory);
2618 for (unsigned int i = 0; i < memory.size(); ++i)
2619 addMemberDecoration(spvType, member, memory[i]);
2620 }
2621
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002622 // Location assignment was already completed correctly by the front end,
2623 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002624 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002625 // ill-specified and decisions have been made to not allow this.
2626 if (! type.isArray() && memberQualifier.hasLocation())
2627 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002628
John Kessenich2f47bc92016-06-30 21:47:35 -06002629 if (qualifier.hasLocation()) // track for upcoming inheritance
2630 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2631
John Kessenich6090df02016-06-30 21:18:02 -06002632 // component, XFB, others
2633 if (glslangMember.getQualifier().hasComponent())
2634 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2635 if (glslangMember.getQualifier().hasXfbOffset())
2636 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2637 else if (explicitLayout != glslang::ElpNone) {
2638 // figure out what to do with offset, which is accumulating
2639 int nextOffset;
2640 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2641 if (offset >= 0)
2642 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2643 offset = nextOffset;
2644 }
2645
2646 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2647 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2648
2649 // built-in variable decorations
2650 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002651 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002652 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002653
2654#ifdef NV_EXTENSIONS
2655 if (builtIn == spv::BuiltInLayer) {
2656 // SPV_NV_viewport_array2 extension
2657 if (glslangMember.getQualifier().layoutViewportRelative){
2658 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2659 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2660 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2661 }
2662 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2663 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2664 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2665 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2666 }
2667 }
chaocdf3956c2017-02-14 14:52:34 -08002668 if (glslangMember.getQualifier().layoutPassthrough) {
2669 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2670 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2671 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2672 }
chaoc771d89f2017-01-13 01:10:53 -08002673#endif
John Kessenich6090df02016-06-30 21:18:02 -06002674 }
2675 }
2676
2677 // Decorate the structure
2678 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002679 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002680 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2681 builder.addCapability(spv::CapabilityGeometryStreams);
2682 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2683 }
John Kessenich6090df02016-06-30 21:18:02 -06002684}
2685
John Kessenich6c292d32016-02-15 20:58:50 -07002686// Turn the expression forming the array size into an id.
2687// This is not quite trivial, because of specialization constants.
2688// Sometimes, a raw constant is turned into an Id, and sometimes
2689// a specialization constant expression is.
2690spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2691{
2692 // First, see if this is sized with a node, meaning a specialization constant:
2693 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2694 if (specNode != nullptr) {
2695 builder.clearAccessChain();
2696 specNode->traverse(this);
2697 return accessChainLoad(specNode->getAsTyped()->getType());
2698 }
qining25262b32016-05-06 17:25:16 -04002699
John Kessenich6c292d32016-02-15 20:58:50 -07002700 // Otherwise, need a compile-time (front end) size, get it:
2701 int size = arraySizes.getDimSize(dim);
2702 assert(size > 0);
2703 return builder.makeUintConstant(size);
2704}
2705
John Kessenich103bef92016-02-08 21:38:15 -07002706// Wrap the builder's accessChainLoad to:
2707// - localize handling of RelaxedPrecision
2708// - use the SPIR-V inferred type instead of another conversion of the glslang type
2709// (avoids unnecessary work and possible type punning for structures)
2710// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002711spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2712{
John Kessenich103bef92016-02-08 21:38:15 -07002713 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2714 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2715
2716 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002717 if (type.getBasicType() == glslang::EbtBool) {
2718 if (builder.isScalarType(nominalTypeId)) {
2719 // Conversion for bool
2720 spv::Id boolType = builder.makeBoolType();
2721 if (nominalTypeId != boolType)
2722 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2723 } else if (builder.isVectorType(nominalTypeId)) {
2724 // Conversion for bvec
2725 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2726 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2727 if (nominalTypeId != bvecType)
2728 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2729 }
2730 }
John Kessenich103bef92016-02-08 21:38:15 -07002731
2732 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002733}
2734
Rex Xu27253232016-02-23 17:51:09 +08002735// Wrap the builder's accessChainStore to:
2736// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002737//
2738// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002739void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2740{
2741 // Need to convert to abstract types when necessary
2742 if (type.getBasicType() == glslang::EbtBool) {
2743 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2744
2745 if (builder.isScalarType(nominalTypeId)) {
2746 // Conversion for bool
2747 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002748 if (nominalTypeId != boolType) {
2749 // keep these outside arguments, for determinant order-of-evaluation
2750 spv::Id one = builder.makeUintConstant(1);
2751 spv::Id zero = builder.makeUintConstant(0);
2752 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2753 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002754 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002755 } else if (builder.isVectorType(nominalTypeId)) {
2756 // Conversion for bvec
2757 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2758 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002759 if (nominalTypeId != bvecType) {
2760 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002761 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2762 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2763 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002764 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002765 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2766 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002767 }
2768 }
2769
2770 builder.accessChainStore(rvalue);
2771}
2772
John Kessenich4bf71552016-09-02 11:20:21 -06002773// For storing when types match at the glslang level, but not might match at the
2774// SPIR-V level.
2775//
2776// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002777// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002778// as in a member-decorated way.
2779//
2780// NOTE: This function can handle any store request; if it's not special it
2781// simplifies to a simple OpStore.
2782//
2783// Implicitly uses the existing builder.accessChain as the storage target.
2784void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2785{
John Kessenichb3e24e42016-09-11 12:33:43 -06002786 // we only do the complex path here if it's an aggregate
2787 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002788 accessChainStore(type, rValue);
2789 return;
2790 }
2791
John Kessenichb3e24e42016-09-11 12:33:43 -06002792 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002793 spv::Id rType = builder.getTypeId(rValue);
2794 spv::Id lValue = builder.accessChainGetLValue();
2795 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2796 if (lType == rType) {
2797 accessChainStore(type, rValue);
2798 return;
2799 }
2800
John Kessenichb3e24e42016-09-11 12:33:43 -06002801 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002802 // where the two types were the same type in GLSL. This requires member
2803 // by member copy, recursively.
2804
John Kessenichb3e24e42016-09-11 12:33:43 -06002805 // If an array, copy element by element.
2806 if (type.isArray()) {
2807 glslang::TType glslangElementType(type, 0);
2808 spv::Id elementRType = builder.getContainedTypeId(rType);
2809 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2810 // get the source member
2811 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002812
John Kessenichb3e24e42016-09-11 12:33:43 -06002813 // set up the target storage
2814 builder.clearAccessChain();
2815 builder.setAccessChainLValue(lValue);
2816 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002817
John Kessenichb3e24e42016-09-11 12:33:43 -06002818 // store the member
2819 multiTypeStore(glslangElementType, elementRValue);
2820 }
2821 } else {
2822 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002823
John Kessenichb3e24e42016-09-11 12:33:43 -06002824 // loop over structure members
2825 const glslang::TTypeList& members = *type.getStruct();
2826 for (int m = 0; m < (int)members.size(); ++m) {
2827 const glslang::TType& glslangMemberType = *members[m].type;
2828
2829 // get the source member
2830 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2831 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2832
2833 // set up the target storage
2834 builder.clearAccessChain();
2835 builder.setAccessChainLValue(lValue);
2836 builder.accessChainPush(builder.makeIntConstant(m));
2837
2838 // store the member
2839 multiTypeStore(glslangMemberType, memberRValue);
2840 }
John Kessenich4bf71552016-09-02 11:20:21 -06002841 }
2842}
2843
John Kessenichf85e8062015-12-19 13:57:10 -07002844// Decide whether or not this type should be
2845// decorated with offsets and strides, and if so
2846// whether std140 or std430 rules should be applied.
2847glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002848{
John Kessenichf85e8062015-12-19 13:57:10 -07002849 // has to be a block
2850 if (type.getBasicType() != glslang::EbtBlock)
2851 return glslang::ElpNone;
2852
2853 // has to be a uniform or buffer block
2854 if (type.getQualifier().storage != glslang::EvqUniform &&
2855 type.getQualifier().storage != glslang::EvqBuffer)
2856 return glslang::ElpNone;
2857
2858 // return the layout to use
2859 switch (type.getQualifier().layoutPacking) {
2860 case glslang::ElpStd140:
2861 case glslang::ElpStd430:
2862 return type.getQualifier().layoutPacking;
2863 default:
2864 return glslang::ElpNone;
2865 }
John Kessenich31ed4832015-09-09 17:51:38 -06002866}
2867
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002868// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002869int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002870{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002871 int size;
John Kessenich49987892015-12-29 17:11:44 -07002872 int stride;
2873 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002874
2875 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002876}
2877
John Kessenich49987892015-12-29 17:11:44 -07002878// 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 -07002879// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002880int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002881{
John Kessenich49987892015-12-29 17:11:44 -07002882 glslang::TType elementType;
2883 elementType.shallowCopy(matrixType);
2884 elementType.clearArraySizes();
2885
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002886 int size;
John Kessenich49987892015-12-29 17:11:44 -07002887 int stride;
2888 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2889
2890 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002891}
2892
John Kessenich5e4b1242015-08-06 22:53:06 -06002893// Given a member type of a struct, realign the current offset for it, and compute
2894// the next (not yet aligned) offset for the next member, which will get aligned
2895// on the next call.
2896// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2897// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2898// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002899void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002900 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002901{
2902 // this will get a positive value when deemed necessary
2903 nextOffset = -1;
2904
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 // override anything in currentOffset with user-set offset
2906 if (memberType.getQualifier().hasOffset())
2907 currentOffset = memberType.getQualifier().layoutOffset;
2908
2909 // It could be that current linker usage in glslang updated all the layoutOffset,
2910 // in which case the following code does not matter. But, that's not quite right
2911 // once cross-compilation unit GLSL validation is done, as the original user
2912 // settings are needed in layoutOffset, and then the following will come into play.
2913
John Kessenichf85e8062015-12-19 13:57:10 -07002914 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002915 if (! memberType.getQualifier().hasOffset())
2916 currentOffset = -1;
2917
2918 return;
2919 }
2920
John Kessenichf85e8062015-12-19 13:57:10 -07002921 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002922 if (currentOffset < 0)
2923 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002924
John Kessenich5e4b1242015-08-06 22:53:06 -06002925 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2926 // but possibly not yet correctly aligned.
2927
2928 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002929 int dummyStride;
2930 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002931
2932 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002933 // TODO: make this consistent in early phases of code:
2934 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2935 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2936 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002937 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002938 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002939 int dummySize;
2940 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2941 if (componentAlignment <= 4)
2942 memberAlignment = componentAlignment;
2943 }
2944
2945 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002946 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002947
2948 // Bump up to vec4 if there is a bad straddle
2949 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2950 glslang::RoundToPow2(currentOffset, 16);
2951
John Kessenich5e4b1242015-08-06 22:53:06 -06002952 nextOffset = currentOffset + memberSize;
2953}
2954
David Netoa901ffe2016-06-08 14:11:40 +01002955void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002956{
David Netoa901ffe2016-06-08 14:11:40 +01002957 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2958 switch (glslangBuiltIn)
2959 {
2960 case glslang::EbvClipDistance:
2961 case glslang::EbvCullDistance:
2962 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002963#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002964 case glslang::EbvViewportMaskNV:
2965 case glslang::EbvSecondaryPositionNV:
2966 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002967 case glslang::EbvPositionPerViewNV:
2968 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002969#endif
David Netoa901ffe2016-06-08 14:11:40 +01002970 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2971 // Alternately, we could just call this for any glslang built-in, since the
2972 // capability already guards against duplicates.
2973 TranslateBuiltInDecoration(glslangBuiltIn, false);
2974 break;
2975 default:
2976 // Capabilities were already generated when the struct was declared.
2977 break;
2978 }
John Kessenichebb50532016-05-16 19:22:05 -06002979}
2980
John Kessenich6fccb3c2016-09-19 16:01:41 -06002981bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002982{
John Kessenicheee9d532016-09-19 18:09:30 -06002983 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002984}
2985
John Kessenichd41993d2017-09-10 15:21:05 -06002986// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002987// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2988// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002989bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2990{
John Kessenich6a14f782017-12-04 02:48:10 -07002991 assert(qualifier == glslang::EvqIn ||
2992 qualifier == glslang::EvqOut ||
2993 qualifier == glslang::EvqInOut ||
2994 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002995 return qualifier != glslang::EvqConstReadOnly;
2996}
2997
2998// Is parameter pass-by-original?
2999bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3000 bool implicitThisParam)
3001{
3002 if (implicitThisParam) // implicit this
3003 return true;
3004 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003005 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003006 return paramType.containsOpaque() || // sampler, etc.
3007 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3008}
3009
John Kessenich140f3df2015-06-26 16:58:36 -06003010// Make all the functions, skeletally, without actually visiting their bodies.
3011void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3012{
John Kessenichfad62972017-07-18 02:35:46 -06003013 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3014 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3015 if (paramPrecision != spv::NoPrecision)
3016 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003017 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003018 };
3019
John Kessenich140f3df2015-06-26 16:58:36 -06003020 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3021 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003022 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003023 continue;
3024
3025 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003026 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003027 //
qining25262b32016-05-06 17:25:16 -04003028 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003029 // function. What it is an address of varies:
3030 //
John Kessenich4bf71552016-09-02 11:20:21 -06003031 // - "in" parameters not marked as "const" can be written to without modifying the calling
3032 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003033 //
3034 // - "const in" parameters can just be the r-value, as no writes need occur.
3035 //
John Kessenich4bf71552016-09-02 11:20:21 -06003036 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3037 // 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 -06003038
3039 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003040 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003041 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3042
John Kessenichfad62972017-07-18 02:35:46 -06003043 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3044 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003045
John Kessenichfad62972017-07-18 02:35:46 -06003046 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003047 for (int p = 0; p < (int)parameters.size(); ++p) {
3048 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3049 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003050 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003051 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003052 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003053 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3054 else
John Kessenich4bf71552016-09-02 11:20:21 -06003055 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003056 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003057 paramTypes.push_back(typeId);
3058 }
3059
3060 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003061 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3062 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003063 glslFunction->getName().c_str(), paramTypes,
3064 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003065 if (implicitThis)
3066 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003067
3068 // Track function to emit/call later
3069 functionMap[glslFunction->getName().c_str()] = function;
3070
3071 // Set the parameter id's
3072 for (int p = 0; p < (int)parameters.size(); ++p) {
3073 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3074 // give a name too
3075 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3076 }
3077 }
3078}
3079
3080// Process all the initializers, while skipping the functions and link objects
3081void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3082{
3083 builder.setBuildPoint(shaderEntry->getLastBlock());
3084 for (int i = 0; i < (int)initializers.size(); ++i) {
3085 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3086 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3087
3088 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003089 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003090 initializer->traverse(this);
3091 }
3092 }
3093}
3094
3095// Process all the functions, while skipping initializers.
3096void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3097{
3098 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3099 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003100 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003101 node->traverse(this);
3102 }
3103}
3104
3105void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3106{
qining25262b32016-05-06 17:25:16 -04003107 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003108 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003109 currentFunction = functionMap[node->getName().c_str()];
3110 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003111 builder.setBuildPoint(functionBlock);
3112}
3113
Rex Xu04db3f52015-09-16 11:44:02 +08003114void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003115{
Rex Xufc618912015-09-09 16:42:49 +08003116 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003117
3118 glslang::TSampler sampler = {};
3119 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003120 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003121 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3122 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3123 }
3124
John Kessenich140f3df2015-06-26 16:58:36 -06003125 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3126 builder.clearAccessChain();
3127 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003128
3129 // Special case l-value operands
3130 bool lvalue = false;
3131 switch (node.getOp()) {
3132 case glslang::EOpImageAtomicAdd:
3133 case glslang::EOpImageAtomicMin:
3134 case glslang::EOpImageAtomicMax:
3135 case glslang::EOpImageAtomicAnd:
3136 case glslang::EOpImageAtomicOr:
3137 case glslang::EOpImageAtomicXor:
3138 case glslang::EOpImageAtomicExchange:
3139 case glslang::EOpImageAtomicCompSwap:
3140 if (i == 0)
3141 lvalue = true;
3142 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003143 case glslang::EOpSparseImageLoad:
3144 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3145 lvalue = true;
3146 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003147 case glslang::EOpSparseTexture:
3148 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3149 lvalue = true;
3150 break;
3151 case glslang::EOpSparseTextureClamp:
3152 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3153 lvalue = true;
3154 break;
3155 case glslang::EOpSparseTextureLod:
3156 case glslang::EOpSparseTextureOffset:
3157 if (i == 3)
3158 lvalue = true;
3159 break;
3160 case glslang::EOpSparseTextureFetch:
3161 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3162 lvalue = true;
3163 break;
3164 case glslang::EOpSparseTextureFetchOffset:
3165 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3166 lvalue = true;
3167 break;
3168 case glslang::EOpSparseTextureLodOffset:
3169 case glslang::EOpSparseTextureGrad:
3170 case glslang::EOpSparseTextureOffsetClamp:
3171 if (i == 4)
3172 lvalue = true;
3173 break;
3174 case glslang::EOpSparseTextureGradOffset:
3175 case glslang::EOpSparseTextureGradClamp:
3176 if (i == 5)
3177 lvalue = true;
3178 break;
3179 case glslang::EOpSparseTextureGradOffsetClamp:
3180 if (i == 6)
3181 lvalue = true;
3182 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003183 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003184 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3185 lvalue = true;
3186 break;
3187 case glslang::EOpSparseTextureGatherOffset:
3188 case glslang::EOpSparseTextureGatherOffsets:
3189 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3190 lvalue = true;
3191 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003192#ifdef AMD_EXTENSIONS
3193 case glslang::EOpSparseTextureGatherLod:
3194 if (i == 3)
3195 lvalue = true;
3196 break;
3197 case glslang::EOpSparseTextureGatherLodOffset:
3198 case glslang::EOpSparseTextureGatherLodOffsets:
3199 if (i == 4)
3200 lvalue = true;
3201 break;
Rex Xu129799a2017-07-05 17:23:28 +08003202 case glslang::EOpSparseImageLoadLod:
3203 if (i == 3)
3204 lvalue = true;
3205 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003206#endif
Rex Xufc618912015-09-09 16:42:49 +08003207 default:
3208 break;
3209 }
3210
Rex Xu6b86d492015-09-16 17:48:22 +08003211 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003212 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003213 else
John Kessenich32cfd492016-02-02 12:37:46 -07003214 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003215 }
3216}
3217
John Kessenichfc51d282015-08-19 13:34:18 -06003218void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003219{
John Kessenichfc51d282015-08-19 13:34:18 -06003220 builder.clearAccessChain();
3221 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003222 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003223}
John Kessenich140f3df2015-06-26 16:58:36 -06003224
John Kessenichfc51d282015-08-19 13:34:18 -06003225spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3226{
John Kesseniche485c7a2017-05-31 18:50:53 -06003227 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003228 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003229
3230 builder.setLine(node->getLoc().line);
3231
John Kessenichfc51d282015-08-19 13:34:18 -06003232 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003233 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3234 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3235 std::vector<spv::Id> arguments;
3236 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003237 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003238 else
3239 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003240 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003241
3242 spv::Builder::TextureParameters params = { };
3243 params.sampler = arguments[0];
3244
Rex Xu04db3f52015-09-16 11:44:02 +08003245 glslang::TCrackedTextureOp cracked;
3246 node->crackTexture(sampler, cracked);
3247
amhagan05506bb2017-06-13 16:53:02 -04003248 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003249
John Kessenichfc51d282015-08-19 13:34:18 -06003250 // Check for queries
3251 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003252 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3253 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003254 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003255
John Kessenichfc51d282015-08-19 13:34:18 -06003256 switch (node->getOp()) {
3257 case glslang::EOpImageQuerySize:
3258 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003259 if (arguments.size() > 1) {
3260 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003261 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003263 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003264 case glslang::EOpImageQuerySamples:
3265 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003266 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003267 case glslang::EOpTextureQueryLod:
3268 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003269 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003270 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003271 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003272 case glslang::EOpSparseTexelsResident:
3273 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003274 default:
3275 assert(0);
3276 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003277 }
John Kessenich140f3df2015-06-26 16:58:36 -06003278 }
3279
LoopDawg4425f242018-02-18 11:40:01 -07003280 int components = node->getType().getVectorSize();
3281
3282 if (node->getOp() == glslang::EOpTextureFetch) {
3283 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3284 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3285 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3286 // here around e.g. which ones return scalars or other types.
3287 components = 4;
3288 }
3289
3290 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3291
3292 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3293
Rex Xufc618912015-09-09 16:42:49 +08003294 // Check for image functions other than queries
3295 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003296 std::vector<spv::Id> operands;
3297 auto opIt = arguments.begin();
3298 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003299
3300 // Handle subpass operations
3301 // TODO: GLSL should change to have the "MS" only on the type rather than the
3302 // built-in function.
3303 if (cracked.subpass) {
3304 // add on the (0,0) coordinate
3305 spv::Id zero = builder.makeIntConstant(0);
3306 std::vector<spv::Id> comps;
3307 comps.push_back(zero);
3308 comps.push_back(zero);
3309 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3310 if (sampler.ms) {
3311 operands.push_back(spv::ImageOperandsSampleMask);
3312 operands.push_back(*(opIt++));
3313 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003314 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3315 builder.setPrecision(result, precision);
3316 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003317 }
3318
John Kessenich56bab042015-09-16 10:54:31 -06003319 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003320#ifdef AMD_EXTENSIONS
3321 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3322#else
John Kessenich56bab042015-09-16 10:54:31 -06003323 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003324#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003325 if (sampler.ms) {
3326 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003327 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003328#ifdef AMD_EXTENSIONS
3329 } else if (cracked.lod) {
3330 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3331 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3332
3333 operands.push_back(spv::ImageOperandsLodMask);
3334 operands.push_back(*opIt);
3335#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003336 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003337 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3338 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003339
LoopDawg4425f242018-02-18 11:40:01 -07003340 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3341 builder.setPrecision(result[0], precision);
3342
3343 // If needed, add a conversion constructor to the proper size.
3344 if (components != node->getType().getVectorSize())
3345 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3346
3347 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003348#ifdef AMD_EXTENSIONS
3349 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3350#else
John Kessenich56bab042015-09-16 10:54:31 -06003351 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003352#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003353 if (sampler.ms) {
3354 operands.push_back(*(opIt + 1));
3355 operands.push_back(spv::ImageOperandsSampleMask);
3356 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003357#ifdef AMD_EXTENSIONS
3358 } else if (cracked.lod) {
3359 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3360 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3361
3362 operands.push_back(*(opIt + 1));
3363 operands.push_back(spv::ImageOperandsLodMask);
3364 operands.push_back(*opIt);
3365#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003366 } else
3367 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003368 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003369 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3370 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003371 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003372#ifdef AMD_EXTENSIONS
3373 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3374#else
Rex Xu5eafa472016-02-19 22:24:03 +08003375 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003376#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003377 builder.addCapability(spv::CapabilitySparseResidency);
3378 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3379 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3380
3381 if (sampler.ms) {
3382 operands.push_back(spv::ImageOperandsSampleMask);
3383 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003384#ifdef AMD_EXTENSIONS
3385 } else if (cracked.lod) {
3386 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3387 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3388
3389 operands.push_back(spv::ImageOperandsLodMask);
3390 operands.push_back(*opIt++);
3391#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003392 }
3393
3394 // Create the return type that was a special structure
3395 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003396 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003397 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3398 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3399
3400 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3401
3402 // Decode the return type
3403 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3404 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003405 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003406 // Process image atomic operations
3407
3408 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3409 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003410 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003411
John Kessenich8c8505c2016-07-26 12:50:38 -06003412 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003413 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003414
3415 std::vector<spv::Id> operands;
3416 operands.push_back(pointer);
3417 for (; opIt != arguments.end(); ++opIt)
3418 operands.push_back(*opIt);
3419
John Kessenich8c8505c2016-07-26 12:50:38 -06003420 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003421 }
3422 }
3423
amhagan05506bb2017-06-13 16:53:02 -04003424#ifdef AMD_EXTENSIONS
3425 // Check for fragment mask functions other than queries
3426 if (cracked.fragMask) {
3427 assert(sampler.ms);
3428
3429 auto opIt = arguments.begin();
3430 std::vector<spv::Id> operands;
3431
3432 // Extract the image if necessary
3433 if (builder.isSampledImage(params.sampler))
3434 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3435
3436 operands.push_back(params.sampler);
3437 ++opIt;
3438
3439 if (sampler.isSubpass()) {
3440 // add on the (0,0) coordinate
3441 spv::Id zero = builder.makeIntConstant(0);
3442 std::vector<spv::Id> comps;
3443 comps.push_back(zero);
3444 comps.push_back(zero);
3445 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3446 }
3447
3448 for (; opIt != arguments.end(); ++opIt)
3449 operands.push_back(*opIt);
3450
3451 spv::Op fragMaskOp = spv::OpNop;
3452 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3453 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3454 else if (node->getOp() == glslang::EOpFragmentFetch)
3455 fragMaskOp = spv::OpFragmentFetchAMD;
3456
3457 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3458 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3459 return builder.createOp(fragMaskOp, resultType(), operands);
3460 }
3461#endif
3462
Rex Xufc618912015-09-09 16:42:49 +08003463 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003464 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003465 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3466
John Kessenichfc51d282015-08-19 13:34:18 -06003467 // check for bias argument
3468 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003469#ifdef AMD_EXTENSIONS
3470 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3471#else
Rex Xu71519fe2015-11-11 15:35:47 +08003472 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003473#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003474 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003475#ifdef AMD_EXTENSIONS
3476 if (cracked.gather)
3477 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3478#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003479 if (cracked.offset)
3480 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003481#ifdef AMD_EXTENSIONS
3482 else if (cracked.offsets)
3483 ++nonBiasArgCount;
3484#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003485 if (cracked.grad)
3486 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003487 if (cracked.lodClamp)
3488 ++nonBiasArgCount;
3489 if (sparse)
3490 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003491
3492 if ((int)arguments.size() > nonBiasArgCount)
3493 bias = true;
3494 }
3495
John Kessenicha5c33d62016-06-02 23:45:21 -06003496 // See if the sampler param should really be just the SPV image part
3497 if (cracked.fetch) {
3498 // a fetch needs to have the image extracted first
3499 if (builder.isSampledImage(params.sampler))
3500 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3501 }
3502
Rex Xu225e0fc2016-11-17 17:47:59 +08003503#ifdef AMD_EXTENSIONS
3504 if (cracked.gather) {
3505 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3506 if (bias || cracked.lod ||
3507 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3508 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003509 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003510 }
3511 }
3512#endif
3513
John Kessenichfc51d282015-08-19 13:34:18 -06003514 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003515
John Kessenichfc51d282015-08-19 13:34:18 -06003516 params.coords = arguments[1];
3517 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003518 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003519
3520 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003521 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003522 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003523 ++extraArgs;
3524 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003525 params.Dref = arguments[2];
3526 ++extraArgs;
3527 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003528 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003529 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003530 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003531 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003532 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003533 dRefComp = builder.getNumComponents(params.coords) - 1;
3534 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003535 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3536 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003537
3538 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003539 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003540 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003541 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003542 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3543 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3544 noImplicitLod = true;
3545 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003546
3547 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003548 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003549 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003550 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003551 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003552
3553 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003554 if (cracked.grad) {
3555 params.gradX = arguments[2 + extraArgs];
3556 params.gradY = arguments[3 + extraArgs];
3557 extraArgs += 2;
3558 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003559
3560 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003561 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003562 params.offset = arguments[2 + extraArgs];
3563 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003564 } else if (cracked.offsets) {
3565 params.offsets = arguments[2 + extraArgs];
3566 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003567 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003568
3569 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003570 if (cracked.lodClamp) {
3571 params.lodClamp = arguments[2 + extraArgs];
3572 ++extraArgs;
3573 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003574
3575 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003576 if (sparse) {
3577 params.texelOut = arguments[2 + extraArgs];
3578 ++extraArgs;
3579 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003580
John Kessenich76d4dfc2016-06-16 12:43:23 -06003581 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003582 if (cracked.gather && ! sampler.shadow) {
3583 // default component is 0, if missing, otherwise an argument
3584 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003585 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003586 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003587 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003588 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003589 }
3590
3591 // bias
3592 if (bias) {
3593 params.bias = arguments[2 + extraArgs];
3594 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003595 }
John Kessenichfc51d282015-08-19 13:34:18 -06003596
John Kessenich65336482016-06-16 14:06:26 -06003597 // projective component (might not to move)
3598 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3599 // are divided by the last component of P."
3600 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3601 // unused components will appear after all used components."
3602 if (cracked.proj) {
3603 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3604 int projTargetComp;
3605 switch (sampler.dim) {
3606 case glslang::Esd1D: projTargetComp = 1; break;
3607 case glslang::Esd2D: projTargetComp = 2; break;
3608 case glslang::EsdRect: projTargetComp = 2; break;
3609 default: projTargetComp = projSourceComp; break;
3610 }
3611 // copy the projective coordinate if we have to
3612 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003613 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003614 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3615 projSourceComp);
3616 params.coords = builder.createCompositeInsert(projComp, params.coords,
3617 builder.getTypeId(params.coords), projTargetComp);
3618 }
3619 }
3620
LoopDawg4425f242018-02-18 11:40:01 -07003621 std::vector<spv::Id> result = {
3622 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3623 };
3624
3625 if (components != node->getType().getVectorSize())
3626 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3627
3628 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003629}
3630
3631spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3632{
3633 // Grab the function's pointer from the previously created function
3634 spv::Function* function = functionMap[node->getName().c_str()];
3635 if (! function)
3636 return 0;
3637
3638 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3639 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3640
3641 // See comments in makeFunctions() for details about the semantics for parameter passing.
3642 //
3643 // These imply we need a four step process:
3644 // 1. Evaluate the arguments
3645 // 2. Allocate and make copies of in, out, and inout arguments
3646 // 3. Make the call
3647 // 4. Copy back the results
3648
3649 // 1. Evaluate the arguments
3650 std::vector<spv::Builder::AccessChain> lValues;
3651 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003652 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003653 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003654 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003655 // build l-value
3656 builder.clearAccessChain();
3657 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003658 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003659 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003660 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3661 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003662 // save l-value
3663 lValues.push_back(builder.getAccessChain());
3664 } else {
3665 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003666 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003667 }
3668 }
3669
3670 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3671 // copy the original into that space.
3672 //
3673 // Also, build up the list of actual arguments to pass in for the call
3674 int lValueCount = 0;
3675 int rValueCount = 0;
3676 std::vector<spv::Id> spvArgs;
3677 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003678 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003679 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003680 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003681 builder.setAccessChain(lValues[lValueCount]);
3682 arg = builder.accessChainGetLValue();
3683 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003684 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003685 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003686 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3687 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3688 // need to copy the input into output space
3689 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003690 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003691 builder.clearAccessChain();
3692 builder.setAccessChainLValue(arg);
3693 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003694 }
3695 ++lValueCount;
3696 } else {
3697 arg = rValues[rValueCount];
3698 ++rValueCount;
3699 }
3700 spvArgs.push_back(arg);
3701 }
3702
3703 // 3. Make the call.
3704 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003705 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003706
3707 // 4. Copy back out an "out" arguments.
3708 lValueCount = 0;
3709 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003710 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003711 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3712 ++lValueCount;
3713 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003714 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3715 spv::Id copy = builder.createLoad(spvArgs[a]);
3716 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003717 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003718 }
3719 ++lValueCount;
3720 }
3721 }
3722
3723 return result;
3724}
3725
3726// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003727spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3728 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003729 spv::Id typeId, spv::Id left, spv::Id right,
3730 glslang::TBasicType typeProxy, bool reduceComparison)
3731{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003732#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003733 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003734 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3735#else
Rex Xucabbb782017-03-24 13:41:14 +08003736 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003737 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003738#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003739 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003740
3741 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003742 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003743 bool comparison = false;
3744
3745 switch (op) {
3746 case glslang::EOpAdd:
3747 case glslang::EOpAddAssign:
3748 if (isFloat)
3749 binOp = spv::OpFAdd;
3750 else
3751 binOp = spv::OpIAdd;
3752 break;
3753 case glslang::EOpSub:
3754 case glslang::EOpSubAssign:
3755 if (isFloat)
3756 binOp = spv::OpFSub;
3757 else
3758 binOp = spv::OpISub;
3759 break;
3760 case glslang::EOpMul:
3761 case glslang::EOpMulAssign:
3762 if (isFloat)
3763 binOp = spv::OpFMul;
3764 else
3765 binOp = spv::OpIMul;
3766 break;
3767 case glslang::EOpVectorTimesScalar:
3768 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003769 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003770 if (builder.isVector(right))
3771 std::swap(left, right);
3772 assert(builder.isScalar(right));
3773 needMatchingVectors = false;
3774 binOp = spv::OpVectorTimesScalar;
3775 } else
3776 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
3778 case glslang::EOpVectorTimesMatrix:
3779 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003780 binOp = spv::OpVectorTimesMatrix;
3781 break;
3782 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003783 binOp = spv::OpMatrixTimesVector;
3784 break;
3785 case glslang::EOpMatrixTimesScalar:
3786 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003787 binOp = spv::OpMatrixTimesScalar;
3788 break;
3789 case glslang::EOpMatrixTimesMatrix:
3790 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003791 binOp = spv::OpMatrixTimesMatrix;
3792 break;
3793 case glslang::EOpOuterProduct:
3794 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003795 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003796 break;
3797
3798 case glslang::EOpDiv:
3799 case glslang::EOpDivAssign:
3800 if (isFloat)
3801 binOp = spv::OpFDiv;
3802 else if (isUnsigned)
3803 binOp = spv::OpUDiv;
3804 else
3805 binOp = spv::OpSDiv;
3806 break;
3807 case glslang::EOpMod:
3808 case glslang::EOpModAssign:
3809 if (isFloat)
3810 binOp = spv::OpFMod;
3811 else if (isUnsigned)
3812 binOp = spv::OpUMod;
3813 else
3814 binOp = spv::OpSMod;
3815 break;
3816 case glslang::EOpRightShift:
3817 case glslang::EOpRightShiftAssign:
3818 if (isUnsigned)
3819 binOp = spv::OpShiftRightLogical;
3820 else
3821 binOp = spv::OpShiftRightArithmetic;
3822 break;
3823 case glslang::EOpLeftShift:
3824 case glslang::EOpLeftShiftAssign:
3825 binOp = spv::OpShiftLeftLogical;
3826 break;
3827 case glslang::EOpAnd:
3828 case glslang::EOpAndAssign:
3829 binOp = spv::OpBitwiseAnd;
3830 break;
3831 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003832 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 binOp = spv::OpLogicalAnd;
3834 break;
3835 case glslang::EOpInclusiveOr:
3836 case glslang::EOpInclusiveOrAssign:
3837 binOp = spv::OpBitwiseOr;
3838 break;
3839 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003840 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003841 binOp = spv::OpLogicalOr;
3842 break;
3843 case glslang::EOpExclusiveOr:
3844 case glslang::EOpExclusiveOrAssign:
3845 binOp = spv::OpBitwiseXor;
3846 break;
3847 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003848 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003849 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003850 break;
3851
3852 case glslang::EOpLessThan:
3853 case glslang::EOpGreaterThan:
3854 case glslang::EOpLessThanEqual:
3855 case glslang::EOpGreaterThanEqual:
3856 case glslang::EOpEqual:
3857 case glslang::EOpNotEqual:
3858 case glslang::EOpVectorEqual:
3859 case glslang::EOpVectorNotEqual:
3860 comparison = true;
3861 break;
3862 default:
3863 break;
3864 }
3865
John Kessenich7c1aa102015-10-15 13:29:11 -06003866 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003867 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003868 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003869 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003870 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003871
3872 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003873 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003874 builder.promoteScalar(precision, left, right);
3875
qining25262b32016-05-06 17:25:16 -04003876 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3877 addDecoration(result, noContraction);
3878 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003879 }
3880
3881 if (! comparison)
3882 return 0;
3883
John Kessenich7c1aa102015-10-15 13:29:11 -06003884 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003885
John Kessenich4583b612016-08-07 19:14:22 -06003886 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3887 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003888 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003889
3890 switch (op) {
3891 case glslang::EOpLessThan:
3892 if (isFloat)
3893 binOp = spv::OpFOrdLessThan;
3894 else if (isUnsigned)
3895 binOp = spv::OpULessThan;
3896 else
3897 binOp = spv::OpSLessThan;
3898 break;
3899 case glslang::EOpGreaterThan:
3900 if (isFloat)
3901 binOp = spv::OpFOrdGreaterThan;
3902 else if (isUnsigned)
3903 binOp = spv::OpUGreaterThan;
3904 else
3905 binOp = spv::OpSGreaterThan;
3906 break;
3907 case glslang::EOpLessThanEqual:
3908 if (isFloat)
3909 binOp = spv::OpFOrdLessThanEqual;
3910 else if (isUnsigned)
3911 binOp = spv::OpULessThanEqual;
3912 else
3913 binOp = spv::OpSLessThanEqual;
3914 break;
3915 case glslang::EOpGreaterThanEqual:
3916 if (isFloat)
3917 binOp = spv::OpFOrdGreaterThanEqual;
3918 else if (isUnsigned)
3919 binOp = spv::OpUGreaterThanEqual;
3920 else
3921 binOp = spv::OpSGreaterThanEqual;
3922 break;
3923 case glslang::EOpEqual:
3924 case glslang::EOpVectorEqual:
3925 if (isFloat)
3926 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003927 else if (isBool)
3928 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003929 else
3930 binOp = spv::OpIEqual;
3931 break;
3932 case glslang::EOpNotEqual:
3933 case glslang::EOpVectorNotEqual:
3934 if (isFloat)
3935 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003936 else if (isBool)
3937 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003938 else
3939 binOp = spv::OpINotEqual;
3940 break;
3941 default:
3942 break;
3943 }
3944
qining25262b32016-05-06 17:25:16 -04003945 if (binOp != spv::OpNop) {
3946 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3947 addDecoration(result, noContraction);
3948 return builder.setPrecision(result, precision);
3949 }
John Kessenich140f3df2015-06-26 16:58:36 -06003950
3951 return 0;
3952}
3953
John Kessenich04bb8a02015-12-12 12:28:14 -07003954//
3955// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3956// These can be any of:
3957//
3958// matrix * scalar
3959// scalar * matrix
3960// matrix * matrix linear algebraic
3961// matrix * vector
3962// vector * matrix
3963// matrix * matrix componentwise
3964// matrix op matrix op in {+, -, /}
3965// matrix op scalar op in {+, -, /}
3966// scalar op matrix op in {+, -, /}
3967//
qining25262b32016-05-06 17:25:16 -04003968spv::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 -07003969{
3970 bool firstClass = true;
3971
3972 // First, handle first-class matrix operations (* and matrix/scalar)
3973 switch (op) {
3974 case spv::OpFDiv:
3975 if (builder.isMatrix(left) && builder.isScalar(right)) {
3976 // turn matrix / scalar into a multiply...
3977 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3978 op = spv::OpMatrixTimesScalar;
3979 } else
3980 firstClass = false;
3981 break;
3982 case spv::OpMatrixTimesScalar:
3983 if (builder.isMatrix(right))
3984 std::swap(left, right);
3985 assert(builder.isScalar(right));
3986 break;
3987 case spv::OpVectorTimesMatrix:
3988 assert(builder.isVector(left));
3989 assert(builder.isMatrix(right));
3990 break;
3991 case spv::OpMatrixTimesVector:
3992 assert(builder.isMatrix(left));
3993 assert(builder.isVector(right));
3994 break;
3995 case spv::OpMatrixTimesMatrix:
3996 assert(builder.isMatrix(left));
3997 assert(builder.isMatrix(right));
3998 break;
3999 default:
4000 firstClass = false;
4001 break;
4002 }
4003
qining25262b32016-05-06 17:25:16 -04004004 if (firstClass) {
4005 spv::Id result = builder.createBinOp(op, typeId, left, right);
4006 addDecoration(result, noContraction);
4007 return builder.setPrecision(result, precision);
4008 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004009
LoopDawg592860c2016-06-09 08:57:35 -06004010 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004011 // The result type of all of them is the same type as the (a) matrix operand.
4012 // The algorithm is to:
4013 // - break the matrix(es) into vectors
4014 // - smear any scalar to a vector
4015 // - do vector operations
4016 // - make a matrix out the vector results
4017 switch (op) {
4018 case spv::OpFAdd:
4019 case spv::OpFSub:
4020 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004021 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004022 case spv::OpFMul:
4023 {
4024 // one time set up...
4025 bool leftMat = builder.isMatrix(left);
4026 bool rightMat = builder.isMatrix(right);
4027 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4028 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4029 spv::Id scalarType = builder.getScalarTypeId(typeId);
4030 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4031 std::vector<spv::Id> results;
4032 spv::Id smearVec = spv::NoResult;
4033 if (builder.isScalar(left))
4034 smearVec = builder.smearScalar(precision, left, vecType);
4035 else if (builder.isScalar(right))
4036 smearVec = builder.smearScalar(precision, right, vecType);
4037
4038 // do each vector op
4039 for (unsigned int c = 0; c < numCols; ++c) {
4040 std::vector<unsigned int> indexes;
4041 indexes.push_back(c);
4042 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4043 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004044 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4045 addDecoration(result, noContraction);
4046 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004047 }
4048
4049 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004050 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004051 }
4052 default:
4053 assert(0);
4054 return spv::NoResult;
4055 }
4056}
4057
qining25262b32016-05-06 17:25:16 -04004058spv::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 -06004059{
4060 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004061 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004063#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004064 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004065 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4066#else
Rex Xucabbb782017-03-24 13:41:14 +08004067 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004068 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004069#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004070
4071 switch (op) {
4072 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004073 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004074 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004075 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004076 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004077 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004078 unaryOp = spv::OpSNegate;
4079 break;
4080
4081 case glslang::EOpLogicalNot:
4082 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004083 unaryOp = spv::OpLogicalNot;
4084 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 case glslang::EOpBitwiseNot:
4086 unaryOp = spv::OpNot;
4087 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004088
John Kessenich140f3df2015-06-26 16:58:36 -06004089 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095 case glslang::EOpTranspose:
4096 unaryOp = spv::OpTranspose;
4097 break;
4098
4099 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 break;
4105 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004106 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004107 break;
4108 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004110 break;
4111 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004112 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004113 break;
4114 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004115 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004116 break;
4117 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004118 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004121 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004122 break;
4123
4124 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004125 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004126 break;
4127 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004128 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004129 break;
4130 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004131 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004132 break;
4133 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004134 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004135 break;
4136 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004137 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004138 break;
4139 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004140 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004141 break;
4142
4143 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004144 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004145 break;
4146 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004147 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004148 break;
4149
4150 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004154 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004155 break;
4156 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004157 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004158 break;
4159 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004160 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004161 break;
4162 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004163 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004164 break;
4165 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004166 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004167 break;
4168
4169 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004170 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004171 break;
4172 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004173 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004174 break;
4175 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004176 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004177 break;
4178 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004179 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004180 break;
4181 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004182 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 break;
4184 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004185 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
4187
4188 case glslang::EOpIsNan:
4189 unaryOp = spv::OpIsNan;
4190 break;
4191 case glslang::EOpIsInf:
4192 unaryOp = spv::OpIsInf;
4193 break;
LoopDawg592860c2016-06-09 08:57:35 -06004194 case glslang::EOpIsFinite:
4195 unaryOp = spv::OpIsFinite;
4196 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004197
Rex Xucbc426e2015-12-15 16:03:10 +08004198 case glslang::EOpFloatBitsToInt:
4199 case glslang::EOpFloatBitsToUint:
4200 case glslang::EOpIntBitsToFloat:
4201 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004202 case glslang::EOpDoubleBitsToInt64:
4203 case glslang::EOpDoubleBitsToUint64:
4204 case glslang::EOpInt64BitsToDouble:
4205 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004206#ifdef AMD_EXTENSIONS
4207 case glslang::EOpFloat16BitsToInt16:
4208 case glslang::EOpFloat16BitsToUint16:
4209 case glslang::EOpInt16BitsToFloat16:
4210 case glslang::EOpUint16BitsToFloat16:
4211#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004212 unaryOp = spv::OpBitcast;
4213 break;
4214
John Kessenich140f3df2015-06-26 16:58:36 -06004215 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004216 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004217 break;
4218 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004219 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004220 break;
4221 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004222 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004223 break;
4224 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004225 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004226 break;
4227 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004228 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004229 break;
4230 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004231 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004232 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004233 case glslang::EOpPackSnorm4x8:
4234 libCall = spv::GLSLstd450PackSnorm4x8;
4235 break;
4236 case glslang::EOpUnpackSnorm4x8:
4237 libCall = spv::GLSLstd450UnpackSnorm4x8;
4238 break;
4239 case glslang::EOpPackUnorm4x8:
4240 libCall = spv::GLSLstd450PackUnorm4x8;
4241 break;
4242 case glslang::EOpUnpackUnorm4x8:
4243 libCall = spv::GLSLstd450UnpackUnorm4x8;
4244 break;
4245 case glslang::EOpPackDouble2x32:
4246 libCall = spv::GLSLstd450PackDouble2x32;
4247 break;
4248 case glslang::EOpUnpackDouble2x32:
4249 libCall = spv::GLSLstd450UnpackDouble2x32;
4250 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004251
Rex Xu8ff43de2016-04-22 16:51:45 +08004252 case glslang::EOpPackInt2x32:
4253 case glslang::EOpUnpackInt2x32:
4254 case glslang::EOpPackUint2x32:
4255 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004256 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004257 break;
4258
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004259#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004260 case glslang::EOpPackInt2x16:
4261 case glslang::EOpUnpackInt2x16:
4262 case glslang::EOpPackUint2x16:
4263 case glslang::EOpUnpackUint2x16:
4264 case glslang::EOpPackInt4x16:
4265 case glslang::EOpUnpackInt4x16:
4266 case glslang::EOpPackUint4x16:
4267 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004268 case glslang::EOpPackFloat2x16:
4269 case glslang::EOpUnpackFloat2x16:
4270 unaryOp = spv::OpBitcast;
4271 break;
4272#endif
4273
John Kessenich140f3df2015-06-26 16:58:36 -06004274 case glslang::EOpDPdx:
4275 unaryOp = spv::OpDPdx;
4276 break;
4277 case glslang::EOpDPdy:
4278 unaryOp = spv::OpDPdy;
4279 break;
4280 case glslang::EOpFwidth:
4281 unaryOp = spv::OpFwidth;
4282 break;
4283 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004284 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004285 unaryOp = spv::OpDPdxFine;
4286 break;
4287 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004288 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004289 unaryOp = spv::OpDPdyFine;
4290 break;
4291 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004292 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004293 unaryOp = spv::OpFwidthFine;
4294 break;
4295 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004296 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004297 unaryOp = spv::OpDPdxCoarse;
4298 break;
4299 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004300 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004301 unaryOp = spv::OpDPdyCoarse;
4302 break;
4303 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004304 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004305 unaryOp = spv::OpFwidthCoarse;
4306 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004307 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004308 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004309 libCall = spv::GLSLstd450InterpolateAtCentroid;
4310 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004311 case glslang::EOpAny:
4312 unaryOp = spv::OpAny;
4313 break;
4314 case glslang::EOpAll:
4315 unaryOp = spv::OpAll;
4316 break;
4317
4318 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004319 if (isFloat)
4320 libCall = spv::GLSLstd450FAbs;
4321 else
4322 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004323 break;
4324 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004325 if (isFloat)
4326 libCall = spv::GLSLstd450FSign;
4327 else
4328 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004329 break;
4330
John Kessenichfc51d282015-08-19 13:34:18 -06004331 case glslang::EOpAtomicCounterIncrement:
4332 case glslang::EOpAtomicCounterDecrement:
4333 case glslang::EOpAtomicCounter:
4334 {
4335 // Handle all of the atomics in one place, in createAtomicOperation()
4336 std::vector<spv::Id> operands;
4337 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004338 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004339 }
4340
John Kessenichfc51d282015-08-19 13:34:18 -06004341 case glslang::EOpBitFieldReverse:
4342 unaryOp = spv::OpBitReverse;
4343 break;
4344 case glslang::EOpBitCount:
4345 unaryOp = spv::OpBitCount;
4346 break;
4347 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004348 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004349 break;
4350 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004351 if (isUnsigned)
4352 libCall = spv::GLSLstd450FindUMsb;
4353 else
4354 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004355 break;
4356
Rex Xu574ab042016-04-14 16:53:07 +08004357 case glslang::EOpBallot:
4358 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004359 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004360 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004361 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004362#ifdef AMD_EXTENSIONS
4363 case glslang::EOpMinInvocations:
4364 case glslang::EOpMaxInvocations:
4365 case glslang::EOpAddInvocations:
4366 case glslang::EOpMinInvocationsNonUniform:
4367 case glslang::EOpMaxInvocationsNonUniform:
4368 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004369 case glslang::EOpMinInvocationsInclusiveScan:
4370 case glslang::EOpMaxInvocationsInclusiveScan:
4371 case glslang::EOpAddInvocationsInclusiveScan:
4372 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4373 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4374 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4375 case glslang::EOpMinInvocationsExclusiveScan:
4376 case glslang::EOpMaxInvocationsExclusiveScan:
4377 case glslang::EOpAddInvocationsExclusiveScan:
4378 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4379 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4380 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004381#endif
Rex Xu51596642016-09-21 18:56:12 +08004382 {
4383 std::vector<spv::Id> operands;
4384 operands.push_back(operand);
4385 return createInvocationsOperation(op, typeId, operands, typeProxy);
4386 }
Rex Xu9d93a232016-05-05 12:30:44 +08004387
4388#ifdef AMD_EXTENSIONS
4389 case glslang::EOpMbcnt:
4390 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4391 libCall = spv::MbcntAMD;
4392 break;
4393
4394 case glslang::EOpCubeFaceIndex:
4395 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4396 libCall = spv::CubeFaceIndexAMD;
4397 break;
4398
4399 case glslang::EOpCubeFaceCoord:
4400 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4401 libCall = spv::CubeFaceCoordAMD;
4402 break;
4403#endif
Rex Xu338b1852016-05-05 20:38:33 +08004404
John Kessenich140f3df2015-06-26 16:58:36 -06004405 default:
4406 return 0;
4407 }
4408
4409 spv::Id id;
4410 if (libCall >= 0) {
4411 std::vector<spv::Id> args;
4412 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004413 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004414 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004415 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004416 }
John Kessenich140f3df2015-06-26 16:58:36 -06004417
qining25262b32016-05-06 17:25:16 -04004418 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004419 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004420}
4421
John Kessenich7a53f762016-01-20 11:19:27 -07004422// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004423spv::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 -07004424{
4425 // Handle unary operations vector by vector.
4426 // The result type is the same type as the original type.
4427 // The algorithm is to:
4428 // - break the matrix into vectors
4429 // - apply the operation to each vector
4430 // - make a matrix out the vector results
4431
4432 // get the types sorted out
4433 int numCols = builder.getNumColumns(operand);
4434 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004435 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4436 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004437 std::vector<spv::Id> results;
4438
4439 // do each vector op
4440 for (int c = 0; c < numCols; ++c) {
4441 std::vector<unsigned int> indexes;
4442 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004443 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4444 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4445 addDecoration(destVec, noContraction);
4446 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004447 }
4448
4449 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004450 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004451}
4452
Rex Xu73e3ce72016-04-27 18:48:17 +08004453spv::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 -06004454{
4455 spv::Op convOp = spv::OpNop;
4456 spv::Id zero = 0;
4457 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004458 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004459
4460 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4461
4462 switch (op) {
4463 case glslang::EOpConvIntToBool:
4464 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004465 case glslang::EOpConvInt64ToBool:
4466 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004467#ifdef AMD_EXTENSIONS
4468 case glslang::EOpConvInt16ToBool:
4469 case glslang::EOpConvUint16ToBool:
4470#endif
4471 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4472 zero = builder.makeUint64Constant(0);
4473#ifdef AMD_EXTENSIONS
4474 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4475 zero = builder.makeUint16Constant(0);
4476#endif
4477 else
4478 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004479 zero = makeSmearedConstant(zero, vectorSize);
4480 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4481
4482 case glslang::EOpConvFloatToBool:
4483 zero = builder.makeFloatConstant(0.0F);
4484 zero = makeSmearedConstant(zero, vectorSize);
4485 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4486
4487 case glslang::EOpConvDoubleToBool:
4488 zero = builder.makeDoubleConstant(0.0);
4489 zero = makeSmearedConstant(zero, vectorSize);
4490 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4491
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004492#ifdef AMD_EXTENSIONS
4493 case glslang::EOpConvFloat16ToBool:
4494 zero = builder.makeFloat16Constant(0.0F);
4495 zero = makeSmearedConstant(zero, vectorSize);
4496 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4497#endif
4498
John Kessenich140f3df2015-06-26 16:58:36 -06004499 case glslang::EOpConvBoolToFloat:
4500 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004501 zero = builder.makeFloatConstant(0.0F);
4502 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004503 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004504
John Kessenich140f3df2015-06-26 16:58:36 -06004505 case glslang::EOpConvBoolToDouble:
4506 convOp = spv::OpSelect;
4507 zero = builder.makeDoubleConstant(0.0);
4508 one = builder.makeDoubleConstant(1.0);
4509 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004510
4511#ifdef AMD_EXTENSIONS
4512 case glslang::EOpConvBoolToFloat16:
4513 convOp = spv::OpSelect;
4514 zero = builder.makeFloat16Constant(0.0F);
4515 one = builder.makeFloat16Constant(1.0F);
4516 break;
4517#endif
4518
John Kessenich140f3df2015-06-26 16:58:36 -06004519 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004520 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004521#ifdef AMD_EXTENSIONS
4522 case glslang::EOpConvBoolToInt16:
4523#endif
4524 if (op == glslang::EOpConvBoolToInt64)
4525 zero = builder.makeInt64Constant(0);
4526#ifdef AMD_EXTENSIONS
4527 else if (op == glslang::EOpConvBoolToInt16)
4528 zero = builder.makeInt16Constant(0);
4529#endif
4530 else
4531 zero = builder.makeIntConstant(0);
4532
4533 if (op == glslang::EOpConvBoolToInt64)
4534 one = builder.makeInt64Constant(1);
4535#ifdef AMD_EXTENSIONS
4536 else if (op == glslang::EOpConvBoolToInt16)
4537 one = builder.makeInt16Constant(1);
4538#endif
4539 else
4540 one = builder.makeIntConstant(1);
4541
John Kessenich140f3df2015-06-26 16:58:36 -06004542 convOp = spv::OpSelect;
4543 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004544
John Kessenich140f3df2015-06-26 16:58:36 -06004545 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004546 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004547#ifdef AMD_EXTENSIONS
4548 case glslang::EOpConvBoolToUint16:
4549#endif
4550 if (op == glslang::EOpConvBoolToUint64)
4551 zero = builder.makeUint64Constant(0);
4552#ifdef AMD_EXTENSIONS
4553 else if (op == glslang::EOpConvBoolToUint16)
4554 zero = builder.makeUint16Constant(0);
4555#endif
4556 else
4557 zero = builder.makeUintConstant(0);
4558
4559 if (op == glslang::EOpConvBoolToUint64)
4560 one = builder.makeUint64Constant(1);
4561#ifdef AMD_EXTENSIONS
4562 else if (op == glslang::EOpConvBoolToUint16)
4563 one = builder.makeUint16Constant(1);
4564#endif
4565 else
4566 one = builder.makeUintConstant(1);
4567
John Kessenich140f3df2015-06-26 16:58:36 -06004568 convOp = spv::OpSelect;
4569 break;
4570
4571 case glslang::EOpConvIntToFloat:
4572 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004573 case glslang::EOpConvInt64ToFloat:
4574 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004575#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004576 case glslang::EOpConvInt16ToFloat:
4577 case glslang::EOpConvInt16ToDouble:
4578 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004579 case glslang::EOpConvIntToFloat16:
4580 case glslang::EOpConvInt64ToFloat16:
4581#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004582 convOp = spv::OpConvertSToF;
4583 break;
4584
4585 case glslang::EOpConvUintToFloat:
4586 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004587 case glslang::EOpConvUint64ToFloat:
4588 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004589#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004590 case glslang::EOpConvUint16ToFloat:
4591 case glslang::EOpConvUint16ToDouble:
4592 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004593 case glslang::EOpConvUintToFloat16:
4594 case glslang::EOpConvUint64ToFloat16:
4595#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004596 convOp = spv::OpConvertUToF;
4597 break;
4598
4599 case glslang::EOpConvDoubleToFloat:
4600 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004601#ifdef AMD_EXTENSIONS
4602 case glslang::EOpConvDoubleToFloat16:
4603 case glslang::EOpConvFloat16ToDouble:
4604 case glslang::EOpConvFloatToFloat16:
4605 case glslang::EOpConvFloat16ToFloat:
4606#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004607 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004608 if (builder.isMatrixType(destType))
4609 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004610 break;
4611
4612 case glslang::EOpConvFloatToInt:
4613 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004614 case glslang::EOpConvFloatToInt64:
4615 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004616#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004617 case glslang::EOpConvFloatToInt16:
4618 case glslang::EOpConvDoubleToInt16:
4619 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004620 case glslang::EOpConvFloat16ToInt:
4621 case glslang::EOpConvFloat16ToInt64:
4622#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004623 convOp = spv::OpConvertFToS;
4624 break;
4625
4626 case glslang::EOpConvUintToInt:
4627 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004628 case glslang::EOpConvUint64ToInt64:
4629 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004630#ifdef AMD_EXTENSIONS
4631 case glslang::EOpConvUint16ToInt16:
4632 case glslang::EOpConvInt16ToUint16:
4633#endif
qininge24aa5e2016-04-07 15:40:27 -04004634 if (builder.isInSpecConstCodeGenMode()) {
4635 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004636 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4637 zero = builder.makeUint64Constant(0);
4638#ifdef AMD_EXTENSIONS
4639 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4640 zero = builder.makeUint16Constant(0);
4641#endif
4642 else
4643 zero = builder.makeUintConstant(0);
4644
qining189b2032016-04-12 23:16:20 -04004645 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004646 // Use OpIAdd, instead of OpBitcast to do the conversion when
4647 // generating for OpSpecConstantOp instruction.
4648 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4649 }
4650 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004651 convOp = spv::OpBitcast;
4652 break;
4653
4654 case glslang::EOpConvFloatToUint:
4655 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004656 case glslang::EOpConvFloatToUint64:
4657 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004658#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004659 case glslang::EOpConvFloatToUint16:
4660 case glslang::EOpConvDoubleToUint16:
4661 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004662 case glslang::EOpConvFloat16ToUint:
4663 case glslang::EOpConvFloat16ToUint64:
4664#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004665 convOp = spv::OpConvertFToU;
4666 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004667
4668 case glslang::EOpConvIntToInt64:
4669 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004670#ifdef AMD_EXTENSIONS
4671 case glslang::EOpConvIntToInt16:
4672 case glslang::EOpConvInt16ToInt:
4673 case glslang::EOpConvInt64ToInt16:
4674 case glslang::EOpConvInt16ToInt64:
4675#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004676 convOp = spv::OpSConvert;
4677 break;
4678
4679 case glslang::EOpConvUintToUint64:
4680 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004681#ifdef AMD_EXTENSIONS
4682 case glslang::EOpConvUintToUint16:
4683 case glslang::EOpConvUint16ToUint:
4684 case glslang::EOpConvUint64ToUint16:
4685 case glslang::EOpConvUint16ToUint64:
4686#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004687 convOp = spv::OpUConvert;
4688 break;
4689
4690 case glslang::EOpConvIntToUint64:
4691 case glslang::EOpConvInt64ToUint:
4692 case glslang::EOpConvUint64ToInt:
4693 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004694#ifdef AMD_EXTENSIONS
4695 case glslang::EOpConvInt16ToUint:
4696 case glslang::EOpConvUintToInt16:
4697 case glslang::EOpConvInt16ToUint64:
4698 case glslang::EOpConvUint64ToInt16:
4699 case glslang::EOpConvUint16ToInt:
4700 case glslang::EOpConvIntToUint16:
4701 case glslang::EOpConvUint16ToInt64:
4702 case glslang::EOpConvInt64ToUint16:
4703#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004704 // OpSConvert/OpUConvert + OpBitCast
4705 switch (op) {
4706 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004707#ifdef AMD_EXTENSIONS
4708 case glslang::EOpConvInt16ToUint64:
4709#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004710 convOp = spv::OpSConvert;
4711 type = builder.makeIntType(64);
4712 break;
4713 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004714#ifdef AMD_EXTENSIONS
4715 case glslang::EOpConvInt16ToUint:
4716#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004717 convOp = spv::OpSConvert;
4718 type = builder.makeIntType(32);
4719 break;
4720 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004721#ifdef AMD_EXTENSIONS
4722 case glslang::EOpConvUint16ToInt:
4723#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004724 convOp = spv::OpUConvert;
4725 type = builder.makeUintType(32);
4726 break;
4727 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004728#ifdef AMD_EXTENSIONS
4729 case glslang::EOpConvUint16ToInt64:
4730#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004731 convOp = spv::OpUConvert;
4732 type = builder.makeUintType(64);
4733 break;
Rex Xucabbb782017-03-24 13:41:14 +08004734#ifdef AMD_EXTENSIONS
4735 case glslang::EOpConvUintToInt16:
4736 case glslang::EOpConvUint64ToInt16:
4737 convOp = spv::OpUConvert;
4738 type = builder.makeUintType(16);
4739 break;
4740 case glslang::EOpConvIntToUint16:
4741 case glslang::EOpConvInt64ToUint16:
4742 convOp = spv::OpSConvert;
4743 type = builder.makeIntType(16);
4744 break;
4745#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004746 default:
4747 assert(0);
4748 break;
4749 }
4750
4751 if (vectorSize > 0)
4752 type = builder.makeVectorType(type, vectorSize);
4753
4754 operand = builder.createUnaryOp(convOp, type, operand);
4755
4756 if (builder.isInSpecConstCodeGenMode()) {
4757 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004758#ifdef AMD_EXTENSIONS
4759 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4760 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4761 zero = builder.makeUint64Constant(0);
4762 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4763 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4764 zero = builder.makeUint16Constant(0);
4765 else
4766 zero = builder.makeUintConstant(0);
4767#else
4768 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4769 zero = builder.makeUint64Constant(0);
4770 else
4771 zero = builder.makeUintConstant(0);
4772#endif
4773
Rex Xu8ff43de2016-04-22 16:51:45 +08004774 zero = makeSmearedConstant(zero, vectorSize);
4775 // Use OpIAdd, instead of OpBitcast to do the conversion when
4776 // generating for OpSpecConstantOp instruction.
4777 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4778 }
4779 // For normal run-time conversion instruction, use OpBitcast.
4780 convOp = spv::OpBitcast;
4781 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004782 default:
4783 break;
4784 }
4785
4786 spv::Id result = 0;
4787 if (convOp == spv::OpNop)
4788 return result;
4789
4790 if (convOp == spv::OpSelect) {
4791 zero = makeSmearedConstant(zero, vectorSize);
4792 one = makeSmearedConstant(one, vectorSize);
4793 result = builder.createTriOp(convOp, destType, operand, one, zero);
4794 } else
4795 result = builder.createUnaryOp(convOp, destType, operand);
4796
John Kessenich32cfd492016-02-02 12:37:46 -07004797 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004798}
4799
4800spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4801{
4802 if (vectorSize == 0)
4803 return constant;
4804
4805 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4806 std::vector<spv::Id> components;
4807 for (int c = 0; c < vectorSize; ++c)
4808 components.push_back(constant);
4809 return builder.makeCompositeConstant(vectorTypeId, components);
4810}
4811
John Kessenich426394d2015-07-23 10:22:48 -06004812// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004813spv::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 -06004814{
4815 spv::Op opCode = spv::OpNop;
4816
4817 switch (op) {
4818 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004819 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004820 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004821 opCode = spv::OpAtomicIAdd;
4822 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004823 case glslang::EOpAtomicCounterSubtract:
4824 opCode = spv::OpAtomicISub;
4825 break;
John Kessenich426394d2015-07-23 10:22:48 -06004826 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004827 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004828 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004829 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004830 break;
4831 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004832 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004833 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004834 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004835 break;
4836 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004837 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004838 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004839 opCode = spv::OpAtomicAnd;
4840 break;
4841 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004842 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004843 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004844 opCode = spv::OpAtomicOr;
4845 break;
4846 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004847 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004848 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004849 opCode = spv::OpAtomicXor;
4850 break;
4851 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004852 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004853 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004854 opCode = spv::OpAtomicExchange;
4855 break;
4856 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004857 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004858 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004859 opCode = spv::OpAtomicCompareExchange;
4860 break;
4861 case glslang::EOpAtomicCounterIncrement:
4862 opCode = spv::OpAtomicIIncrement;
4863 break;
4864 case glslang::EOpAtomicCounterDecrement:
4865 opCode = spv::OpAtomicIDecrement;
4866 break;
4867 case glslang::EOpAtomicCounter:
4868 opCode = spv::OpAtomicLoad;
4869 break;
4870 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004871 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004872 break;
4873 }
4874
Rex Xue8fe8b02017-09-26 15:42:56 +08004875 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4876 builder.addCapability(spv::CapabilityInt64Atomics);
4877
John Kessenich426394d2015-07-23 10:22:48 -06004878 // Sort out the operands
4879 // - mapping from glslang -> SPV
4880 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004881 // - compare-exchange swaps the value and comparator
4882 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004883 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004884 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4885 auto opIt = operands.begin(); // walk the glslang operands
4886 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004887 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4888 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4889 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004890 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4891 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004892 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004893 spvAtomicOperands.push_back(*(opIt + 1));
4894 spvAtomicOperands.push_back(*opIt);
4895 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004896 }
John Kessenich426394d2015-07-23 10:22:48 -06004897
John Kessenich3e60a6f2015-09-14 22:45:16 -06004898 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004899 for (; opIt != operands.end(); ++opIt)
4900 spvAtomicOperands.push_back(*opIt);
4901
John Kessenich48d6e792017-10-06 21:21:48 -06004902 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4903
4904 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4905 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4906 if (op == glslang::EOpAtomicCounterDecrement)
4907 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4908
4909 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004910}
4911
John Kessenich91cef522016-05-05 16:45:40 -06004912// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004913spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004914{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004915#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004916 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004917 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004918#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004919
Rex Xu51596642016-09-21 18:56:12 +08004920 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004921 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004922 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4923
chaocf200da82016-12-20 12:44:35 -08004924 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4925 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004926 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4927 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004928 } else if (op == glslang::EOpAnyInvocation ||
4929 op == glslang::EOpAllInvocations ||
4930 op == glslang::EOpAllInvocationsEqual) {
4931 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4932 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004933 } else {
4934 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004935#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004936 if (op == glslang::EOpMinInvocationsNonUniform ||
4937 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004938 op == glslang::EOpAddInvocationsNonUniform ||
4939 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4940 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4941 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4942 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4943 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4944 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004945 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004946#endif
Rex Xu51596642016-09-21 18:56:12 +08004947
4948 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004949#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004950 switch (op) {
4951 case glslang::EOpMinInvocations:
4952 case glslang::EOpMaxInvocations:
4953 case glslang::EOpAddInvocations:
4954 case glslang::EOpMinInvocationsNonUniform:
4955 case glslang::EOpMaxInvocationsNonUniform:
4956 case glslang::EOpAddInvocationsNonUniform:
4957 groupOperation = spv::GroupOperationReduce;
4958 spvGroupOperands.push_back(groupOperation);
4959 break;
4960 case glslang::EOpMinInvocationsInclusiveScan:
4961 case glslang::EOpMaxInvocationsInclusiveScan:
4962 case glslang::EOpAddInvocationsInclusiveScan:
4963 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4964 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4965 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4966 groupOperation = spv::GroupOperationInclusiveScan;
4967 spvGroupOperands.push_back(groupOperation);
4968 break;
4969 case glslang::EOpMinInvocationsExclusiveScan:
4970 case glslang::EOpMaxInvocationsExclusiveScan:
4971 case glslang::EOpAddInvocationsExclusiveScan:
4972 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4973 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4974 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4975 groupOperation = spv::GroupOperationExclusiveScan;
4976 spvGroupOperands.push_back(groupOperation);
4977 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004978 default:
4979 break;
Rex Xu430ef402016-10-14 17:22:23 +08004980 }
Rex Xu9d93a232016-05-05 12:30:44 +08004981#endif
Rex Xu51596642016-09-21 18:56:12 +08004982 }
4983
4984 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4985 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004986
4987 switch (op) {
4988 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004989 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004990 break;
John Kessenich91cef522016-05-05 16:45:40 -06004991 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004992 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004993 break;
John Kessenich91cef522016-05-05 16:45:40 -06004994 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004995 opCode = spv::OpSubgroupAllEqualKHR;
4996 break;
Rex Xu51596642016-09-21 18:56:12 +08004997 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004998 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004999 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005000 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005001 break;
5002 case glslang::EOpReadFirstInvocation:
5003 opCode = spv::OpSubgroupFirstInvocationKHR;
5004 break;
5005 case glslang::EOpBallot:
5006 {
5007 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5008 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5009 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5010 //
5011 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5012 //
5013 spv::Id uintType = builder.makeUintType(32);
5014 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5015 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5016
5017 std::vector<spv::Id> components;
5018 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5019 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5020
5021 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5022 return builder.createUnaryOp(spv::OpBitcast, typeId,
5023 builder.createCompositeConstruct(uvec2Type, components));
5024 }
5025
Rex Xu9d93a232016-05-05 12:30:44 +08005026#ifdef AMD_EXTENSIONS
5027 case glslang::EOpMinInvocations:
5028 case glslang::EOpMaxInvocations:
5029 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005030 case glslang::EOpMinInvocationsInclusiveScan:
5031 case glslang::EOpMaxInvocationsInclusiveScan:
5032 case glslang::EOpAddInvocationsInclusiveScan:
5033 case glslang::EOpMinInvocationsExclusiveScan:
5034 case glslang::EOpMaxInvocationsExclusiveScan:
5035 case glslang::EOpAddInvocationsExclusiveScan:
5036 if (op == glslang::EOpMinInvocations ||
5037 op == glslang::EOpMinInvocationsInclusiveScan ||
5038 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005039 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005040 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005041 else {
5042 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005043 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005044 else
Rex Xu51596642016-09-21 18:56:12 +08005045 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005046 }
Rex Xu430ef402016-10-14 17:22:23 +08005047 } else if (op == glslang::EOpMaxInvocations ||
5048 op == glslang::EOpMaxInvocationsInclusiveScan ||
5049 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005050 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005051 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005052 else {
5053 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005054 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005055 else
Rex Xu51596642016-09-21 18:56:12 +08005056 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005057 }
5058 } else {
5059 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005060 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005061 else
Rex Xu51596642016-09-21 18:56:12 +08005062 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005063 }
5064
Rex Xu2bbbe062016-08-23 15:41:05 +08005065 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005066 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005067
5068 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005069 case glslang::EOpMinInvocationsNonUniform:
5070 case glslang::EOpMaxInvocationsNonUniform:
5071 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005072 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5073 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5074 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5075 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5076 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5077 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5078 if (op == glslang::EOpMinInvocationsNonUniform ||
5079 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5080 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005081 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005082 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005083 else {
5084 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005085 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005086 else
Rex Xu51596642016-09-21 18:56:12 +08005087 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005088 }
5089 }
Rex Xu430ef402016-10-14 17:22:23 +08005090 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5091 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5092 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005093 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005094 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005095 else {
5096 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005097 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005098 else
Rex Xu51596642016-09-21 18:56:12 +08005099 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005100 }
5101 }
5102 else {
5103 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005104 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005105 else
Rex Xu51596642016-09-21 18:56:12 +08005106 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005107 }
5108
Rex Xu2bbbe062016-08-23 15:41:05 +08005109 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005110 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005111
5112 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005113#endif
John Kessenich91cef522016-05-05 16:45:40 -06005114 default:
5115 logger->missingFunctionality("invocation operation");
5116 return spv::NoResult;
5117 }
Rex Xu51596642016-09-21 18:56:12 +08005118
5119 assert(opCode != spv::OpNop);
5120 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005121}
5122
Rex Xu2bbbe062016-08-23 15:41:05 +08005123// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005124spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005125{
Rex Xub7072052016-09-26 15:53:40 +08005126#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005127 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5128 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005129 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005130 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005131 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5132 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5133 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005134#else
5135 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5136 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005137 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5138 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005139#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005140
5141 // Handle group invocation operations scalar by scalar.
5142 // The result type is the same type as the original type.
5143 // The algorithm is to:
5144 // - break the vector into scalars
5145 // - apply the operation to each scalar
5146 // - make a vector out the scalar results
5147
5148 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005149 int numComponents = builder.getNumComponents(operands[0]);
5150 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005151 std::vector<spv::Id> results;
5152
5153 // do each scalar op
5154 for (int comp = 0; comp < numComponents; ++comp) {
5155 std::vector<unsigned int> indexes;
5156 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005157 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005158 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005159 if (op == spv::OpSubgroupReadInvocationKHR) {
5160 spvGroupOperands.push_back(scalar);
5161 spvGroupOperands.push_back(operands[1]);
5162 } else if (op == spv::OpGroupBroadcast) {
5163 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005164 spvGroupOperands.push_back(scalar);
5165 spvGroupOperands.push_back(operands[1]);
5166 } else {
chaocf200da82016-12-20 12:44:35 -08005167 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005168 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005169 spvGroupOperands.push_back(scalar);
5170 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005171
Rex Xub7072052016-09-26 15:53:40 +08005172 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005173 }
5174
5175 // put the pieces together
5176 return builder.createCompositeConstruct(typeId, results);
5177}
Rex Xu2bbbe062016-08-23 15:41:05 +08005178
John Kessenich5e4b1242015-08-06 22:53:06 -06005179spv::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 -06005180{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005181#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005182 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005183 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5184#else
Rex Xucabbb782017-03-24 13:41:14 +08005185 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005186 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005187#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005188
John Kessenich140f3df2015-06-26 16:58:36 -06005189 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005190 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005191 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005192 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005193 spv::Id typeId0 = 0;
5194 if (consumedOperands > 0)
5195 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005196 spv::Id typeId1 = 0;
5197 if (consumedOperands > 1)
5198 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005199 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005200
5201 switch (op) {
5202 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005203 if (isFloat)
5204 libCall = spv::GLSLstd450FMin;
5205 else if (isUnsigned)
5206 libCall = spv::GLSLstd450UMin;
5207 else
5208 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005209 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 if (isFloat)
5216 libCall = spv::GLSLstd450FMax;
5217 else if (isUnsigned)
5218 libCall = spv::GLSLstd450UMax;
5219 else
5220 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005221 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
5223 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EOpDot:
5227 opCode = spv::OpDot;
5228 break;
5229 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005231 break;
5232
5233 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 if (isFloat)
5235 libCall = spv::GLSLstd450FClamp;
5236 else if (isUnsigned)
5237 libCall = spv::GLSLstd450UClamp;
5238 else
5239 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005240 builder.promoteScalar(precision, operands.front(), operands[1]);
5241 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005242 break;
5243 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005244 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5245 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005246 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005247 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005248 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005249 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005250 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005251 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005252 break;
5253 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005254 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005255 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005256 break;
5257 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005258 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005259 builder.promoteScalar(precision, operands[0], operands[2]);
5260 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005261 break;
5262
5263 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005264 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005265 break;
5266 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005267 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005268 break;
5269 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005270 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005273 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
5275 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005278 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005279 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005280 libCall = spv::GLSLstd450InterpolateAtSample;
5281 break;
5282 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005283 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005284 libCall = spv::GLSLstd450InterpolateAtOffset;
5285 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005286 case glslang::EOpAddCarry:
5287 opCode = spv::OpIAddCarry;
5288 typeId = builder.makeStructResultType(typeId0, typeId0);
5289 consumedOperands = 2;
5290 break;
5291 case glslang::EOpSubBorrow:
5292 opCode = spv::OpISubBorrow;
5293 typeId = builder.makeStructResultType(typeId0, typeId0);
5294 consumedOperands = 2;
5295 break;
5296 case glslang::EOpUMulExtended:
5297 opCode = spv::OpUMulExtended;
5298 typeId = builder.makeStructResultType(typeId0, typeId0);
5299 consumedOperands = 2;
5300 break;
5301 case glslang::EOpIMulExtended:
5302 opCode = spv::OpSMulExtended;
5303 typeId = builder.makeStructResultType(typeId0, typeId0);
5304 consumedOperands = 2;
5305 break;
5306 case glslang::EOpBitfieldExtract:
5307 if (isUnsigned)
5308 opCode = spv::OpBitFieldUExtract;
5309 else
5310 opCode = spv::OpBitFieldSExtract;
5311 break;
5312 case glslang::EOpBitfieldInsert:
5313 opCode = spv::OpBitFieldInsert;
5314 break;
5315
5316 case glslang::EOpFma:
5317 libCall = spv::GLSLstd450Fma;
5318 break;
5319 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005320 {
5321 libCall = spv::GLSLstd450FrexpStruct;
5322 assert(builder.isPointerType(typeId1));
5323 typeId1 = builder.getContainedTypeId(typeId1);
5324#ifdef AMD_EXTENSIONS
5325 int width = builder.getScalarTypeWidth(typeId1);
5326#else
5327 int width = 32;
5328#endif
5329 if (builder.getNumComponents(operands[0]) == 1)
5330 frexpIntType = builder.makeIntegerType(width, true);
5331 else
5332 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5333 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5334 consumedOperands = 1;
5335 }
John Kessenich55e7d112015-11-15 21:33:39 -07005336 break;
5337 case glslang::EOpLdexp:
5338 libCall = spv::GLSLstd450Ldexp;
5339 break;
5340
Rex Xu574ab042016-04-14 16:53:07 +08005341 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005342 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005343
Rex Xu9d93a232016-05-05 12:30:44 +08005344#ifdef AMD_EXTENSIONS
5345 case glslang::EOpSwizzleInvocations:
5346 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5347 libCall = spv::SwizzleInvocationsAMD;
5348 break;
5349 case glslang::EOpSwizzleInvocationsMasked:
5350 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5351 libCall = spv::SwizzleInvocationsMaskedAMD;
5352 break;
5353 case glslang::EOpWriteInvocation:
5354 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5355 libCall = spv::WriteInvocationAMD;
5356 break;
5357
5358 case glslang::EOpMin3:
5359 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5360 if (isFloat)
5361 libCall = spv::FMin3AMD;
5362 else {
5363 if (isUnsigned)
5364 libCall = spv::UMin3AMD;
5365 else
5366 libCall = spv::SMin3AMD;
5367 }
5368 break;
5369 case glslang::EOpMax3:
5370 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5371 if (isFloat)
5372 libCall = spv::FMax3AMD;
5373 else {
5374 if (isUnsigned)
5375 libCall = spv::UMax3AMD;
5376 else
5377 libCall = spv::SMax3AMD;
5378 }
5379 break;
5380 case glslang::EOpMid3:
5381 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5382 if (isFloat)
5383 libCall = spv::FMid3AMD;
5384 else {
5385 if (isUnsigned)
5386 libCall = spv::UMid3AMD;
5387 else
5388 libCall = spv::SMid3AMD;
5389 }
5390 break;
5391
5392 case glslang::EOpInterpolateAtVertex:
5393 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5394 libCall = spv::InterpolateAtVertexAMD;
5395 break;
5396#endif
5397
John Kessenich140f3df2015-06-26 16:58:36 -06005398 default:
5399 return 0;
5400 }
5401
5402 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005403 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005404 // Use an extended instruction from the standard library.
5405 // Construct the call arguments, without modifying the original operands vector.
5406 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5407 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005408 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005409 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005410 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005411 case 0:
5412 // should all be handled by visitAggregate and createNoArgOperation
5413 assert(0);
5414 return 0;
5415 case 1:
5416 // should all be handled by createUnaryOperation
5417 assert(0);
5418 return 0;
5419 case 2:
5420 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5421 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005422 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005423 // anything 3 or over doesn't have l-value operands, so all should be consumed
5424 assert(consumedOperands == operands.size());
5425 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005426 break;
5427 }
5428 }
5429
John Kessenich55e7d112015-11-15 21:33:39 -07005430 // Decode the return types that were structures
5431 switch (op) {
5432 case glslang::EOpAddCarry:
5433 case glslang::EOpSubBorrow:
5434 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5435 id = builder.createCompositeExtract(id, typeId0, 0);
5436 break;
5437 case glslang::EOpUMulExtended:
5438 case glslang::EOpIMulExtended:
5439 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5440 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5441 break;
5442 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005443 {
5444 assert(operands.size() == 2);
5445 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5446 // "exp" is floating-point type (from HLSL intrinsic)
5447 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5448 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5449 builder.createStore(member1, operands[1]);
5450 } else
5451 // "exp" is integer type (from GLSL built-in function)
5452 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5453 id = builder.createCompositeExtract(id, typeId0, 0);
5454 }
John Kessenich55e7d112015-11-15 21:33:39 -07005455 break;
5456 default:
5457 break;
5458 }
5459
John Kessenich32cfd492016-02-02 12:37:46 -07005460 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005461}
5462
Rex Xu9d93a232016-05-05 12:30:44 +08005463// Intrinsics with no arguments (or no return value, and no precision).
5464spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005465{
5466 // TODO: get the barrier operands correct
5467
5468 switch (op) {
5469 case glslang::EOpEmitVertex:
5470 builder.createNoResultOp(spv::OpEmitVertex);
5471 return 0;
5472 case glslang::EOpEndPrimitive:
5473 builder.createNoResultOp(spv::OpEndPrimitive);
5474 return 0;
5475 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005476 if (glslangIntermediate->getStage() == EShLangTessControl) {
5477 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5478 // TODO: prefer the following, when available:
5479 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5480 // spv::MemorySemanticsPatchMask |
5481 // spv::MemorySemanticsAcquireReleaseMask);
5482 } else {
5483 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5484 spv::MemorySemanticsWorkgroupMemoryMask |
5485 spv::MemorySemanticsAcquireReleaseMask);
5486 }
John Kessenich140f3df2015-06-26 16:58:36 -06005487 return 0;
5488 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005489 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5490 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005491 return 0;
5492 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005493 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5494 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005495 return 0;
5496 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005497 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5498 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005499 return 0;
5500 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005501 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5502 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005503 return 0;
5504 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005505 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5506 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005507 return 0;
5508 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005509 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5510 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005511 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005512 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005513 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005514 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005515 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005516 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005517 case glslang::EOpDeviceMemoryBarrier:
5518 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5519 spv::MemorySemanticsImageMemoryMask |
5520 spv::MemorySemanticsAcquireReleaseMask);
5521 return 0;
5522 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5523 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5524 spv::MemorySemanticsImageMemoryMask |
5525 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005526 return 0;
5527 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005528 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5529 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005530 return 0;
5531 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005532 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5533 spv::MemorySemanticsWorkgroupMemoryMask |
5534 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005535 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005536#ifdef AMD_EXTENSIONS
5537 case glslang::EOpTime:
5538 {
5539 std::vector<spv::Id> args; // Dummy arguments
5540 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5541 return builder.setPrecision(id, precision);
5542 }
5543#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005544 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005545 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005546 return 0;
5547 }
5548}
5549
5550spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5551{
John Kessenich2f273362015-07-18 22:34:27 -06005552 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005553 spv::Id id;
5554 if (symbolValues.end() != iter) {
5555 id = iter->second;
5556 return id;
5557 }
5558
5559 // it was not found, create it
5560 id = createSpvVariable(symbol);
5561 symbolValues[symbol->getId()] = id;
5562
Rex Xuc884b4a2016-06-29 15:03:44 +08005563 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005564 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005565 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005566 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005567 if (symbol->getType().getQualifier().hasSpecConstantId())
5568 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005569 if (symbol->getQualifier().hasIndex())
5570 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5571 if (symbol->getQualifier().hasComponent())
5572 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005573 // atomic counters use this:
5574 if (symbol->getQualifier().hasOffset())
5575 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005576 }
5577
scygan2c864272016-05-18 18:09:17 +02005578 if (symbol->getQualifier().hasLocation())
5579 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005580 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005581 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005582 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005583 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005584 }
John Kessenich140f3df2015-06-26 16:58:36 -06005585 if (symbol->getQualifier().hasSet())
5586 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005587 else if (IsDescriptorResource(symbol->getType())) {
5588 // default to 0
5589 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5590 }
John Kessenich140f3df2015-06-26 16:58:36 -06005591 if (symbol->getQualifier().hasBinding())
5592 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005593 if (symbol->getQualifier().hasAttachment())
5594 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005595 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005596 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005597 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005598 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005599 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005600 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005601 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5602 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5603 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5604 }
5605 if (symbol->getQualifier().hasXfbOffset())
5606 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005607 }
5608
Rex Xu1da878f2016-02-21 20:59:01 +08005609 if (symbol->getType().isImage()) {
5610 std::vector<spv::Decoration> memory;
5611 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5612 for (unsigned int i = 0; i < memory.size(); ++i)
5613 addDecoration(id, memory[i]);
5614 }
5615
John Kessenich140f3df2015-06-26 16:58:36 -06005616 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005617 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005618 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005619 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005620
John Kessenichecba76f2017-01-06 00:34:48 -07005621#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005622 if (builtIn == spv::BuiltInSampleMask) {
5623 spv::Decoration decoration;
5624 // GL_NV_sample_mask_override_coverage extension
5625 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005626 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005627 else
5628 decoration = (spv::Decoration)spv::DecorationMax;
5629 addDecoration(id, decoration);
5630 if (decoration != spv::DecorationMax) {
5631 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5632 }
5633 }
chaoc771d89f2017-01-13 01:10:53 -08005634 else if (builtIn == spv::BuiltInLayer) {
5635 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005636 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005637 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5638 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5639 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5640 }
John Kessenichb41bff62017-08-11 13:07:17 -06005641 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005642 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5643 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5644 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5645 }
5646 }
5647
chaoc6e5acae2016-12-20 13:28:52 -08005648 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005649 addDecoration(id, spv::DecorationPassthroughNV);
5650 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005651 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5652 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005653#endif
5654
John Kessenich140f3df2015-06-26 16:58:36 -06005655 return id;
5656}
5657
John Kessenich55e7d112015-11-15 21:33:39 -07005658// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005659void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5660{
John Kessenich4016e382016-07-15 11:53:56 -06005661 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005662 builder.addDecoration(id, dec);
5663}
5664
John Kessenich55e7d112015-11-15 21:33:39 -07005665// If 'dec' is valid, add a one-operand decoration to an object
5666void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5667{
John Kessenich4016e382016-07-15 11:53:56 -06005668 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005669 builder.addDecoration(id, dec, value);
5670}
5671
5672// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005673void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5674{
John Kessenich4016e382016-07-15 11:53:56 -06005675 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005676 builder.addMemberDecoration(id, (unsigned)member, dec);
5677}
5678
John Kessenich92187592016-02-01 13:45:25 -07005679// If 'dec' is valid, add a one-operand decoration to a struct member
5680void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5681{
John Kessenich4016e382016-07-15 11:53:56 -06005682 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005683 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5684}
5685
John Kessenich55e7d112015-11-15 21:33:39 -07005686// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005687// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005688//
5689// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5690//
5691// Recursively walk the nodes. The nodes form a tree whose leaves are
5692// regular constants, which themselves are trees that createSpvConstant()
5693// recursively walks. So, this function walks the "top" of the tree:
5694// - emit specialization constant-building instructions for specConstant
5695// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005696spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005697{
John Kessenich7cc0e282016-03-20 00:46:02 -06005698 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005699
qining4f4bb812016-04-03 23:55:17 -04005700 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005701 if (! node.getQualifier().specConstant) {
5702 // hand off to the non-spec-constant path
5703 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5704 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005705 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005706 nextConst, false);
5707 }
5708
5709 // We now know we have a specialization constant to build
5710
John Kessenichd94c0032016-05-30 19:29:40 -06005711 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005712 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5713 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5714 std::vector<spv::Id> dimConstId;
5715 for (int dim = 0; dim < 3; ++dim) {
5716 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5717 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5718 if (specConst)
5719 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5720 }
5721 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5722 }
5723
5724 // An AST node labelled as specialization constant should be a symbol node.
5725 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5726 if (auto* sn = node.getAsSymbolNode()) {
5727 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005728 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5729 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5730 // will set the builder into spec constant op instruction generating mode.
5731 sub_tree->traverse(this);
5732 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005733 } else if (auto* const_union_array = &sn->getConstArray()){
5734 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005735 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5736 builder.addName(id, sn->getName().c_str());
5737 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005738 }
5739 }
qining4f4bb812016-04-03 23:55:17 -04005740
5741 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5742 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005743 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005744 exit(1);
5745 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005746}
5747
John Kessenich140f3df2015-06-26 16:58:36 -06005748// Use 'consts' as the flattened glslang source of scalar constants to recursively
5749// build the aggregate SPIR-V constant.
5750//
5751// If there are not enough elements present in 'consts', 0 will be substituted;
5752// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5753//
qining08408382016-03-21 09:51:37 -04005754spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005755{
5756 // vector of constants for SPIR-V
5757 std::vector<spv::Id> spvConsts;
5758
5759 // Type is used for struct and array constants
5760 spv::Id typeId = convertGlslangToSpvType(glslangType);
5761
5762 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005763 glslang::TType elementType(glslangType, 0);
5764 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005765 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005766 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005767 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005768 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005769 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005770 } else if (glslangType.getStruct()) {
5771 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5772 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005773 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005774 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005775 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5776 bool zero = nextConst >= consts.size();
5777 switch (glslangType.getBasicType()) {
5778 case glslang::EbtInt:
5779 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5780 break;
5781 case glslang::EbtUint:
5782 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5783 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005784 case glslang::EbtInt64:
5785 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5786 break;
5787 case glslang::EbtUint64:
5788 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5789 break;
Rex Xucabbb782017-03-24 13:41:14 +08005790#ifdef AMD_EXTENSIONS
5791 case glslang::EbtInt16:
5792 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5793 break;
5794 case glslang::EbtUint16:
5795 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5796 break;
5797#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005798 case glslang::EbtFloat:
5799 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5800 break;
5801 case glslang::EbtDouble:
5802 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5803 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005804#ifdef AMD_EXTENSIONS
5805 case glslang::EbtFloat16:
5806 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5807 break;
5808#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005809 case glslang::EbtBool:
5810 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5811 break;
5812 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005813 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005814 break;
5815 }
5816 ++nextConst;
5817 }
5818 } else {
5819 // we have a non-aggregate (scalar) constant
5820 bool zero = nextConst >= consts.size();
5821 spv::Id scalar = 0;
5822 switch (glslangType.getBasicType()) {
5823 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005824 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005827 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005829 case glslang::EbtInt64:
5830 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5831 break;
5832 case glslang::EbtUint64:
5833 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5834 break;
Rex Xucabbb782017-03-24 13:41:14 +08005835#ifdef AMD_EXTENSIONS
5836 case glslang::EbtInt16:
5837 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5838 break;
5839 case glslang::EbtUint16:
5840 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5841 break;
5842#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005843 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005844 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005847 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005849#ifdef AMD_EXTENSIONS
5850 case glslang::EbtFloat16:
5851 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5852 break;
5853#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005854 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005855 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005858 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860 }
5861 ++nextConst;
5862 return scalar;
5863 }
5864
5865 return builder.makeCompositeConstant(typeId, spvConsts);
5866}
5867
John Kessenich7c1aa102015-10-15 13:29:11 -06005868// Return true if the node is a constant or symbol whose reading has no
5869// non-trivial observable cost or effect.
5870bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5871{
5872 // don't know what this is
5873 if (node == nullptr)
5874 return false;
5875
5876 // a constant is safe
5877 if (node->getAsConstantUnion() != nullptr)
5878 return true;
5879
5880 // not a symbol means non-trivial
5881 if (node->getAsSymbolNode() == nullptr)
5882 return false;
5883
5884 // a symbol, depends on what's being read
5885 switch (node->getType().getQualifier().storage) {
5886 case glslang::EvqTemporary:
5887 case glslang::EvqGlobal:
5888 case glslang::EvqIn:
5889 case glslang::EvqInOut:
5890 case glslang::EvqConst:
5891 case glslang::EvqConstReadOnly:
5892 case glslang::EvqUniform:
5893 return true;
5894 default:
5895 return false;
5896 }
qining25262b32016-05-06 17:25:16 -04005897}
John Kessenich7c1aa102015-10-15 13:29:11 -06005898
5899// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005900// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005901// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005902// Return true if trivial.
5903bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5904{
5905 if (node == nullptr)
5906 return false;
5907
John Kessenich84cc15f2017-05-24 16:44:47 -06005908 // count non scalars as trivial, as well as anything coming from HLSL
5909 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005910 return true;
5911
John Kessenich7c1aa102015-10-15 13:29:11 -06005912 // symbols and constants are trivial
5913 if (isTrivialLeaf(node))
5914 return true;
5915
5916 // otherwise, it needs to be a simple operation or one or two leaf nodes
5917
5918 // not a simple operation
5919 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5920 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5921 if (binaryNode == nullptr && unaryNode == nullptr)
5922 return false;
5923
5924 // not on leaf nodes
5925 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5926 return false;
5927
5928 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5929 return false;
5930 }
5931
5932 switch (node->getAsOperator()->getOp()) {
5933 case glslang::EOpLogicalNot:
5934 case glslang::EOpConvIntToBool:
5935 case glslang::EOpConvUintToBool:
5936 case glslang::EOpConvFloatToBool:
5937 case glslang::EOpConvDoubleToBool:
5938 case glslang::EOpEqual:
5939 case glslang::EOpNotEqual:
5940 case glslang::EOpLessThan:
5941 case glslang::EOpGreaterThan:
5942 case glslang::EOpLessThanEqual:
5943 case glslang::EOpGreaterThanEqual:
5944 case glslang::EOpIndexDirect:
5945 case glslang::EOpIndexDirectStruct:
5946 case glslang::EOpLogicalXor:
5947 case glslang::EOpAny:
5948 case glslang::EOpAll:
5949 return true;
5950 default:
5951 return false;
5952 }
5953}
5954
5955// Emit short-circuiting code, where 'right' is never evaluated unless
5956// the left side is true (for &&) or false (for ||).
5957spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5958{
5959 spv::Id boolTypeId = builder.makeBoolType();
5960
5961 // emit left operand
5962 builder.clearAccessChain();
5963 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005964 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005965
5966 // Operands to accumulate OpPhi operands
5967 std::vector<spv::Id> phiOperands;
5968 // accumulate left operand's phi information
5969 phiOperands.push_back(leftId);
5970 phiOperands.push_back(builder.getBuildPoint()->getId());
5971
5972 // Make the two kinds of operation symmetric with a "!"
5973 // || => emit "if (! left) result = right"
5974 // && => emit "if ( left) result = right"
5975 //
5976 // TODO: this runtime "not" for || could be avoided by adding functionality
5977 // to 'builder' to have an "else" without an "then"
5978 if (op == glslang::EOpLogicalOr)
5979 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5980
5981 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005982 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005983
5984 // emit right operand as the "then" part of the "if"
5985 builder.clearAccessChain();
5986 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005987 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005988
5989 // accumulate left operand's phi information
5990 phiOperands.push_back(rightId);
5991 phiOperands.push_back(builder.getBuildPoint()->getId());
5992
5993 // finish the "if"
5994 ifBuilder.makeEndIf();
5995
5996 // phi together the two results
5997 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5998}
5999
Frank Henigman541f7bb2018-01-16 00:18:26 -05006000#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006001// Return type Id of the imported set of extended instructions corresponds to the name.
6002// Import this set if it has not been imported yet.
6003spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6004{
6005 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6006 return extBuiltinMap[name];
6007 else {
Rex Xu51596642016-09-21 18:56:12 +08006008 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006009 spv::Id extBuiltins = builder.import(name);
6010 extBuiltinMap[name] = extBuiltins;
6011 return extBuiltins;
6012 }
6013}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006014#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006015
John Kessenich140f3df2015-06-26 16:58:36 -06006016}; // end anonymous namespace
6017
6018namespace glslang {
6019
John Kessenich68d78fd2015-07-12 19:28:10 -06006020void GetSpirvVersion(std::string& version)
6021{
John Kessenich9e55f632015-07-15 10:03:39 -06006022 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006023 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006024 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006025 version = buf;
6026}
6027
John Kessenicha372a3e2017-11-02 22:32:14 -06006028// For low-order part of the generator's magic number. Bump up
6029// when there is a change in the style (e.g., if SSA form changes,
6030// or a different instruction sequence to do something gets used).
6031int GetSpirvGeneratorVersion()
6032{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006033 // return 1; // start
6034 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006035 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
6036 return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenicha372a3e2017-11-02 22:32:14 -06006037}
6038
John Kessenich140f3df2015-06-26 16:58:36 -06006039// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006040void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006041{
6042 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006043 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006044 if (out.fail())
6045 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006046 for (int i = 0; i < (int)spirv.size(); ++i) {
6047 unsigned int word = spirv[i];
6048 out.write((const char*)&word, 4);
6049 }
6050 out.close();
6051}
6052
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006053// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006054void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006055{
6056 std::ofstream out;
6057 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006058 if (out.fail())
6059 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006060 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006061 if (varName != nullptr) {
6062 out << "\t #pragma once" << std::endl;
6063 out << "const uint32_t " << varName << "[] = {" << std::endl;
6064 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006065 const int WORDS_PER_LINE = 8;
6066 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6067 out << "\t";
6068 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6069 const unsigned int word = spirv[i + j];
6070 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6071 if (i + j + 1 < (int)spirv.size()) {
6072 out << ",";
6073 }
6074 }
6075 out << std::endl;
6076 }
Flavio15017db2017-02-15 14:29:33 -08006077 if (varName != nullptr) {
6078 out << "};";
6079 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006080 out.close();
6081}
6082
GregFcd1f1692017-09-21 18:40:22 -06006083#ifdef ENABLE_OPT
6084void errHandler(const std::string& str) {
6085 std::cerr << str << std::endl;
6086}
6087#endif
6088
John Kessenich140f3df2015-06-26 16:58:36 -06006089//
6090// Set up the glslang traversal
6091//
John Kessenich121853f2017-05-31 17:11:16 -06006092void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006093{
Lei Zhang17535f72016-05-04 15:55:59 -04006094 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006095 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006096}
6097
John Kessenich121853f2017-05-31 17:11:16 -06006098void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6099 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006100{
John Kessenich140f3df2015-06-26 16:58:36 -06006101 TIntermNode* root = intermediate.getTreeRoot();
6102
6103 if (root == 0)
6104 return;
6105
John Kessenich121853f2017-05-31 17:11:16 -06006106 glslang::SpvOptions defaultOptions;
6107 if (options == nullptr)
6108 options = &defaultOptions;
6109
John Kessenich140f3df2015-06-26 16:58:36 -06006110 glslang::GetThreadPoolAllocator().push();
6111
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006112 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006113 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006114 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006115 it.dumpSpv(spirv);
6116
GregFcd1f1692017-09-21 18:40:22 -06006117#ifdef ENABLE_OPT
6118 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6119 // eg. forward and remove memory writes of opaque types.
6120 if ((intermediate.getSource() == EShSourceHlsl ||
6121 options->optimizeSize) &&
6122 !options->disableOptimizer) {
6123 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6124
6125 spvtools::Optimizer optimizer(target_env);
6126 optimizer.SetMessageConsumer([](spv_message_level_t level,
6127 const char* source,
6128 const spv_position_t& position,
6129 const char* message) {
6130 std::cerr << StringifyMessage(level, source, position, message)
6131 << std::endl;
6132 });
6133
6134 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006135 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6136 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006137 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6138 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6139 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6140 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006141 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006142 optimizer.RegisterPass(CreateAggressiveDCEPass());
6143 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006144 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006145 optimizer.RegisterPass(CreateBlockMergePass());
6146 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6147 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006148 optimizer.RegisterPass(CreateDeadInsertElimPass());
6149 if (options->optimizeSize) {
6150 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6151 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6152 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6153 }
GregFcd1f1692017-09-21 18:40:22 -06006154 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006155
6156 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6157 return;
6158
6159 // Remove dead module-level objects: functions, types, vars
6160 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6161 spv::spirvbin_t Remapper(0);
6162 Remapper.registerErrorHandler(errHandler);
6163 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6164 }
6165#endif
6166
John Kessenich140f3df2015-06-26 16:58:36 -06006167 glslang::GetThreadPoolAllocator().pop();
6168}
6169
6170}; // end namespace glslang