blob: b7b6597dc563d7b1f0b73a421dd6b817b1f7e48f [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;
134 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&) 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
770spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode) const
771{
772 spv::LoopControlMask control = spv::LoopControlMaskNone;
773
774 if (loopNode.getDontUnroll())
775 control = control | spv::LoopControlDontUnrollMask;
776 if (loopNode.getUnroll())
777 control = control | spv::LoopControlUnrollMask;
778
779 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600780}
781
John Kessenicha5c5fb62017-05-05 05:09:58 -0600782// Translate glslang type to SPIR-V storage class.
783spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
784{
785 if (type.getQualifier().isPipeInput())
786 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600787 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600788 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600789
790 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
791 type.getQualifier().storage == glslang::EvqUniform) {
792 if (type.getBasicType() == glslang::EbtAtomicUint)
793 return spv::StorageClassAtomicCounter;
794 if (type.containsOpaque())
795 return spv::StorageClassUniformConstant;
796 }
797
798 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600799 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
800 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600801 }
802
803 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600804 if (type.getQualifier().layoutPushConstant)
805 return spv::StorageClassPushConstant;
806 if (type.getBasicType() == glslang::EbtBlock)
807 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600808 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600809 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600810
811 switch (type.getQualifier().storage) {
812 case glslang::EvqShared: return spv::StorageClassWorkgroup;
813 case glslang::EvqGlobal: return spv::StorageClassPrivate;
814 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
815 case glslang::EvqTemporary: return spv::StorageClassFunction;
816 default:
817 assert(0);
818 break;
819 }
820
821 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600822}
823
qining25262b32016-05-06 17:25:16 -0400824// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700825// descriptor set.
826bool IsDescriptorResource(const glslang::TType& type)
827{
John Kessenichf7497e22016-03-08 21:36:22 -0700828 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700829 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700830 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700831
832 // non block...
833 // basically samplerXXX/subpass/sampler/texture are all included
834 // if they are the global-scope-class, not the function parameter
835 // (or local, if they ever exist) class.
836 if (type.getBasicType() == glslang::EbtSampler)
837 return type.getQualifier().isUniformOrBuffer();
838
839 // None of the above.
840 return false;
841}
842
John Kesseniche0b6cad2015-12-24 10:30:13 -0700843void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
844{
845 if (child.layoutMatrix == glslang::ElmNone)
846 child.layoutMatrix = parent.layoutMatrix;
847
848 if (parent.invariant)
849 child.invariant = true;
850 if (parent.nopersp)
851 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800852#ifdef AMD_EXTENSIONS
853 if (parent.explicitInterp)
854 child.explicitInterp = true;
855#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700856 if (parent.flat)
857 child.flat = true;
858 if (parent.centroid)
859 child.centroid = true;
860 if (parent.patch)
861 child.patch = true;
862 if (parent.sample)
863 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800864 if (parent.coherent)
865 child.coherent = true;
866 if (parent.volatil)
867 child.volatil = true;
868 if (parent.restrict)
869 child.restrict = true;
870 if (parent.readonly)
871 child.readonly = true;
872 if (parent.writeonly)
873 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700874}
875
John Kessenichf2b7f332016-09-01 17:05:23 -0600876bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700877{
John Kessenich7b9fa252016-01-21 18:56:57 -0700878 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600879 // - struct members might inherit from a struct declaration
880 // (note that non-block structs don't explicitly inherit,
881 // only implicitly, meaning no decoration involved)
882 // - affect decorations on the struct members
883 // (note smooth does not, and expecting something like volatile
884 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700885 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600886 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700887}
888
John Kessenich140f3df2015-06-26 16:58:36 -0600889//
890// Implement the TGlslangToSpvTraverser class.
891//
892
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700893TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600894 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
895 : TIntermTraverser(true, false, true),
896 options(options),
897 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600898 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700899 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700900 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600901 glslangIntermediate(glslangIntermediate)
902{
903 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
904
905 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600906 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
907 glslangIntermediate->getVersion());
908
John Kessenich121853f2017-05-31 17:11:16 -0600909 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600910 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600911 builder.setSourceFile(glslangIntermediate->getSourceFile());
912
913 // Set the source shader's text. If for SPV version 1.0, include
914 // a preamble in comments stating the OpModuleProcessed instructions.
915 // Otherwise, emit those as actual instructions.
916 std::string text;
917 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
918 for (int p = 0; p < (int)processes.size(); ++p) {
919 if (glslangIntermediate->getSpv().spv < 0x00010100) {
920 text.append("// OpModuleProcessed ");
921 text.append(processes[p]);
922 text.append("\n");
923 } else
924 builder.addModuleProcessed(processes[p]);
925 }
926 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
927 text.append("#line 1\n");
928 text.append(glslangIntermediate->getSourceText());
929 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600930 }
John Kessenich140f3df2015-06-26 16:58:36 -0600931 stdBuiltins = builder.import("GLSL.std.450");
932 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600933 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
934 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600935
936 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600937 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
938 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600939 builder.addSourceExtension(it->c_str());
940
941 // Add the top-level modes for this shader.
942
John Kessenich92187592016-02-01 13:45:25 -0700943 if (glslangIntermediate->getXfbMode()) {
944 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600945 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700946 }
John Kessenich140f3df2015-06-26 16:58:36 -0600947
948 unsigned int mode;
949 switch (glslangIntermediate->getStage()) {
950 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600951 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600952 break;
953
steve-lunarge7412492017-03-23 11:56:07 -0600954 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600955 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600957
steve-lunarge7412492017-03-23 11:56:07 -0600958 glslang::TLayoutGeometry primitive;
959
960 if (glslangIntermediate->getStage() == EShLangTessControl) {
961 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
962 primitive = glslangIntermediate->getOutputPrimitive();
963 } else {
964 primitive = glslangIntermediate->getInputPrimitive();
965 }
966
967 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700968 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
969 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
970 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600971 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600972 }
John Kessenich4016e382016-07-15 11:53:56 -0600973 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600974 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
975
John Kesseniche6903322015-10-13 16:29:02 -0600976 switch (glslangIntermediate->getVertexSpacing()) {
977 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
978 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
979 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600980 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600981 }
John Kessenich4016e382016-07-15 11:53:56 -0600982 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600983 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
984
985 switch (glslangIntermediate->getVertexOrder()) {
986 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
987 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; 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 if (glslangIntermediate->getPointMode())
994 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600995 break;
996
997 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600998 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600999 switch (glslangIntermediate->getInputPrimitive()) {
1000 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1001 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1002 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001003 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001004 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001005 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001006 }
John Kessenich4016e382016-07-15 11:53:56 -06001007 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001008 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001009
John Kessenich140f3df2015-06-26 16:58:36 -06001010 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1011
1012 switch (glslangIntermediate->getOutputPrimitive()) {
1013 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1014 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1015 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001016 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001017 }
John Kessenich4016e382016-07-15 11:53:56 -06001018 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001019 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1020 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1021 break;
1022
1023 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001024 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001025 if (glslangIntermediate->getPixelCenterInteger())
1026 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001027
John Kessenich140f3df2015-06-26 16:58:36 -06001028 if (glslangIntermediate->getOriginUpperLeft())
1029 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001030 else
1031 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001032
1033 if (glslangIntermediate->getEarlyFragmentTests())
1034 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1035
chaocc1204522017-06-30 17:14:30 -07001036 if (glslangIntermediate->getPostDepthCoverage()) {
1037 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1038 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1039 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1040 }
1041
John Kesseniche6903322015-10-13 16:29:02 -06001042 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001043 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1044 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001045 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001046 }
John Kessenich4016e382016-07-15 11:53:56 -06001047 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001048 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1049
1050 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1051 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001052 break;
1053
1054 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001055 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001056 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1057 glslangIntermediate->getLocalSize(1),
1058 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001059 break;
1060
1061 default:
1062 break;
1063 }
John Kessenich140f3df2015-06-26 16:58:36 -06001064}
1065
John Kessenichfca82622016-11-26 13:23:20 -07001066// Finish creating SPV, after the traversal is complete.
1067void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001068{
John Kessenich517fe7a2016-11-26 13:31:47 -07001069 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001070 builder.setBuildPoint(shaderEntry->getLastBlock());
1071 builder.leaveFunction();
1072 }
1073
John Kessenich7ba63412015-12-20 17:37:07 -07001074 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001075 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1076 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001077
qiningda397332016-03-09 19:54:03 -05001078 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001079}
1080
John Kessenichfca82622016-11-26 13:23:20 -07001081// Write the SPV into 'out'.
1082void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001083{
John Kessenichfca82622016-11-26 13:23:20 -07001084 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001085}
1086
1087//
1088// Implement the traversal functions.
1089//
1090// Return true from interior nodes to have the external traversal
1091// continue on to children. Return false if children were
1092// already processed.
1093//
1094
1095//
qining25262b32016-05-06 17:25:16 -04001096// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001097// - uniform/input reads
1098// - output writes
1099// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1100// - something simple that degenerates into the last bullet
1101//
1102void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1103{
qining75d1d802016-04-06 14:42:01 -04001104 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1105 if (symbol->getType().getQualifier().isSpecConstant())
1106 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1107
John Kessenich140f3df2015-06-26 16:58:36 -06001108 // getSymbolId() will set up all the IO decorations on the first call.
1109 // Formal function parameters were mapped during makeFunctions().
1110 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001111
1112 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1113 if (builder.isPointer(id)) {
1114 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001115 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1116 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1117 iOSet.insert(id);
1118 }
John Kessenich7ba63412015-12-20 17:37:07 -07001119 }
1120
1121 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001122 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001123 // Prepare to generate code for the access
1124
1125 // L-value chains will be computed left to right. We're on the symbol now,
1126 // which is the left-most part of the access chain, so now is "clear" time,
1127 // followed by setting the base.
1128 builder.clearAccessChain();
1129
1130 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001131 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001132 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001133 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001134 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001135 // These are also pure R-values.
1136 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001137 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001138 builder.setAccessChainRValue(id);
1139 else
1140 builder.setAccessChainLValue(id);
1141 }
1142}
1143
1144bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1145{
John Kesseniche485c7a2017-05-31 18:50:53 -06001146 builder.setLine(node->getLoc().line);
1147
qining40887662016-04-03 22:20:42 -04001148 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1149 if (node->getType().getQualifier().isSpecConstant())
1150 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1151
John Kessenich140f3df2015-06-26 16:58:36 -06001152 // First, handle special cases
1153 switch (node->getOp()) {
1154 case glslang::EOpAssign:
1155 case glslang::EOpAddAssign:
1156 case glslang::EOpSubAssign:
1157 case glslang::EOpMulAssign:
1158 case glslang::EOpVectorTimesMatrixAssign:
1159 case glslang::EOpVectorTimesScalarAssign:
1160 case glslang::EOpMatrixTimesScalarAssign:
1161 case glslang::EOpMatrixTimesMatrixAssign:
1162 case glslang::EOpDivAssign:
1163 case glslang::EOpModAssign:
1164 case glslang::EOpAndAssign:
1165 case glslang::EOpInclusiveOrAssign:
1166 case glslang::EOpExclusiveOrAssign:
1167 case glslang::EOpLeftShiftAssign:
1168 case glslang::EOpRightShiftAssign:
1169 // A bin-op assign "a += b" means the same thing as "a = a + b"
1170 // where a is evaluated before b. For a simple assignment, GLSL
1171 // says to evaluate the left before the right. So, always, left
1172 // node then right node.
1173 {
1174 // get the left l-value, save it away
1175 builder.clearAccessChain();
1176 node->getLeft()->traverse(this);
1177 spv::Builder::AccessChain lValue = builder.getAccessChain();
1178
1179 // evaluate the right
1180 builder.clearAccessChain();
1181 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001182 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001183
1184 if (node->getOp() != glslang::EOpAssign) {
1185 // the left is also an r-value
1186 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001187 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001188
1189 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001190 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001191 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001192 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1193 node->getType().getBasicType());
1194
1195 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001196 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 }
1198
1199 // store the result
1200 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001201 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001202
1203 // assignments are expressions having an rValue after they are evaluated...
1204 builder.clearAccessChain();
1205 builder.setAccessChainRValue(rValue);
1206 }
1207 return false;
1208 case glslang::EOpIndexDirect:
1209 case glslang::EOpIndexDirectStruct:
1210 {
1211 // Get the left part of the access chain.
1212 node->getLeft()->traverse(this);
1213
1214 // Add the next element in the chain
1215
David Netoa901ffe2016-06-08 14:11:40 +01001216 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001217 if (! node->getLeft()->getType().isArray() &&
1218 node->getLeft()->getType().isVector() &&
1219 node->getOp() == glslang::EOpIndexDirect) {
1220 // This is essentially a hard-coded vector swizzle of size 1,
1221 // so short circuit the access-chain stuff with a swizzle.
1222 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001223 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001224 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001225 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001226 int spvIndex = glslangIndex;
1227 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1228 node->getOp() == glslang::EOpIndexDirectStruct)
1229 {
1230 // This may be, e.g., an anonymous block-member selection, which generally need
1231 // index remapping due to hidden members in anonymous blocks.
1232 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1233 assert(remapper.size() > 0);
1234 spvIndex = remapper[glslangIndex];
1235 }
John Kessenichebb50532016-05-16 19:22:05 -06001236
David Netoa901ffe2016-06-08 14:11:40 +01001237 // normal case for indexing array or structure or block
1238 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1239
1240 // Add capabilities here for accessing PointSize and clip/cull distance.
1241 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001242 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001243 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001244 }
1245 }
1246 return false;
1247 case glslang::EOpIndexIndirect:
1248 {
1249 // Structure or array or vector indirection.
1250 // Will use native SPIR-V access-chain for struct and array indirection;
1251 // matrices are arrays of vectors, so will also work for a matrix.
1252 // Will use the access chain's 'component' for variable index into a vector.
1253
1254 // This adapter is building access chains left to right.
1255 // Set up the access chain to the left.
1256 node->getLeft()->traverse(this);
1257
1258 // save it so that computing the right side doesn't trash it
1259 spv::Builder::AccessChain partial = builder.getAccessChain();
1260
1261 // compute the next index in the chain
1262 builder.clearAccessChain();
1263 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001264 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001265
1266 // restore the saved access chain
1267 builder.setAccessChain(partial);
1268
1269 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001270 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001271 else
John Kessenichfa668da2015-09-13 14:46:30 -06001272 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001273 }
1274 return false;
1275 case glslang::EOpVectorSwizzle:
1276 {
1277 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001278 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001279 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001281 }
1282 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001283 case glslang::EOpMatrixSwizzle:
1284 logger->missingFunctionality("matrix swizzle");
1285 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001286 case glslang::EOpLogicalOr:
1287 case glslang::EOpLogicalAnd:
1288 {
1289
1290 // These may require short circuiting, but can sometimes be done as straight
1291 // binary operations. The right operand must be short circuited if it has
1292 // side effects, and should probably be if it is complex.
1293 if (isTrivial(node->getRight()->getAsTyped()))
1294 break; // handle below as a normal binary operation
1295 // otherwise, we need to do dynamic short circuiting on the right operand
1296 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1297 builder.clearAccessChain();
1298 builder.setAccessChainRValue(result);
1299 }
1300 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001301 default:
1302 break;
1303 }
1304
1305 // Assume generic binary op...
1306
John Kessenich32cfd492016-02-02 12:37:46 -07001307 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001308 builder.clearAccessChain();
1309 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001310 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001311
John Kessenich32cfd492016-02-02 12:37:46 -07001312 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001313 builder.clearAccessChain();
1314 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001315 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001316
John Kessenich32cfd492016-02-02 12:37:46 -07001317 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001318 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001319 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001320 convertGlslangToSpvType(node->getType()), left, right,
1321 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001322
John Kessenich50e57562015-12-21 21:21:11 -07001323 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001324 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001325 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001326 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001327 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001328 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001329 return false;
1330 }
John Kessenich140f3df2015-06-26 16:58:36 -06001331}
1332
1333bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1334{
John Kesseniche485c7a2017-05-31 18:50:53 -06001335 builder.setLine(node->getLoc().line);
1336
qining40887662016-04-03 22:20:42 -04001337 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1338 if (node->getType().getQualifier().isSpecConstant())
1339 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1340
John Kessenichfc51d282015-08-19 13:34:18 -06001341 spv::Id result = spv::NoResult;
1342
1343 // try texturing first
1344 result = createImageTextureFunctionCall(node);
1345 if (result != spv::NoResult) {
1346 builder.clearAccessChain();
1347 builder.setAccessChainRValue(result);
1348
1349 return false; // done with this node
1350 }
1351
1352 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001353
1354 if (node->getOp() == glslang::EOpArrayLength) {
1355 // Quite special; won't want to evaluate the operand.
1356
1357 // Normal .length() would have been constant folded by the front-end.
1358 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001359 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001360 assert(node->getOperand()->getType().isRuntimeSizedArray());
1361 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1362 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001363 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1364 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001365
1366 builder.clearAccessChain();
1367 builder.setAccessChainRValue(length);
1368
1369 return false;
1370 }
1371
John Kessenichfc51d282015-08-19 13:34:18 -06001372 // Start by evaluating the operand
1373
John Kessenich8c8505c2016-07-26 12:50:38 -06001374 // Does it need a swizzle inversion? If so, evaluation is inverted;
1375 // operate first on the swizzle base, then apply the swizzle.
1376 spv::Id invertedType = spv::NoType;
1377 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1378 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1379 invertedType = getInvertedSwizzleType(*node->getOperand());
1380
John Kessenich140f3df2015-06-26 16:58:36 -06001381 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001382 if (invertedType != spv::NoType)
1383 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1384 else
1385 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001386
Rex Xufc618912015-09-09 16:42:49 +08001387 spv::Id operand = spv::NoResult;
1388
1389 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1390 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001391 node->getOp() == glslang::EOpAtomicCounter ||
1392 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001393 operand = builder.accessChainGetLValue(); // Special case l-value operands
1394 else
John Kessenich32cfd492016-02-02 12:37:46 -07001395 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001396
John Kessenichf6640762016-08-01 19:44:00 -06001397 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001398 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001399
1400 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001401 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001402 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001403
1404 // if not, then possibly an operation
1405 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001406 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001407
1408 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001409 if (invertedType)
1410 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1411
John Kessenich140f3df2015-06-26 16:58:36 -06001412 builder.clearAccessChain();
1413 builder.setAccessChainRValue(result);
1414
1415 return false; // done with this node
1416 }
1417
1418 // it must be a special case, check...
1419 switch (node->getOp()) {
1420 case glslang::EOpPostIncrement:
1421 case glslang::EOpPostDecrement:
1422 case glslang::EOpPreIncrement:
1423 case glslang::EOpPreDecrement:
1424 {
1425 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001426 spv::Id one = 0;
1427 if (node->getBasicType() == glslang::EbtFloat)
1428 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001429 else if (node->getBasicType() == glslang::EbtDouble)
1430 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001431#ifdef AMD_EXTENSIONS
1432 else if (node->getBasicType() == glslang::EbtFloat16)
1433 one = builder.makeFloat16Constant(1.0F);
1434#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001435 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1436 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001437#ifdef AMD_EXTENSIONS
1438 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1439 one = builder.makeInt16Constant(1);
1440#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001441 else
1442 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001443 glslang::TOperator op;
1444 if (node->getOp() == glslang::EOpPreIncrement ||
1445 node->getOp() == glslang::EOpPostIncrement)
1446 op = glslang::EOpAdd;
1447 else
1448 op = glslang::EOpSub;
1449
John Kessenichf6640762016-08-01 19:44:00 -06001450 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001451 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001452 convertGlslangToSpvType(node->getType()), operand, one,
1453 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001454 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001455
1456 // The result of operation is always stored, but conditionally the
1457 // consumed result. The consumed result is always an r-value.
1458 builder.accessChainStore(result);
1459 builder.clearAccessChain();
1460 if (node->getOp() == glslang::EOpPreIncrement ||
1461 node->getOp() == glslang::EOpPreDecrement)
1462 builder.setAccessChainRValue(result);
1463 else
1464 builder.setAccessChainRValue(operand);
1465 }
1466
1467 return false;
1468
1469 case glslang::EOpEmitStreamVertex:
1470 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1471 return false;
1472 case glslang::EOpEndStreamPrimitive:
1473 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1474 return false;
1475
1476 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001477 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001478 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001479 }
John Kessenich140f3df2015-06-26 16:58:36 -06001480}
1481
1482bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1483{
qining27e04a02016-04-14 16:40:20 -04001484 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1485 if (node->getType().getQualifier().isSpecConstant())
1486 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1487
John Kessenichfc51d282015-08-19 13:34:18 -06001488 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001489 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1490 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001491
1492 // try texturing
1493 result = createImageTextureFunctionCall(node);
1494 if (result != spv::NoResult) {
1495 builder.clearAccessChain();
1496 builder.setAccessChainRValue(result);
1497
1498 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001499#ifdef AMD_EXTENSIONS
1500 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1501#else
John Kessenich56bab042015-09-16 10:54:31 -06001502 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001503#endif
Rex Xufc618912015-09-09 16:42:49 +08001504 // "imageStore" is a special case, which has no result
1505 return false;
1506 }
John Kessenichfc51d282015-08-19 13:34:18 -06001507
John Kessenich140f3df2015-06-26 16:58:36 -06001508 glslang::TOperator binOp = glslang::EOpNull;
1509 bool reduceComparison = true;
1510 bool isMatrix = false;
1511 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001512 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001513
1514 assert(node->getOp());
1515
John Kessenichf6640762016-08-01 19:44:00 -06001516 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001517
1518 switch (node->getOp()) {
1519 case glslang::EOpSequence:
1520 {
1521 if (preVisit)
1522 ++sequenceDepth;
1523 else
1524 --sequenceDepth;
1525
1526 if (sequenceDepth == 1) {
1527 // If this is the parent node of all the functions, we want to see them
1528 // early, so all call points have actual SPIR-V functions to reference.
1529 // In all cases, still let the traverser visit the children for us.
1530 makeFunctions(node->getAsAggregate()->getSequence());
1531
John Kessenich6fccb3c2016-09-19 16:01:41 -06001532 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001533 // anything else gets there, so visit out of order, doing them all now.
1534 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1535
John Kessenich6a60c2f2016-12-08 21:01:59 -07001536 // 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 -06001537 // so do them manually.
1538 visitFunctions(node->getAsAggregate()->getSequence());
1539
1540 return false;
1541 }
1542
1543 return true;
1544 }
1545 case glslang::EOpLinkerObjects:
1546 {
1547 if (visit == glslang::EvPreVisit)
1548 linkageOnly = true;
1549 else
1550 linkageOnly = false;
1551
1552 return true;
1553 }
1554 case glslang::EOpComma:
1555 {
1556 // processing from left to right naturally leaves the right-most
1557 // lying around in the access chain
1558 glslang::TIntermSequence& glslangOperands = node->getSequence();
1559 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1560 glslangOperands[i]->traverse(this);
1561
1562 return false;
1563 }
1564 case glslang::EOpFunction:
1565 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001566 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001567 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001568 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001569 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001570 } else {
1571 handleFunctionEntry(node);
1572 }
1573 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001574 if (inEntryPoint)
1575 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001576 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001577 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001578 }
1579
1580 return true;
1581 case glslang::EOpParameters:
1582 // Parameters will have been consumed by EOpFunction processing, but not
1583 // the body, so we still visited the function node's children, making this
1584 // child redundant.
1585 return false;
1586 case glslang::EOpFunctionCall:
1587 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001588 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001589 if (node->isUserDefined())
1590 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001591 // 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 -07001592 if (result) {
1593 builder.clearAccessChain();
1594 builder.setAccessChainRValue(result);
1595 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001596 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001597
1598 return false;
1599 }
1600 case glslang::EOpConstructMat2x2:
1601 case glslang::EOpConstructMat2x3:
1602 case glslang::EOpConstructMat2x4:
1603 case glslang::EOpConstructMat3x2:
1604 case glslang::EOpConstructMat3x3:
1605 case glslang::EOpConstructMat3x4:
1606 case glslang::EOpConstructMat4x2:
1607 case glslang::EOpConstructMat4x3:
1608 case glslang::EOpConstructMat4x4:
1609 case glslang::EOpConstructDMat2x2:
1610 case glslang::EOpConstructDMat2x3:
1611 case glslang::EOpConstructDMat2x4:
1612 case glslang::EOpConstructDMat3x2:
1613 case glslang::EOpConstructDMat3x3:
1614 case glslang::EOpConstructDMat3x4:
1615 case glslang::EOpConstructDMat4x2:
1616 case glslang::EOpConstructDMat4x3:
1617 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001618 case glslang::EOpConstructIMat2x2:
1619 case glslang::EOpConstructIMat2x3:
1620 case glslang::EOpConstructIMat2x4:
1621 case glslang::EOpConstructIMat3x2:
1622 case glslang::EOpConstructIMat3x3:
1623 case glslang::EOpConstructIMat3x4:
1624 case glslang::EOpConstructIMat4x2:
1625 case glslang::EOpConstructIMat4x3:
1626 case glslang::EOpConstructIMat4x4:
1627 case glslang::EOpConstructUMat2x2:
1628 case glslang::EOpConstructUMat2x3:
1629 case glslang::EOpConstructUMat2x4:
1630 case glslang::EOpConstructUMat3x2:
1631 case glslang::EOpConstructUMat3x3:
1632 case glslang::EOpConstructUMat3x4:
1633 case glslang::EOpConstructUMat4x2:
1634 case glslang::EOpConstructUMat4x3:
1635 case glslang::EOpConstructUMat4x4:
1636 case glslang::EOpConstructBMat2x2:
1637 case glslang::EOpConstructBMat2x3:
1638 case glslang::EOpConstructBMat2x4:
1639 case glslang::EOpConstructBMat3x2:
1640 case glslang::EOpConstructBMat3x3:
1641 case glslang::EOpConstructBMat3x4:
1642 case glslang::EOpConstructBMat4x2:
1643 case glslang::EOpConstructBMat4x3:
1644 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001645#ifdef AMD_EXTENSIONS
1646 case glslang::EOpConstructF16Mat2x2:
1647 case glslang::EOpConstructF16Mat2x3:
1648 case glslang::EOpConstructF16Mat2x4:
1649 case glslang::EOpConstructF16Mat3x2:
1650 case glslang::EOpConstructF16Mat3x3:
1651 case glslang::EOpConstructF16Mat3x4:
1652 case glslang::EOpConstructF16Mat4x2:
1653 case glslang::EOpConstructF16Mat4x3:
1654 case glslang::EOpConstructF16Mat4x4:
1655#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001656 isMatrix = true;
1657 // fall through
1658 case glslang::EOpConstructFloat:
1659 case glslang::EOpConstructVec2:
1660 case glslang::EOpConstructVec3:
1661 case glslang::EOpConstructVec4:
1662 case glslang::EOpConstructDouble:
1663 case glslang::EOpConstructDVec2:
1664 case glslang::EOpConstructDVec3:
1665 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001666#ifdef AMD_EXTENSIONS
1667 case glslang::EOpConstructFloat16:
1668 case glslang::EOpConstructF16Vec2:
1669 case glslang::EOpConstructF16Vec3:
1670 case glslang::EOpConstructF16Vec4:
1671#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001672 case glslang::EOpConstructBool:
1673 case glslang::EOpConstructBVec2:
1674 case glslang::EOpConstructBVec3:
1675 case glslang::EOpConstructBVec4:
1676 case glslang::EOpConstructInt:
1677 case glslang::EOpConstructIVec2:
1678 case glslang::EOpConstructIVec3:
1679 case glslang::EOpConstructIVec4:
1680 case glslang::EOpConstructUint:
1681 case glslang::EOpConstructUVec2:
1682 case glslang::EOpConstructUVec3:
1683 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001684 case glslang::EOpConstructInt64:
1685 case glslang::EOpConstructI64Vec2:
1686 case glslang::EOpConstructI64Vec3:
1687 case glslang::EOpConstructI64Vec4:
1688 case glslang::EOpConstructUint64:
1689 case glslang::EOpConstructU64Vec2:
1690 case glslang::EOpConstructU64Vec3:
1691 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001692#ifdef AMD_EXTENSIONS
1693 case glslang::EOpConstructInt16:
1694 case glslang::EOpConstructI16Vec2:
1695 case glslang::EOpConstructI16Vec3:
1696 case glslang::EOpConstructI16Vec4:
1697 case glslang::EOpConstructUint16:
1698 case glslang::EOpConstructU16Vec2:
1699 case glslang::EOpConstructU16Vec3:
1700 case glslang::EOpConstructU16Vec4:
1701#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001702 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001703 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001704 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001705 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001706 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001707 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001708 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001709 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001710 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001711 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001712 std::vector<spv::Id> constituents;
1713 for (int c = 0; c < (int)arguments.size(); ++c)
1714 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001715 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001716 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001717 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001718 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001719 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001720
1721 builder.clearAccessChain();
1722 builder.setAccessChainRValue(constructed);
1723
1724 return false;
1725 }
1726
1727 // These six are component-wise compares with component-wise results.
1728 // Forward on to createBinaryOperation(), requesting a vector result.
1729 case glslang::EOpLessThan:
1730 case glslang::EOpGreaterThan:
1731 case glslang::EOpLessThanEqual:
1732 case glslang::EOpGreaterThanEqual:
1733 case glslang::EOpVectorEqual:
1734 case glslang::EOpVectorNotEqual:
1735 {
1736 // Map the operation to a binary
1737 binOp = node->getOp();
1738 reduceComparison = false;
1739 switch (node->getOp()) {
1740 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1741 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1742 default: binOp = node->getOp(); break;
1743 }
1744
1745 break;
1746 }
1747 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001748 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001749 binOp = glslang::EOpMul;
1750 break;
1751 case glslang::EOpOuterProduct:
1752 // two vectors multiplied to make a matrix
1753 binOp = glslang::EOpOuterProduct;
1754 break;
1755 case glslang::EOpDot:
1756 {
qining25262b32016-05-06 17:25:16 -04001757 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001758 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001759 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001760 binOp = glslang::EOpMul;
1761 break;
1762 }
1763 case glslang::EOpMod:
1764 // when an aggregate, this is the floating-point mod built-in function,
1765 // which can be emitted by the one in createBinaryOperation()
1766 binOp = glslang::EOpMod;
1767 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001768 case glslang::EOpEmitVertex:
1769 case glslang::EOpEndPrimitive:
1770 case glslang::EOpBarrier:
1771 case glslang::EOpMemoryBarrier:
1772 case glslang::EOpMemoryBarrierAtomicCounter:
1773 case glslang::EOpMemoryBarrierBuffer:
1774 case glslang::EOpMemoryBarrierImage:
1775 case glslang::EOpMemoryBarrierShared:
1776 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001777 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001778 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001779 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001780 case glslang::EOpWorkgroupMemoryBarrier:
1781 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001782 noReturnValue = true;
1783 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1784 break;
1785
John Kessenich426394d2015-07-23 10:22:48 -06001786 case glslang::EOpAtomicAdd:
1787 case glslang::EOpAtomicMin:
1788 case glslang::EOpAtomicMax:
1789 case glslang::EOpAtomicAnd:
1790 case glslang::EOpAtomicOr:
1791 case glslang::EOpAtomicXor:
1792 case glslang::EOpAtomicExchange:
1793 case glslang::EOpAtomicCompSwap:
1794 atomic = true;
1795 break;
1796
John Kessenich0d0c6d32017-07-23 16:08:26 -06001797 case glslang::EOpAtomicCounterAdd:
1798 case glslang::EOpAtomicCounterSubtract:
1799 case glslang::EOpAtomicCounterMin:
1800 case glslang::EOpAtomicCounterMax:
1801 case glslang::EOpAtomicCounterAnd:
1802 case glslang::EOpAtomicCounterOr:
1803 case glslang::EOpAtomicCounterXor:
1804 case glslang::EOpAtomicCounterExchange:
1805 case glslang::EOpAtomicCounterCompSwap:
1806 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1807 builder.addCapability(spv::CapabilityAtomicStorageOps);
1808 atomic = true;
1809 break;
1810
John Kessenich140f3df2015-06-26 16:58:36 -06001811 default:
1812 break;
1813 }
1814
1815 //
1816 // See if it maps to a regular operation.
1817 //
John Kessenich140f3df2015-06-26 16:58:36 -06001818 if (binOp != glslang::EOpNull) {
1819 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1820 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1821 assert(left && right);
1822
1823 builder.clearAccessChain();
1824 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001825 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001826
1827 builder.clearAccessChain();
1828 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001829 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001830
John Kesseniche485c7a2017-05-31 18:50:53 -06001831 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001832 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001833 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001834 left->getType().getBasicType(), reduceComparison);
1835
1836 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001837 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001838 builder.clearAccessChain();
1839 builder.setAccessChainRValue(result);
1840
1841 return false;
1842 }
1843
John Kessenich426394d2015-07-23 10:22:48 -06001844 //
1845 // Create the list of operands.
1846 //
John Kessenich140f3df2015-06-26 16:58:36 -06001847 glslang::TIntermSequence& glslangOperands = node->getSequence();
1848 std::vector<spv::Id> operands;
1849 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001850 // special case l-value operands; there are just a few
1851 bool lvalue = false;
1852 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001853 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001854 case glslang::EOpModf:
1855 if (arg == 1)
1856 lvalue = true;
1857 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001858 case glslang::EOpInterpolateAtSample:
1859 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001860#ifdef AMD_EXTENSIONS
1861 case glslang::EOpInterpolateAtVertex:
1862#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001863 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001864 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001865
1866 // Does it need a swizzle inversion? If so, evaluation is inverted;
1867 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001868 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001869 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1870 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1871 }
Rex Xu7a26c172015-12-08 17:12:09 +08001872 break;
Rex Xud4782c12015-09-06 16:30:11 +08001873 case glslang::EOpAtomicAdd:
1874 case glslang::EOpAtomicMin:
1875 case glslang::EOpAtomicMax:
1876 case glslang::EOpAtomicAnd:
1877 case glslang::EOpAtomicOr:
1878 case glslang::EOpAtomicXor:
1879 case glslang::EOpAtomicExchange:
1880 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001881 case glslang::EOpAtomicCounterAdd:
1882 case glslang::EOpAtomicCounterSubtract:
1883 case glslang::EOpAtomicCounterMin:
1884 case glslang::EOpAtomicCounterMax:
1885 case glslang::EOpAtomicCounterAnd:
1886 case glslang::EOpAtomicCounterOr:
1887 case glslang::EOpAtomicCounterXor:
1888 case glslang::EOpAtomicCounterExchange:
1889 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001890 if (arg == 0)
1891 lvalue = true;
1892 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001893 case glslang::EOpAddCarry:
1894 case glslang::EOpSubBorrow:
1895 if (arg == 2)
1896 lvalue = true;
1897 break;
1898 case glslang::EOpUMulExtended:
1899 case glslang::EOpIMulExtended:
1900 if (arg >= 2)
1901 lvalue = true;
1902 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001903 default:
1904 break;
1905 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001906 builder.clearAccessChain();
1907 if (invertedType != spv::NoType && arg == 0)
1908 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1909 else
1910 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001911 if (lvalue)
1912 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001913 else {
1914 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001915 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001916 }
John Kessenich140f3df2015-06-26 16:58:36 -06001917 }
John Kessenich426394d2015-07-23 10:22:48 -06001918
John Kesseniche485c7a2017-05-31 18:50:53 -06001919 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001920 if (atomic) {
1921 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001922 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001923 } else {
1924 // Pass through to generic operations.
1925 switch (glslangOperands.size()) {
1926 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001927 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001928 break;
1929 case 1:
qining25262b32016-05-06 17:25:16 -04001930 result = createUnaryOperation(
1931 node->getOp(), precision,
1932 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001933 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001934 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001935 break;
1936 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001937 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001938 break;
1939 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001940 if (invertedType)
1941 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001942 }
1943
1944 if (noReturnValue)
1945 return false;
1946
1947 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001948 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001949 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001950 } else {
1951 builder.clearAccessChain();
1952 builder.setAccessChainRValue(result);
1953 return false;
1954 }
1955}
1956
John Kessenich433e9ff2017-01-26 20:31:11 -07001957// This path handles both if-then-else and ?:
1958// The if-then-else has a node type of void, while
1959// ?: has either a void or a non-void node type
1960//
1961// Leaving the result, when not void:
1962// GLSL only has r-values as the result of a :?, but
1963// if we have an l-value, that can be more efficient if it will
1964// become the base of a complex r-value expression, because the
1965// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001966bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1967{
John Kessenich433e9ff2017-01-26 20:31:11 -07001968 // See if it simple and safe to generate OpSelect instead of using control flow.
1969 // Crucially, side effects must be avoided, and there are performance trade-offs.
1970 // Return true if good idea (and safe) for OpSelect, false otherwise.
1971 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001972 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1973 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001974 return false;
1975
1976 if (node->getTrueBlock() == nullptr ||
1977 node->getFalseBlock() == nullptr)
1978 return false;
1979
1980 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1981 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1982
1983 // return true if a single operand to ? : is okay for OpSelect
1984 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001985 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001986 };
1987
1988 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1989 operandOkay(node->getFalseBlock()->getAsTyped());
1990 };
1991
1992 // Emit OpSelect for this selection.
1993 const auto handleAsOpSelect = [&]() {
1994 node->getCondition()->traverse(this);
1995 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1996 node->getTrueBlock()->traverse(this);
1997 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1998 node->getFalseBlock()->traverse(this);
1999 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2000
John Kesseniche485c7a2017-05-31 18:50:53 -06002001 builder.setLine(node->getLoc().line);
2002
John Kesseniche434ad92017-03-30 10:09:28 -06002003 // smear condition to vector, if necessary (AST is always scalar)
2004 if (builder.isVector(trueValue))
2005 condition = builder.smearScalar(spv::NoPrecision, condition,
2006 builder.makeVectorType(builder.makeBoolType(),
2007 builder.getNumComponents(trueValue)));
2008
2009 spv::Id select = builder.createTriOp(spv::OpSelect,
2010 convertGlslangToSpvType(node->getType()), condition,
2011 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002012 builder.clearAccessChain();
2013 builder.setAccessChainRValue(select);
2014 };
2015
2016 // Try for OpSelect
2017
2018 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002019 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2020 if (node->getType().getQualifier().isSpecConstant())
2021 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2022
John Kessenich433e9ff2017-01-26 20:31:11 -07002023 handleAsOpSelect();
2024 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002025 }
2026
Rex Xu57e65922017-07-04 23:23:40 +08002027 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002028 // Don't handle results as temporaries, because there will be two names
2029 // and better to leave SSA to later passes.
2030 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2031 ? spv::NoResult
2032 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2033
John Kessenich140f3df2015-06-26 16:58:36 -06002034 // emit the condition before doing anything with selection
2035 node->getCondition()->traverse(this);
2036
Rex Xu57e65922017-07-04 23:23:40 +08002037 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002038 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002039
John Kessenich140f3df2015-06-26 16:58:36 -06002040 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002041 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002042
John Kessenich433e9ff2017-01-26 20:31:11 -07002043 // emit the "then" statement
2044 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002045 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002046 if (result != spv::NoResult)
2047 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002048 }
2049
John Kessenich433e9ff2017-01-26 20:31:11 -07002050 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002051 ifBuilder.makeBeginElse();
2052 // emit the "else" statement
2053 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002054 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002055 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 }
2057
John Kessenich433e9ff2017-01-26 20:31:11 -07002058 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002059 ifBuilder.makeEndIf();
2060
John Kessenich433e9ff2017-01-26 20:31:11 -07002061 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002062 // GLSL only has r-values as the result of a :?, but
2063 // if we have an l-value, that can be more efficient if it will
2064 // become the base of a complex r-value expression, because the
2065 // next layer copies r-values into memory to use the access-chain mechanism
2066 builder.clearAccessChain();
2067 builder.setAccessChainLValue(result);
2068 }
2069
2070 return false;
2071}
2072
2073bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2074{
2075 // emit and get the condition before doing anything with switch
2076 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002077 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002078
Rex Xu57e65922017-07-04 23:23:40 +08002079 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002080 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002081
John Kessenich140f3df2015-06-26 16:58:36 -06002082 // browse the children to sort out code segments
2083 int defaultSegment = -1;
2084 std::vector<TIntermNode*> codeSegments;
2085 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2086 std::vector<int> caseValues;
2087 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2088 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2089 TIntermNode* child = *c;
2090 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002091 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002092 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002093 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002094 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2095 } else
2096 codeSegments.push_back(child);
2097 }
2098
qining25262b32016-05-06 17:25:16 -04002099 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002100 // statements between the last case and the end of the switch statement
2101 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2102 (int)codeSegments.size() == defaultSegment)
2103 codeSegments.push_back(nullptr);
2104
2105 // make the switch statement
2106 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002107 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002108
2109 // emit all the code in the segments
2110 breakForLoop.push(false);
2111 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2112 builder.nextSwitchSegment(segmentBlocks, s);
2113 if (codeSegments[s])
2114 codeSegments[s]->traverse(this);
2115 else
2116 builder.addSwitchBreak();
2117 }
2118 breakForLoop.pop();
2119
2120 builder.endSwitch(segmentBlocks);
2121
2122 return false;
2123}
2124
2125void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2126{
2127 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002128 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002129
2130 builder.clearAccessChain();
2131 builder.setAccessChainRValue(constant);
2132}
2133
2134bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2135{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002136 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002137 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002138
2139 // Loop control:
John Kesseniche18fd202018-01-30 11:01:39 -07002140 const spv::LoopControlMask control = TranslateLoopControl(*node);
steve-lunargf1709e72017-05-02 20:14:50 -06002141
2142 // TODO: dependency length
2143
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002144 // Spec requires back edges to target header blocks, and every header block
2145 // must dominate its merge block. Make a header block first to ensure these
2146 // conditions are met. By definition, it will contain OpLoopMerge, followed
2147 // by a block-ending branch. But we don't want to put any other body/test
2148 // instructions in it, since the body/test may have arbitrary instructions,
2149 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002150 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002151 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002152 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002153 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002154 spv::Block& test = builder.makeNewBlock();
2155 builder.createBranch(&test);
2156
2157 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002158 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002159 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002160 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2161
2162 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002163 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002164 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002165 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002166 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002167 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002168
2169 builder.setBuildPoint(&blocks.continue_target);
2170 if (node->getTerminal())
2171 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002172 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002173 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002174 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002175 builder.createBranch(&blocks.body);
2176
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002177 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002178 builder.setBuildPoint(&blocks.body);
2179 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002180 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002181 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002182 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002183
2184 builder.setBuildPoint(&blocks.continue_target);
2185 if (node->getTerminal())
2186 node->getTerminal()->traverse(this);
2187 if (node->getTest()) {
2188 node->getTest()->traverse(this);
2189 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002190 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002191 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002192 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002193 // TODO: unless there was a break/return/discard instruction
2194 // somewhere in the body, this is an infinite loop, so we should
2195 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002196 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002197 }
John Kessenich140f3df2015-06-26 16:58:36 -06002198 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002199 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002200 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002201 return false;
2202}
2203
2204bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2205{
2206 if (node->getExpression())
2207 node->getExpression()->traverse(this);
2208
John Kesseniche485c7a2017-05-31 18:50:53 -06002209 builder.setLine(node->getLoc().line);
2210
John Kessenich140f3df2015-06-26 16:58:36 -06002211 switch (node->getFlowOp()) {
2212 case glslang::EOpKill:
2213 builder.makeDiscard();
2214 break;
2215 case glslang::EOpBreak:
2216 if (breakForLoop.top())
2217 builder.createLoopExit();
2218 else
2219 builder.addSwitchBreak();
2220 break;
2221 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002222 builder.createLoopContinue();
2223 break;
2224 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002225 if (node->getExpression()) {
2226 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2227 spv::Id returnId = accessChainLoad(glslangReturnType);
2228 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2229 builder.clearAccessChain();
2230 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2231 builder.setAccessChainLValue(copyId);
2232 multiTypeStore(glslangReturnType, returnId);
2233 returnId = builder.createLoad(copyId);
2234 }
2235 builder.makeReturn(false, returnId);
2236 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002237 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002238
2239 builder.clearAccessChain();
2240 break;
2241
2242 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002243 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002244 break;
2245 }
2246
2247 return false;
2248}
2249
2250spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2251{
qining25262b32016-05-06 17:25:16 -04002252 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002253 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002254 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002255 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002256 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002257 }
2258
2259 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002260 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002261 spv::Id spvType = convertGlslangToSpvType(node->getType());
2262
Rex Xuf89ad982017-04-07 23:22:33 +08002263#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002264 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2265 node->getType().containsBasicType(glslang::EbtInt16) ||
2266 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002267 if (contains16BitType) {
2268 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2269 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2270 builder.addCapability(spv::CapabilityStorageInputOutput16);
2271 } else if (storageClass == spv::StorageClassPushConstant) {
2272 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2273 builder.addCapability(spv::CapabilityStoragePushConstant16);
2274 } else if (storageClass == spv::StorageClassUniform) {
2275 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2276 builder.addCapability(spv::CapabilityStorageUniform16);
2277 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2278 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2279 }
2280 }
2281#endif
2282
John Kessenich140f3df2015-06-26 16:58:36 -06002283 const char* name = node->getName().c_str();
2284 if (glslang::IsAnonymous(name))
2285 name = "";
2286
2287 return builder.createVariable(storageClass, spvType, name);
2288}
2289
2290// Return type Id of the sampled type.
2291spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2292{
2293 switch (sampler.type) {
2294 case glslang::EbtFloat: return builder.makeFloatType(32);
2295 case glslang::EbtInt: return builder.makeIntType(32);
2296 case glslang::EbtUint: return builder.makeUintType(32);
2297 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002298 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002299 return builder.makeFloatType(32);
2300 }
2301}
2302
John Kessenich8c8505c2016-07-26 12:50:38 -06002303// If node is a swizzle operation, return the type that should be used if
2304// the swizzle base is first consumed by another operation, before the swizzle
2305// is applied.
2306spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2307{
John Kessenichecba76f2017-01-06 00:34:48 -07002308 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002309 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2310 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2311 else
2312 return spv::NoType;
2313}
2314
2315// When inverting a swizzle with a parent op, this function
2316// will apply the swizzle operation to a completed parent operation.
2317spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2318{
2319 std::vector<unsigned> swizzle;
2320 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2321 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2322}
2323
John Kessenich8c8505c2016-07-26 12:50:38 -06002324// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2325void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2326{
2327 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2328 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2329 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2330}
2331
John Kessenich3ac051e2015-12-20 11:29:16 -07002332// Convert from a glslang type to an SPV type, by calling into a
2333// recursive version of this function. This establishes the inherited
2334// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002335spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2336{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002337 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002338}
2339
2340// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002341// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002342// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002343spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002344{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002345 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002346
2347 switch (type.getBasicType()) {
2348 case glslang::EbtVoid:
2349 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002350 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002351 break;
2352 case glslang::EbtFloat:
2353 spvType = builder.makeFloatType(32);
2354 break;
2355 case glslang::EbtDouble:
2356 spvType = builder.makeFloatType(64);
2357 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002358#ifdef AMD_EXTENSIONS
2359 case glslang::EbtFloat16:
2360 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002361 spvType = builder.makeFloatType(16);
2362 break;
2363#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002364 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002365 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2366 // a 32-bit int where non-0 means true.
2367 if (explicitLayout != glslang::ElpNone)
2368 spvType = builder.makeUintType(32);
2369 else
2370 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002371 break;
2372 case glslang::EbtInt:
2373 spvType = builder.makeIntType(32);
2374 break;
2375 case glslang::EbtUint:
2376 spvType = builder.makeUintType(32);
2377 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002378 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002379 spvType = builder.makeIntType(64);
2380 break;
2381 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002382 spvType = builder.makeUintType(64);
2383 break;
Rex Xucabbb782017-03-24 13:41:14 +08002384#ifdef AMD_EXTENSIONS
2385 case glslang::EbtInt16:
2386 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2387 spvType = builder.makeIntType(16);
2388 break;
2389 case glslang::EbtUint16:
2390 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2391 spvType = builder.makeUintType(16);
2392 break;
2393#endif
John Kessenich426394d2015-07-23 10:22:48 -06002394 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002395 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002396 spvType = builder.makeUintType(32);
2397 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002398 case glslang::EbtSampler:
2399 {
2400 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002401 if (sampler.sampler) {
2402 // pure sampler
2403 spvType = builder.makeSamplerType();
2404 } else {
2405 // an image is present, make its type
2406 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2407 sampler.image ? 2 : 1, TranslateImageFormat(type));
2408 if (sampler.combined) {
2409 // already has both image and sampler, make the combined type
2410 spvType = builder.makeSampledImageType(spvType);
2411 }
John Kessenich55e7d112015-11-15 21:33:39 -07002412 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002413 }
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415 case glslang::EbtStruct:
2416 case glslang::EbtBlock:
2417 {
2418 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002419 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002420
2421 // Try to share structs for different layouts, but not yet for other
2422 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002423 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002424 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002425 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002426 break;
2427
2428 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002429 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002430 memberRemapper[glslangMembers].resize(glslangMembers->size());
2431 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002432 }
2433 break;
2434 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002435 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002436 break;
2437 }
2438
2439 if (type.isMatrix())
2440 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2441 else {
2442 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2443 if (type.getVectorSize() > 1)
2444 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2445 }
2446
2447 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002448 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2449
John Kessenichc9a80832015-09-12 12:17:44 -06002450 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002451 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002452 // We need to decorate array strides for types needing explicit layout, except blocks.
2453 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002454 // Use a dummy glslang type for querying internal strides of
2455 // arrays of arrays, but using just a one-dimensional array.
2456 glslang::TType simpleArrayType(type, 0); // deference type of the array
2457 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2458 simpleArrayType.getArraySizes().dereference();
2459
2460 // Will compute the higher-order strides here, rather than making a whole
2461 // pile of types and doing repetitive recursion on their contents.
2462 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2463 }
John Kessenichf8842e52016-01-04 19:22:56 -07002464
2465 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002466 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002467 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002468 if (stride > 0)
2469 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002470 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002471 }
2472 } else {
2473 // single-dimensional array, and don't yet have stride
2474
John Kessenichf8842e52016-01-04 19:22:56 -07002475 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002476 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2477 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002478 }
John Kessenich31ed4832015-09-09 17:51:38 -06002479
John Kessenichc9a80832015-09-12 12:17:44 -06002480 // Do the outer dimension, which might not be known for a runtime-sized array
2481 if (type.isRuntimeSizedArray()) {
2482 spvType = builder.makeRuntimeArray(spvType);
2483 } else {
2484 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002485 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002486 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002487 if (stride > 0)
2488 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002489 }
2490
2491 return spvType;
2492}
2493
John Kessenich0e737842017-03-24 18:38:16 -06002494// TODO: this functionality should exist at a higher level, in creating the AST
2495//
2496// Identify interface members that don't have their required extension turned on.
2497//
2498bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2499{
2500 auto& extensions = glslangIntermediate->getRequestedExtensions();
2501
Rex Xubcf291a2017-03-29 23:01:36 +08002502 if (member.getFieldName() == "gl_ViewportMask" &&
2503 extensions.find("GL_NV_viewport_array2") == extensions.end())
2504 return true;
2505 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2506 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2507 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002508 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2509 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2510 return true;
2511 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2512 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2513 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002514 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2515 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2516 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002517
2518 return false;
2519};
2520
John Kessenich6090df02016-06-30 21:18:02 -06002521// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2522// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2523// Mutually recursive with convertGlslangToSpvType().
2524spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2525 const glslang::TTypeList* glslangMembers,
2526 glslang::TLayoutPacking explicitLayout,
2527 const glslang::TQualifier& qualifier)
2528{
2529 // Create a vector of struct types for SPIR-V to consume
2530 std::vector<spv::Id> spvMembers;
2531 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 -06002532 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2533 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2534 if (glslangMember.hiddenMember()) {
2535 ++memberDelta;
2536 if (type.getBasicType() == glslang::EbtBlock)
2537 memberRemapper[glslangMembers][i] = -1;
2538 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002539 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002540 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002541 if (filterMember(glslangMember))
2542 continue;
2543 }
John Kessenich6090df02016-06-30 21:18:02 -06002544 // modify just this child's view of the qualifier
2545 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2546 InheritQualifiers(memberQualifier, qualifier);
2547
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002548 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002549 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002550 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002551
2552 // recurse
2553 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2554 }
2555 }
2556
2557 // Make the SPIR-V type
2558 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002559 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002560 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2561
2562 // Decorate it
2563 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2564
2565 return spvType;
2566}
2567
2568void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2569 const glslang::TTypeList* glslangMembers,
2570 glslang::TLayoutPacking explicitLayout,
2571 const glslang::TQualifier& qualifier,
2572 spv::Id spvType)
2573{
2574 // Name and decorate the non-hidden members
2575 int offset = -1;
2576 int locationOffset = 0; // for use within the members of this struct
2577 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2578 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2579 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002580 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002581 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002582 if (filterMember(glslangMember))
2583 continue;
2584 }
John Kessenich6090df02016-06-30 21:18:02 -06002585
2586 // modify just this child's view of the qualifier
2587 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2588 InheritQualifiers(memberQualifier, qualifier);
2589
2590 // using -1 above to indicate a hidden member
2591 if (member >= 0) {
2592 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2593 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2594 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2595 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002596 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2597 type.getQualifier().storage == glslang::EvqVaryingOut) {
2598 if (type.getBasicType() == glslang::EbtBlock ||
2599 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002600 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2601 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2602 }
2603 }
2604 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2605
Rex Xu286ca432017-07-27 14:33:16 +08002606 if (type.getBasicType() == glslang::EbtBlock &&
2607 qualifier.storage == glslang::EvqBuffer) {
2608 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002609 std::vector<spv::Decoration> memory;
2610 TranslateMemoryDecoration(memberQualifier, memory);
2611 for (unsigned int i = 0; i < memory.size(); ++i)
2612 addMemberDecoration(spvType, member, memory[i]);
2613 }
2614
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002615 // Location assignment was already completed correctly by the front end,
2616 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002617 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002618 // ill-specified and decisions have been made to not allow this.
2619 if (! type.isArray() && memberQualifier.hasLocation())
2620 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002621
John Kessenich2f47bc92016-06-30 21:47:35 -06002622 if (qualifier.hasLocation()) // track for upcoming inheritance
2623 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2624
John Kessenich6090df02016-06-30 21:18:02 -06002625 // component, XFB, others
2626 if (glslangMember.getQualifier().hasComponent())
2627 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2628 if (glslangMember.getQualifier().hasXfbOffset())
2629 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2630 else if (explicitLayout != glslang::ElpNone) {
2631 // figure out what to do with offset, which is accumulating
2632 int nextOffset;
2633 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2634 if (offset >= 0)
2635 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2636 offset = nextOffset;
2637 }
2638
2639 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2640 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2641
2642 // built-in variable decorations
2643 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002644 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002645 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002646
2647#ifdef NV_EXTENSIONS
2648 if (builtIn == spv::BuiltInLayer) {
2649 // SPV_NV_viewport_array2 extension
2650 if (glslangMember.getQualifier().layoutViewportRelative){
2651 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2652 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2653 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2654 }
2655 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2656 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2657 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2658 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2659 }
2660 }
chaocdf3956c2017-02-14 14:52:34 -08002661 if (glslangMember.getQualifier().layoutPassthrough) {
2662 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2663 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2664 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2665 }
chaoc771d89f2017-01-13 01:10:53 -08002666#endif
John Kessenich6090df02016-06-30 21:18:02 -06002667 }
2668 }
2669
2670 // Decorate the structure
2671 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002672 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002673 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2674 builder.addCapability(spv::CapabilityGeometryStreams);
2675 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2676 }
John Kessenich6090df02016-06-30 21:18:02 -06002677}
2678
John Kessenich6c292d32016-02-15 20:58:50 -07002679// Turn the expression forming the array size into an id.
2680// This is not quite trivial, because of specialization constants.
2681// Sometimes, a raw constant is turned into an Id, and sometimes
2682// a specialization constant expression is.
2683spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2684{
2685 // First, see if this is sized with a node, meaning a specialization constant:
2686 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2687 if (specNode != nullptr) {
2688 builder.clearAccessChain();
2689 specNode->traverse(this);
2690 return accessChainLoad(specNode->getAsTyped()->getType());
2691 }
qining25262b32016-05-06 17:25:16 -04002692
John Kessenich6c292d32016-02-15 20:58:50 -07002693 // Otherwise, need a compile-time (front end) size, get it:
2694 int size = arraySizes.getDimSize(dim);
2695 assert(size > 0);
2696 return builder.makeUintConstant(size);
2697}
2698
John Kessenich103bef92016-02-08 21:38:15 -07002699// Wrap the builder's accessChainLoad to:
2700// - localize handling of RelaxedPrecision
2701// - use the SPIR-V inferred type instead of another conversion of the glslang type
2702// (avoids unnecessary work and possible type punning for structures)
2703// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002704spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2705{
John Kessenich103bef92016-02-08 21:38:15 -07002706 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2707 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2708
2709 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002710 if (type.getBasicType() == glslang::EbtBool) {
2711 if (builder.isScalarType(nominalTypeId)) {
2712 // Conversion for bool
2713 spv::Id boolType = builder.makeBoolType();
2714 if (nominalTypeId != boolType)
2715 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2716 } else if (builder.isVectorType(nominalTypeId)) {
2717 // Conversion for bvec
2718 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2719 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2720 if (nominalTypeId != bvecType)
2721 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2722 }
2723 }
John Kessenich103bef92016-02-08 21:38:15 -07002724
2725 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002726}
2727
Rex Xu27253232016-02-23 17:51:09 +08002728// Wrap the builder's accessChainStore to:
2729// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002730//
2731// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002732void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2733{
2734 // Need to convert to abstract types when necessary
2735 if (type.getBasicType() == glslang::EbtBool) {
2736 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2737
2738 if (builder.isScalarType(nominalTypeId)) {
2739 // Conversion for bool
2740 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002741 if (nominalTypeId != boolType) {
2742 // keep these outside arguments, for determinant order-of-evaluation
2743 spv::Id one = builder.makeUintConstant(1);
2744 spv::Id zero = builder.makeUintConstant(0);
2745 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2746 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002747 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002748 } else if (builder.isVectorType(nominalTypeId)) {
2749 // Conversion for bvec
2750 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2751 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002752 if (nominalTypeId != bvecType) {
2753 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002754 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2755 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2756 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002757 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002758 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2759 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002760 }
2761 }
2762
2763 builder.accessChainStore(rvalue);
2764}
2765
John Kessenich4bf71552016-09-02 11:20:21 -06002766// For storing when types match at the glslang level, but not might match at the
2767// SPIR-V level.
2768//
2769// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002770// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002771// as in a member-decorated way.
2772//
2773// NOTE: This function can handle any store request; if it's not special it
2774// simplifies to a simple OpStore.
2775//
2776// Implicitly uses the existing builder.accessChain as the storage target.
2777void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2778{
John Kessenichb3e24e42016-09-11 12:33:43 -06002779 // we only do the complex path here if it's an aggregate
2780 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002781 accessChainStore(type, rValue);
2782 return;
2783 }
2784
John Kessenichb3e24e42016-09-11 12:33:43 -06002785 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002786 spv::Id rType = builder.getTypeId(rValue);
2787 spv::Id lValue = builder.accessChainGetLValue();
2788 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2789 if (lType == rType) {
2790 accessChainStore(type, rValue);
2791 return;
2792 }
2793
John Kessenichb3e24e42016-09-11 12:33:43 -06002794 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002795 // where the two types were the same type in GLSL. This requires member
2796 // by member copy, recursively.
2797
John Kessenichb3e24e42016-09-11 12:33:43 -06002798 // If an array, copy element by element.
2799 if (type.isArray()) {
2800 glslang::TType glslangElementType(type, 0);
2801 spv::Id elementRType = builder.getContainedTypeId(rType);
2802 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2803 // get the source member
2804 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002805
John Kessenichb3e24e42016-09-11 12:33:43 -06002806 // set up the target storage
2807 builder.clearAccessChain();
2808 builder.setAccessChainLValue(lValue);
2809 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002810
John Kessenichb3e24e42016-09-11 12:33:43 -06002811 // store the member
2812 multiTypeStore(glslangElementType, elementRValue);
2813 }
2814 } else {
2815 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002816
John Kessenichb3e24e42016-09-11 12:33:43 -06002817 // loop over structure members
2818 const glslang::TTypeList& members = *type.getStruct();
2819 for (int m = 0; m < (int)members.size(); ++m) {
2820 const glslang::TType& glslangMemberType = *members[m].type;
2821
2822 // get the source member
2823 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2824 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2825
2826 // set up the target storage
2827 builder.clearAccessChain();
2828 builder.setAccessChainLValue(lValue);
2829 builder.accessChainPush(builder.makeIntConstant(m));
2830
2831 // store the member
2832 multiTypeStore(glslangMemberType, memberRValue);
2833 }
John Kessenich4bf71552016-09-02 11:20:21 -06002834 }
2835}
2836
John Kessenichf85e8062015-12-19 13:57:10 -07002837// Decide whether or not this type should be
2838// decorated with offsets and strides, and if so
2839// whether std140 or std430 rules should be applied.
2840glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002841{
John Kessenichf85e8062015-12-19 13:57:10 -07002842 // has to be a block
2843 if (type.getBasicType() != glslang::EbtBlock)
2844 return glslang::ElpNone;
2845
2846 // has to be a uniform or buffer block
2847 if (type.getQualifier().storage != glslang::EvqUniform &&
2848 type.getQualifier().storage != glslang::EvqBuffer)
2849 return glslang::ElpNone;
2850
2851 // return the layout to use
2852 switch (type.getQualifier().layoutPacking) {
2853 case glslang::ElpStd140:
2854 case glslang::ElpStd430:
2855 return type.getQualifier().layoutPacking;
2856 default:
2857 return glslang::ElpNone;
2858 }
John Kessenich31ed4832015-09-09 17:51:38 -06002859}
2860
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002861// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002862int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002863{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002864 int size;
John Kessenich49987892015-12-29 17:11:44 -07002865 int stride;
2866 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002867
2868 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002869}
2870
John Kessenich49987892015-12-29 17:11:44 -07002871// 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 -07002872// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002873int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002874{
John Kessenich49987892015-12-29 17:11:44 -07002875 glslang::TType elementType;
2876 elementType.shallowCopy(matrixType);
2877 elementType.clearArraySizes();
2878
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002879 int size;
John Kessenich49987892015-12-29 17:11:44 -07002880 int stride;
2881 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2882
2883 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002884}
2885
John Kessenich5e4b1242015-08-06 22:53:06 -06002886// Given a member type of a struct, realign the current offset for it, and compute
2887// the next (not yet aligned) offset for the next member, which will get aligned
2888// on the next call.
2889// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2890// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2891// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002892void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002893 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002894{
2895 // this will get a positive value when deemed necessary
2896 nextOffset = -1;
2897
John Kessenich5e4b1242015-08-06 22:53:06 -06002898 // override anything in currentOffset with user-set offset
2899 if (memberType.getQualifier().hasOffset())
2900 currentOffset = memberType.getQualifier().layoutOffset;
2901
2902 // It could be that current linker usage in glslang updated all the layoutOffset,
2903 // in which case the following code does not matter. But, that's not quite right
2904 // once cross-compilation unit GLSL validation is done, as the original user
2905 // settings are needed in layoutOffset, and then the following will come into play.
2906
John Kessenichf85e8062015-12-19 13:57:10 -07002907 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002908 if (! memberType.getQualifier().hasOffset())
2909 currentOffset = -1;
2910
2911 return;
2912 }
2913
John Kessenichf85e8062015-12-19 13:57:10 -07002914 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002915 if (currentOffset < 0)
2916 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002917
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2919 // but possibly not yet correctly aligned.
2920
2921 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002922 int dummyStride;
2923 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002924
2925 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002926 // TODO: make this consistent in early phases of code:
2927 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2928 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2929 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002930 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002931 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002932 int dummySize;
2933 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2934 if (componentAlignment <= 4)
2935 memberAlignment = componentAlignment;
2936 }
2937
2938 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002939 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002940
2941 // Bump up to vec4 if there is a bad straddle
2942 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2943 glslang::RoundToPow2(currentOffset, 16);
2944
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 nextOffset = currentOffset + memberSize;
2946}
2947
David Netoa901ffe2016-06-08 14:11:40 +01002948void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002949{
David Netoa901ffe2016-06-08 14:11:40 +01002950 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2951 switch (glslangBuiltIn)
2952 {
2953 case glslang::EbvClipDistance:
2954 case glslang::EbvCullDistance:
2955 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002956#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002957 case glslang::EbvViewportMaskNV:
2958 case glslang::EbvSecondaryPositionNV:
2959 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002960 case glslang::EbvPositionPerViewNV:
2961 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002962#endif
David Netoa901ffe2016-06-08 14:11:40 +01002963 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2964 // Alternately, we could just call this for any glslang built-in, since the
2965 // capability already guards against duplicates.
2966 TranslateBuiltInDecoration(glslangBuiltIn, false);
2967 break;
2968 default:
2969 // Capabilities were already generated when the struct was declared.
2970 break;
2971 }
John Kessenichebb50532016-05-16 19:22:05 -06002972}
2973
John Kessenich6fccb3c2016-09-19 16:01:41 -06002974bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002975{
John Kessenicheee9d532016-09-19 18:09:30 -06002976 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002977}
2978
John Kessenichd41993d2017-09-10 15:21:05 -06002979// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002980// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2981// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002982bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2983{
John Kessenich6a14f782017-12-04 02:48:10 -07002984 assert(qualifier == glslang::EvqIn ||
2985 qualifier == glslang::EvqOut ||
2986 qualifier == glslang::EvqInOut ||
2987 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002988 return qualifier != glslang::EvqConstReadOnly;
2989}
2990
2991// Is parameter pass-by-original?
2992bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2993 bool implicitThisParam)
2994{
2995 if (implicitThisParam) // implicit this
2996 return true;
2997 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07002998 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06002999 return paramType.containsOpaque() || // sampler, etc.
3000 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3001}
3002
John Kessenich140f3df2015-06-26 16:58:36 -06003003// Make all the functions, skeletally, without actually visiting their bodies.
3004void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3005{
John Kessenichfad62972017-07-18 02:35:46 -06003006 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3007 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3008 if (paramPrecision != spv::NoPrecision)
3009 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003010 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003011 };
3012
John Kessenich140f3df2015-06-26 16:58:36 -06003013 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3014 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003015 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003016 continue;
3017
3018 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003019 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003020 //
qining25262b32016-05-06 17:25:16 -04003021 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003022 // function. What it is an address of varies:
3023 //
John Kessenich4bf71552016-09-02 11:20:21 -06003024 // - "in" parameters not marked as "const" can be written to without modifying the calling
3025 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003026 //
3027 // - "const in" parameters can just be the r-value, as no writes need occur.
3028 //
John Kessenich4bf71552016-09-02 11:20:21 -06003029 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3030 // 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 -06003031
3032 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003033 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003034 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3035
John Kessenichfad62972017-07-18 02:35:46 -06003036 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3037 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003038
John Kessenichfad62972017-07-18 02:35:46 -06003039 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003040 for (int p = 0; p < (int)parameters.size(); ++p) {
3041 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3042 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003043 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003044 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003045 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003046 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3047 else
John Kessenich4bf71552016-09-02 11:20:21 -06003048 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003049 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003050 paramTypes.push_back(typeId);
3051 }
3052
3053 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003054 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3055 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003056 glslFunction->getName().c_str(), paramTypes,
3057 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003058 if (implicitThis)
3059 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003060
3061 // Track function to emit/call later
3062 functionMap[glslFunction->getName().c_str()] = function;
3063
3064 // Set the parameter id's
3065 for (int p = 0; p < (int)parameters.size(); ++p) {
3066 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3067 // give a name too
3068 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3069 }
3070 }
3071}
3072
3073// Process all the initializers, while skipping the functions and link objects
3074void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3075{
3076 builder.setBuildPoint(shaderEntry->getLastBlock());
3077 for (int i = 0; i < (int)initializers.size(); ++i) {
3078 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3079 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3080
3081 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003082 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003083 initializer->traverse(this);
3084 }
3085 }
3086}
3087
3088// Process all the functions, while skipping initializers.
3089void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3090{
3091 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3092 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003093 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003094 node->traverse(this);
3095 }
3096}
3097
3098void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3099{
qining25262b32016-05-06 17:25:16 -04003100 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003101 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003102 currentFunction = functionMap[node->getName().c_str()];
3103 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003104 builder.setBuildPoint(functionBlock);
3105}
3106
Rex Xu04db3f52015-09-16 11:44:02 +08003107void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003108{
Rex Xufc618912015-09-09 16:42:49 +08003109 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003110
3111 glslang::TSampler sampler = {};
3112 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003113 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003114 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3115 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3116 }
3117
John Kessenich140f3df2015-06-26 16:58:36 -06003118 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3119 builder.clearAccessChain();
3120 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003121
3122 // Special case l-value operands
3123 bool lvalue = false;
3124 switch (node.getOp()) {
3125 case glslang::EOpImageAtomicAdd:
3126 case glslang::EOpImageAtomicMin:
3127 case glslang::EOpImageAtomicMax:
3128 case glslang::EOpImageAtomicAnd:
3129 case glslang::EOpImageAtomicOr:
3130 case glslang::EOpImageAtomicXor:
3131 case glslang::EOpImageAtomicExchange:
3132 case glslang::EOpImageAtomicCompSwap:
3133 if (i == 0)
3134 lvalue = true;
3135 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003136 case glslang::EOpSparseImageLoad:
3137 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3138 lvalue = true;
3139 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003140 case glslang::EOpSparseTexture:
3141 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3142 lvalue = true;
3143 break;
3144 case glslang::EOpSparseTextureClamp:
3145 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3146 lvalue = true;
3147 break;
3148 case glslang::EOpSparseTextureLod:
3149 case glslang::EOpSparseTextureOffset:
3150 if (i == 3)
3151 lvalue = true;
3152 break;
3153 case glslang::EOpSparseTextureFetch:
3154 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3155 lvalue = true;
3156 break;
3157 case glslang::EOpSparseTextureFetchOffset:
3158 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3159 lvalue = true;
3160 break;
3161 case glslang::EOpSparseTextureLodOffset:
3162 case glslang::EOpSparseTextureGrad:
3163 case glslang::EOpSparseTextureOffsetClamp:
3164 if (i == 4)
3165 lvalue = true;
3166 break;
3167 case glslang::EOpSparseTextureGradOffset:
3168 case glslang::EOpSparseTextureGradClamp:
3169 if (i == 5)
3170 lvalue = true;
3171 break;
3172 case glslang::EOpSparseTextureGradOffsetClamp:
3173 if (i == 6)
3174 lvalue = true;
3175 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003176 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003177 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3178 lvalue = true;
3179 break;
3180 case glslang::EOpSparseTextureGatherOffset:
3181 case glslang::EOpSparseTextureGatherOffsets:
3182 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3183 lvalue = true;
3184 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003185#ifdef AMD_EXTENSIONS
3186 case glslang::EOpSparseTextureGatherLod:
3187 if (i == 3)
3188 lvalue = true;
3189 break;
3190 case glslang::EOpSparseTextureGatherLodOffset:
3191 case glslang::EOpSparseTextureGatherLodOffsets:
3192 if (i == 4)
3193 lvalue = true;
3194 break;
Rex Xu129799a2017-07-05 17:23:28 +08003195 case glslang::EOpSparseImageLoadLod:
3196 if (i == 3)
3197 lvalue = true;
3198 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003199#endif
Rex Xufc618912015-09-09 16:42:49 +08003200 default:
3201 break;
3202 }
3203
Rex Xu6b86d492015-09-16 17:48:22 +08003204 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003205 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003206 else
John Kessenich32cfd492016-02-02 12:37:46 -07003207 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003208 }
3209}
3210
John Kessenichfc51d282015-08-19 13:34:18 -06003211void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003212{
John Kessenichfc51d282015-08-19 13:34:18 -06003213 builder.clearAccessChain();
3214 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003215 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003216}
John Kessenich140f3df2015-06-26 16:58:36 -06003217
John Kessenichfc51d282015-08-19 13:34:18 -06003218spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3219{
John Kesseniche485c7a2017-05-31 18:50:53 -06003220 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003221 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003222
3223 builder.setLine(node->getLoc().line);
3224
John Kessenich8c8505c2016-07-26 12:50:38 -06003225 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003226
John Kessenichfc51d282015-08-19 13:34:18 -06003227 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003228 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3229 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3230 std::vector<spv::Id> arguments;
3231 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003232 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003233 else
3234 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003235 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003236
3237 spv::Builder::TextureParameters params = { };
3238 params.sampler = arguments[0];
3239
Rex Xu04db3f52015-09-16 11:44:02 +08003240 glslang::TCrackedTextureOp cracked;
3241 node->crackTexture(sampler, cracked);
3242
amhagan05506bb2017-06-13 16:53:02 -04003243 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003244
John Kessenichfc51d282015-08-19 13:34:18 -06003245 // Check for queries
3246 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003247 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3248 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003249 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003250
John Kessenichfc51d282015-08-19 13:34:18 -06003251 switch (node->getOp()) {
3252 case glslang::EOpImageQuerySize:
3253 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003254 if (arguments.size() > 1) {
3255 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003256 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003257 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003258 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003259 case glslang::EOpImageQuerySamples:
3260 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003261 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003262 case glslang::EOpTextureQueryLod:
3263 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003264 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003265 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003266 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003267 case glslang::EOpSparseTexelsResident:
3268 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003269 default:
3270 assert(0);
3271 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003272 }
John Kessenich140f3df2015-06-26 16:58:36 -06003273 }
3274
Rex Xufc618912015-09-09 16:42:49 +08003275 // Check for image functions other than queries
3276 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003277 std::vector<spv::Id> operands;
3278 auto opIt = arguments.begin();
3279 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003280
3281 // Handle subpass operations
3282 // TODO: GLSL should change to have the "MS" only on the type rather than the
3283 // built-in function.
3284 if (cracked.subpass) {
3285 // add on the (0,0) coordinate
3286 spv::Id zero = builder.makeIntConstant(0);
3287 std::vector<spv::Id> comps;
3288 comps.push_back(zero);
3289 comps.push_back(zero);
3290 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3291 if (sampler.ms) {
3292 operands.push_back(spv::ImageOperandsSampleMask);
3293 operands.push_back(*(opIt++));
3294 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003295 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3296 builder.setPrecision(result, precision);
3297 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003298 }
3299
John Kessenich56bab042015-09-16 10:54:31 -06003300 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003301#ifdef AMD_EXTENSIONS
3302 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3303#else
John Kessenich56bab042015-09-16 10:54:31 -06003304 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003305#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003306 if (sampler.ms) {
3307 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003308 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003309#ifdef AMD_EXTENSIONS
3310 } else if (cracked.lod) {
3311 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3312 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3313
3314 operands.push_back(spv::ImageOperandsLodMask);
3315 operands.push_back(*opIt);
3316#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003317 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003318 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3319 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003320
3321 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3322 builder.setPrecision(result, precision);
3323 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003324#ifdef AMD_EXTENSIONS
3325 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3326#else
John Kessenich56bab042015-09-16 10:54:31 -06003327 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003328#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003329 if (sampler.ms) {
3330 operands.push_back(*(opIt + 1));
3331 operands.push_back(spv::ImageOperandsSampleMask);
3332 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003333#ifdef AMD_EXTENSIONS
3334 } else if (cracked.lod) {
3335 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3336 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3337
3338 operands.push_back(*(opIt + 1));
3339 operands.push_back(spv::ImageOperandsLodMask);
3340 operands.push_back(*opIt);
3341#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003342 } else
3343 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003344 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003345 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3346 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003347 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003348#ifdef AMD_EXTENSIONS
3349 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3350#else
Rex Xu5eafa472016-02-19 22:24:03 +08003351 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003352#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003353 builder.addCapability(spv::CapabilitySparseResidency);
3354 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3355 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3356
3357 if (sampler.ms) {
3358 operands.push_back(spv::ImageOperandsSampleMask);
3359 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003360#ifdef AMD_EXTENSIONS
3361 } else if (cracked.lod) {
3362 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3363 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3364
3365 operands.push_back(spv::ImageOperandsLodMask);
3366 operands.push_back(*opIt++);
3367#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003368 }
3369
3370 // Create the return type that was a special structure
3371 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003372 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003373 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3374 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3375
3376 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3377
3378 // Decode the return type
3379 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3380 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003381 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003382 // Process image atomic operations
3383
3384 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3385 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003386 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003387
John Kessenich8c8505c2016-07-26 12:50:38 -06003388 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003389 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003390
3391 std::vector<spv::Id> operands;
3392 operands.push_back(pointer);
3393 for (; opIt != arguments.end(); ++opIt)
3394 operands.push_back(*opIt);
3395
John Kessenich8c8505c2016-07-26 12:50:38 -06003396 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003397 }
3398 }
3399
amhagan05506bb2017-06-13 16:53:02 -04003400#ifdef AMD_EXTENSIONS
3401 // Check for fragment mask functions other than queries
3402 if (cracked.fragMask) {
3403 assert(sampler.ms);
3404
3405 auto opIt = arguments.begin();
3406 std::vector<spv::Id> operands;
3407
3408 // Extract the image if necessary
3409 if (builder.isSampledImage(params.sampler))
3410 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3411
3412 operands.push_back(params.sampler);
3413 ++opIt;
3414
3415 if (sampler.isSubpass()) {
3416 // add on the (0,0) coordinate
3417 spv::Id zero = builder.makeIntConstant(0);
3418 std::vector<spv::Id> comps;
3419 comps.push_back(zero);
3420 comps.push_back(zero);
3421 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3422 }
3423
3424 for (; opIt != arguments.end(); ++opIt)
3425 operands.push_back(*opIt);
3426
3427 spv::Op fragMaskOp = spv::OpNop;
3428 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3429 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3430 else if (node->getOp() == glslang::EOpFragmentFetch)
3431 fragMaskOp = spv::OpFragmentFetchAMD;
3432
3433 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3434 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3435 return builder.createOp(fragMaskOp, resultType(), operands);
3436 }
3437#endif
3438
Rex Xufc618912015-09-09 16:42:49 +08003439 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003440 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003441 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3442
John Kessenichfc51d282015-08-19 13:34:18 -06003443 // check for bias argument
3444 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003445#ifdef AMD_EXTENSIONS
3446 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3447#else
Rex Xu71519fe2015-11-11 15:35:47 +08003448 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003449#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003450 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003451#ifdef AMD_EXTENSIONS
3452 if (cracked.gather)
3453 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3454#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003455 if (cracked.offset)
3456 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003457#ifdef AMD_EXTENSIONS
3458 else if (cracked.offsets)
3459 ++nonBiasArgCount;
3460#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003461 if (cracked.grad)
3462 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003463 if (cracked.lodClamp)
3464 ++nonBiasArgCount;
3465 if (sparse)
3466 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003467
3468 if ((int)arguments.size() > nonBiasArgCount)
3469 bias = true;
3470 }
3471
John Kessenicha5c33d62016-06-02 23:45:21 -06003472 // See if the sampler param should really be just the SPV image part
3473 if (cracked.fetch) {
3474 // a fetch needs to have the image extracted first
3475 if (builder.isSampledImage(params.sampler))
3476 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3477 }
3478
Rex Xu225e0fc2016-11-17 17:47:59 +08003479#ifdef AMD_EXTENSIONS
3480 if (cracked.gather) {
3481 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3482 if (bias || cracked.lod ||
3483 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3484 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003485 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003486 }
3487 }
3488#endif
3489
John Kessenichfc51d282015-08-19 13:34:18 -06003490 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003491
John Kessenichfc51d282015-08-19 13:34:18 -06003492 params.coords = arguments[1];
3493 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003494 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003495
3496 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003497 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003498 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003499 ++extraArgs;
3500 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003501 params.Dref = arguments[2];
3502 ++extraArgs;
3503 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003504 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003505 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003506 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003507 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003508 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003509 dRefComp = builder.getNumComponents(params.coords) - 1;
3510 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003511 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3512 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003513
3514 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003515 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003516 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003517 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003518 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3519 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3520 noImplicitLod = true;
3521 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003522
3523 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003524 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003525 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003526 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003527 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003528
3529 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003530 if (cracked.grad) {
3531 params.gradX = arguments[2 + extraArgs];
3532 params.gradY = arguments[3 + extraArgs];
3533 extraArgs += 2;
3534 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003535
3536 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003537 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003538 params.offset = arguments[2 + extraArgs];
3539 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003540 } else if (cracked.offsets) {
3541 params.offsets = arguments[2 + extraArgs];
3542 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003543 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003544
3545 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003546 if (cracked.lodClamp) {
3547 params.lodClamp = arguments[2 + extraArgs];
3548 ++extraArgs;
3549 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003550
3551 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003552 if (sparse) {
3553 params.texelOut = arguments[2 + extraArgs];
3554 ++extraArgs;
3555 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003556
John Kessenich76d4dfc2016-06-16 12:43:23 -06003557 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003558 if (cracked.gather && ! sampler.shadow) {
3559 // default component is 0, if missing, otherwise an argument
3560 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003561 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003562 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003563 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003564 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003565 }
3566
3567 // bias
3568 if (bias) {
3569 params.bias = arguments[2 + extraArgs];
3570 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003571 }
John Kessenichfc51d282015-08-19 13:34:18 -06003572
John Kessenich65336482016-06-16 14:06:26 -06003573 // projective component (might not to move)
3574 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3575 // are divided by the last component of P."
3576 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3577 // unused components will appear after all used components."
3578 if (cracked.proj) {
3579 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3580 int projTargetComp;
3581 switch (sampler.dim) {
3582 case glslang::Esd1D: projTargetComp = 1; break;
3583 case glslang::Esd2D: projTargetComp = 2; break;
3584 case glslang::EsdRect: projTargetComp = 2; break;
3585 default: projTargetComp = projSourceComp; break;
3586 }
3587 // copy the projective coordinate if we have to
3588 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003589 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003590 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3591 projSourceComp);
3592 params.coords = builder.createCompositeInsert(projComp, params.coords,
3593 builder.getTypeId(params.coords), projTargetComp);
3594 }
3595 }
3596
John Kessenich8c8505c2016-07-26 12:50:38 -06003597 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003598}
3599
3600spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3601{
3602 // Grab the function's pointer from the previously created function
3603 spv::Function* function = functionMap[node->getName().c_str()];
3604 if (! function)
3605 return 0;
3606
3607 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3608 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3609
3610 // See comments in makeFunctions() for details about the semantics for parameter passing.
3611 //
3612 // These imply we need a four step process:
3613 // 1. Evaluate the arguments
3614 // 2. Allocate and make copies of in, out, and inout arguments
3615 // 3. Make the call
3616 // 4. Copy back the results
3617
3618 // 1. Evaluate the arguments
3619 std::vector<spv::Builder::AccessChain> lValues;
3620 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003621 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003622 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003623 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003624 // build l-value
3625 builder.clearAccessChain();
3626 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003627 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003628 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003629 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3630 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003631 // save l-value
3632 lValues.push_back(builder.getAccessChain());
3633 } else {
3634 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003635 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003636 }
3637 }
3638
3639 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3640 // copy the original into that space.
3641 //
3642 // Also, build up the list of actual arguments to pass in for the call
3643 int lValueCount = 0;
3644 int rValueCount = 0;
3645 std::vector<spv::Id> spvArgs;
3646 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003647 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003648 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003649 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003650 builder.setAccessChain(lValues[lValueCount]);
3651 arg = builder.accessChainGetLValue();
3652 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003653 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003654 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003655 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3656 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3657 // need to copy the input into output space
3658 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003659 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003660 builder.clearAccessChain();
3661 builder.setAccessChainLValue(arg);
3662 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003663 }
3664 ++lValueCount;
3665 } else {
3666 arg = rValues[rValueCount];
3667 ++rValueCount;
3668 }
3669 spvArgs.push_back(arg);
3670 }
3671
3672 // 3. Make the call.
3673 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003674 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003675
3676 // 4. Copy back out an "out" arguments.
3677 lValueCount = 0;
3678 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003679 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003680 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3681 ++lValueCount;
3682 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003683 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3684 spv::Id copy = builder.createLoad(spvArgs[a]);
3685 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003686 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003687 }
3688 ++lValueCount;
3689 }
3690 }
3691
3692 return result;
3693}
3694
3695// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003696spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3697 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003698 spv::Id typeId, spv::Id left, spv::Id right,
3699 glslang::TBasicType typeProxy, bool reduceComparison)
3700{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003701#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003702 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003703 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3704#else
Rex Xucabbb782017-03-24 13:41:14 +08003705 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003707#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003708 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003709
3710 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003711 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003712 bool comparison = false;
3713
3714 switch (op) {
3715 case glslang::EOpAdd:
3716 case glslang::EOpAddAssign:
3717 if (isFloat)
3718 binOp = spv::OpFAdd;
3719 else
3720 binOp = spv::OpIAdd;
3721 break;
3722 case glslang::EOpSub:
3723 case glslang::EOpSubAssign:
3724 if (isFloat)
3725 binOp = spv::OpFSub;
3726 else
3727 binOp = spv::OpISub;
3728 break;
3729 case glslang::EOpMul:
3730 case glslang::EOpMulAssign:
3731 if (isFloat)
3732 binOp = spv::OpFMul;
3733 else
3734 binOp = spv::OpIMul;
3735 break;
3736 case glslang::EOpVectorTimesScalar:
3737 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003738 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003739 if (builder.isVector(right))
3740 std::swap(left, right);
3741 assert(builder.isScalar(right));
3742 needMatchingVectors = false;
3743 binOp = spv::OpVectorTimesScalar;
3744 } else
3745 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747 case glslang::EOpVectorTimesMatrix:
3748 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003749 binOp = spv::OpVectorTimesMatrix;
3750 break;
3751 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003752 binOp = spv::OpMatrixTimesVector;
3753 break;
3754 case glslang::EOpMatrixTimesScalar:
3755 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003756 binOp = spv::OpMatrixTimesScalar;
3757 break;
3758 case glslang::EOpMatrixTimesMatrix:
3759 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003760 binOp = spv::OpMatrixTimesMatrix;
3761 break;
3762 case glslang::EOpOuterProduct:
3763 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003764 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766
3767 case glslang::EOpDiv:
3768 case glslang::EOpDivAssign:
3769 if (isFloat)
3770 binOp = spv::OpFDiv;
3771 else if (isUnsigned)
3772 binOp = spv::OpUDiv;
3773 else
3774 binOp = spv::OpSDiv;
3775 break;
3776 case glslang::EOpMod:
3777 case glslang::EOpModAssign:
3778 if (isFloat)
3779 binOp = spv::OpFMod;
3780 else if (isUnsigned)
3781 binOp = spv::OpUMod;
3782 else
3783 binOp = spv::OpSMod;
3784 break;
3785 case glslang::EOpRightShift:
3786 case glslang::EOpRightShiftAssign:
3787 if (isUnsigned)
3788 binOp = spv::OpShiftRightLogical;
3789 else
3790 binOp = spv::OpShiftRightArithmetic;
3791 break;
3792 case glslang::EOpLeftShift:
3793 case glslang::EOpLeftShiftAssign:
3794 binOp = spv::OpShiftLeftLogical;
3795 break;
3796 case glslang::EOpAnd:
3797 case glslang::EOpAndAssign:
3798 binOp = spv::OpBitwiseAnd;
3799 break;
3800 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003801 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003802 binOp = spv::OpLogicalAnd;
3803 break;
3804 case glslang::EOpInclusiveOr:
3805 case glslang::EOpInclusiveOrAssign:
3806 binOp = spv::OpBitwiseOr;
3807 break;
3808 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003809 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 binOp = spv::OpLogicalOr;
3811 break;
3812 case glslang::EOpExclusiveOr:
3813 case glslang::EOpExclusiveOrAssign:
3814 binOp = spv::OpBitwiseXor;
3815 break;
3816 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003817 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003818 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820
3821 case glslang::EOpLessThan:
3822 case glslang::EOpGreaterThan:
3823 case glslang::EOpLessThanEqual:
3824 case glslang::EOpGreaterThanEqual:
3825 case glslang::EOpEqual:
3826 case glslang::EOpNotEqual:
3827 case glslang::EOpVectorEqual:
3828 case glslang::EOpVectorNotEqual:
3829 comparison = true;
3830 break;
3831 default:
3832 break;
3833 }
3834
John Kessenich7c1aa102015-10-15 13:29:11 -06003835 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003836 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003837 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003838 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003839 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003840
3841 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003842 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003843 builder.promoteScalar(precision, left, right);
3844
qining25262b32016-05-06 17:25:16 -04003845 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3846 addDecoration(result, noContraction);
3847 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003848 }
3849
3850 if (! comparison)
3851 return 0;
3852
John Kessenich7c1aa102015-10-15 13:29:11 -06003853 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003854
John Kessenich4583b612016-08-07 19:14:22 -06003855 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3856 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003857 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003858
3859 switch (op) {
3860 case glslang::EOpLessThan:
3861 if (isFloat)
3862 binOp = spv::OpFOrdLessThan;
3863 else if (isUnsigned)
3864 binOp = spv::OpULessThan;
3865 else
3866 binOp = spv::OpSLessThan;
3867 break;
3868 case glslang::EOpGreaterThan:
3869 if (isFloat)
3870 binOp = spv::OpFOrdGreaterThan;
3871 else if (isUnsigned)
3872 binOp = spv::OpUGreaterThan;
3873 else
3874 binOp = spv::OpSGreaterThan;
3875 break;
3876 case glslang::EOpLessThanEqual:
3877 if (isFloat)
3878 binOp = spv::OpFOrdLessThanEqual;
3879 else if (isUnsigned)
3880 binOp = spv::OpULessThanEqual;
3881 else
3882 binOp = spv::OpSLessThanEqual;
3883 break;
3884 case glslang::EOpGreaterThanEqual:
3885 if (isFloat)
3886 binOp = spv::OpFOrdGreaterThanEqual;
3887 else if (isUnsigned)
3888 binOp = spv::OpUGreaterThanEqual;
3889 else
3890 binOp = spv::OpSGreaterThanEqual;
3891 break;
3892 case glslang::EOpEqual:
3893 case glslang::EOpVectorEqual:
3894 if (isFloat)
3895 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003896 else if (isBool)
3897 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003898 else
3899 binOp = spv::OpIEqual;
3900 break;
3901 case glslang::EOpNotEqual:
3902 case glslang::EOpVectorNotEqual:
3903 if (isFloat)
3904 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003905 else if (isBool)
3906 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003907 else
3908 binOp = spv::OpINotEqual;
3909 break;
3910 default:
3911 break;
3912 }
3913
qining25262b32016-05-06 17:25:16 -04003914 if (binOp != spv::OpNop) {
3915 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3916 addDecoration(result, noContraction);
3917 return builder.setPrecision(result, precision);
3918 }
John Kessenich140f3df2015-06-26 16:58:36 -06003919
3920 return 0;
3921}
3922
John Kessenich04bb8a02015-12-12 12:28:14 -07003923//
3924// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3925// These can be any of:
3926//
3927// matrix * scalar
3928// scalar * matrix
3929// matrix * matrix linear algebraic
3930// matrix * vector
3931// vector * matrix
3932// matrix * matrix componentwise
3933// matrix op matrix op in {+, -, /}
3934// matrix op scalar op in {+, -, /}
3935// scalar op matrix op in {+, -, /}
3936//
qining25262b32016-05-06 17:25:16 -04003937spv::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 -07003938{
3939 bool firstClass = true;
3940
3941 // First, handle first-class matrix operations (* and matrix/scalar)
3942 switch (op) {
3943 case spv::OpFDiv:
3944 if (builder.isMatrix(left) && builder.isScalar(right)) {
3945 // turn matrix / scalar into a multiply...
3946 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3947 op = spv::OpMatrixTimesScalar;
3948 } else
3949 firstClass = false;
3950 break;
3951 case spv::OpMatrixTimesScalar:
3952 if (builder.isMatrix(right))
3953 std::swap(left, right);
3954 assert(builder.isScalar(right));
3955 break;
3956 case spv::OpVectorTimesMatrix:
3957 assert(builder.isVector(left));
3958 assert(builder.isMatrix(right));
3959 break;
3960 case spv::OpMatrixTimesVector:
3961 assert(builder.isMatrix(left));
3962 assert(builder.isVector(right));
3963 break;
3964 case spv::OpMatrixTimesMatrix:
3965 assert(builder.isMatrix(left));
3966 assert(builder.isMatrix(right));
3967 break;
3968 default:
3969 firstClass = false;
3970 break;
3971 }
3972
qining25262b32016-05-06 17:25:16 -04003973 if (firstClass) {
3974 spv::Id result = builder.createBinOp(op, typeId, left, right);
3975 addDecoration(result, noContraction);
3976 return builder.setPrecision(result, precision);
3977 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003978
LoopDawg592860c2016-06-09 08:57:35 -06003979 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003980 // The result type of all of them is the same type as the (a) matrix operand.
3981 // The algorithm is to:
3982 // - break the matrix(es) into vectors
3983 // - smear any scalar to a vector
3984 // - do vector operations
3985 // - make a matrix out the vector results
3986 switch (op) {
3987 case spv::OpFAdd:
3988 case spv::OpFSub:
3989 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003990 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003991 case spv::OpFMul:
3992 {
3993 // one time set up...
3994 bool leftMat = builder.isMatrix(left);
3995 bool rightMat = builder.isMatrix(right);
3996 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3997 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3998 spv::Id scalarType = builder.getScalarTypeId(typeId);
3999 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4000 std::vector<spv::Id> results;
4001 spv::Id smearVec = spv::NoResult;
4002 if (builder.isScalar(left))
4003 smearVec = builder.smearScalar(precision, left, vecType);
4004 else if (builder.isScalar(right))
4005 smearVec = builder.smearScalar(precision, right, vecType);
4006
4007 // do each vector op
4008 for (unsigned int c = 0; c < numCols; ++c) {
4009 std::vector<unsigned int> indexes;
4010 indexes.push_back(c);
4011 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4012 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004013 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4014 addDecoration(result, noContraction);
4015 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004016 }
4017
4018 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004019 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004020 }
4021 default:
4022 assert(0);
4023 return spv::NoResult;
4024 }
4025}
4026
qining25262b32016-05-06 17:25:16 -04004027spv::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 -06004028{
4029 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004030 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004031 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004032#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004033 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004034 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4035#else
Rex Xucabbb782017-03-24 13:41:14 +08004036 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004037 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004038#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004039
4040 switch (op) {
4041 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004042 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004043 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004044 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004045 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004046 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004047 unaryOp = spv::OpSNegate;
4048 break;
4049
4050 case glslang::EOpLogicalNot:
4051 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 unaryOp = spv::OpLogicalNot;
4053 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 case glslang::EOpBitwiseNot:
4055 unaryOp = spv::OpNot;
4056 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004057
John Kessenich140f3df2015-06-26 16:58:36 -06004058 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpTranspose:
4065 unaryOp = spv::OpTranspose;
4066 break;
4067
4068 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004069 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004070 break;
4071 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004072 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
4077 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092
4093 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004094 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004095 break;
4096 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 break;
4105 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004106 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004107 break;
4108 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004110 break;
4111
4112 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118
4119 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
4128 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137
4138 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004142 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004145 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004146 break;
4147 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004148 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004154 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004155 break;
4156
4157 case glslang::EOpIsNan:
4158 unaryOp = spv::OpIsNan;
4159 break;
4160 case glslang::EOpIsInf:
4161 unaryOp = spv::OpIsInf;
4162 break;
LoopDawg592860c2016-06-09 08:57:35 -06004163 case glslang::EOpIsFinite:
4164 unaryOp = spv::OpIsFinite;
4165 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004166
Rex Xucbc426e2015-12-15 16:03:10 +08004167 case glslang::EOpFloatBitsToInt:
4168 case glslang::EOpFloatBitsToUint:
4169 case glslang::EOpIntBitsToFloat:
4170 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004171 case glslang::EOpDoubleBitsToInt64:
4172 case glslang::EOpDoubleBitsToUint64:
4173 case glslang::EOpInt64BitsToDouble:
4174 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004175#ifdef AMD_EXTENSIONS
4176 case glslang::EOpFloat16BitsToInt16:
4177 case glslang::EOpFloat16BitsToUint16:
4178 case glslang::EOpInt16BitsToFloat16:
4179 case glslang::EOpUint16BitsToFloat16:
4180#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004181 unaryOp = spv::OpBitcast;
4182 break;
4183
John Kessenich140f3df2015-06-26 16:58:36 -06004184 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004185 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
4187 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004188 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004189 break;
4190 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004191 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004192 break;
4193 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004194 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004195 break;
4196 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004197 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004198 break;
4199 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004200 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004201 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004202 case glslang::EOpPackSnorm4x8:
4203 libCall = spv::GLSLstd450PackSnorm4x8;
4204 break;
4205 case glslang::EOpUnpackSnorm4x8:
4206 libCall = spv::GLSLstd450UnpackSnorm4x8;
4207 break;
4208 case glslang::EOpPackUnorm4x8:
4209 libCall = spv::GLSLstd450PackUnorm4x8;
4210 break;
4211 case glslang::EOpUnpackUnorm4x8:
4212 libCall = spv::GLSLstd450UnpackUnorm4x8;
4213 break;
4214 case glslang::EOpPackDouble2x32:
4215 libCall = spv::GLSLstd450PackDouble2x32;
4216 break;
4217 case glslang::EOpUnpackDouble2x32:
4218 libCall = spv::GLSLstd450UnpackDouble2x32;
4219 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004220
Rex Xu8ff43de2016-04-22 16:51:45 +08004221 case glslang::EOpPackInt2x32:
4222 case glslang::EOpUnpackInt2x32:
4223 case glslang::EOpPackUint2x32:
4224 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004225 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004226 break;
4227
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004228#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004229 case glslang::EOpPackInt2x16:
4230 case glslang::EOpUnpackInt2x16:
4231 case glslang::EOpPackUint2x16:
4232 case glslang::EOpUnpackUint2x16:
4233 case glslang::EOpPackInt4x16:
4234 case glslang::EOpUnpackInt4x16:
4235 case glslang::EOpPackUint4x16:
4236 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004237 case glslang::EOpPackFloat2x16:
4238 case glslang::EOpUnpackFloat2x16:
4239 unaryOp = spv::OpBitcast;
4240 break;
4241#endif
4242
John Kessenich140f3df2015-06-26 16:58:36 -06004243 case glslang::EOpDPdx:
4244 unaryOp = spv::OpDPdx;
4245 break;
4246 case glslang::EOpDPdy:
4247 unaryOp = spv::OpDPdy;
4248 break;
4249 case glslang::EOpFwidth:
4250 unaryOp = spv::OpFwidth;
4251 break;
4252 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004253 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004254 unaryOp = spv::OpDPdxFine;
4255 break;
4256 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004257 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004258 unaryOp = spv::OpDPdyFine;
4259 break;
4260 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004261 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004262 unaryOp = spv::OpFwidthFine;
4263 break;
4264 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004265 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004266 unaryOp = spv::OpDPdxCoarse;
4267 break;
4268 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004269 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004270 unaryOp = spv::OpDPdyCoarse;
4271 break;
4272 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004273 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004274 unaryOp = spv::OpFwidthCoarse;
4275 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004276 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004277 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004278 libCall = spv::GLSLstd450InterpolateAtCentroid;
4279 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004280 case glslang::EOpAny:
4281 unaryOp = spv::OpAny;
4282 break;
4283 case glslang::EOpAll:
4284 unaryOp = spv::OpAll;
4285 break;
4286
4287 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004288 if (isFloat)
4289 libCall = spv::GLSLstd450FAbs;
4290 else
4291 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004292 break;
4293 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004294 if (isFloat)
4295 libCall = spv::GLSLstd450FSign;
4296 else
4297 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004298 break;
4299
John Kessenichfc51d282015-08-19 13:34:18 -06004300 case glslang::EOpAtomicCounterIncrement:
4301 case glslang::EOpAtomicCounterDecrement:
4302 case glslang::EOpAtomicCounter:
4303 {
4304 // Handle all of the atomics in one place, in createAtomicOperation()
4305 std::vector<spv::Id> operands;
4306 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004307 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004308 }
4309
John Kessenichfc51d282015-08-19 13:34:18 -06004310 case glslang::EOpBitFieldReverse:
4311 unaryOp = spv::OpBitReverse;
4312 break;
4313 case glslang::EOpBitCount:
4314 unaryOp = spv::OpBitCount;
4315 break;
4316 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004317 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004318 break;
4319 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004320 if (isUnsigned)
4321 libCall = spv::GLSLstd450FindUMsb;
4322 else
4323 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004324 break;
4325
Rex Xu574ab042016-04-14 16:53:07 +08004326 case glslang::EOpBallot:
4327 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004328 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004329 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004330 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004331#ifdef AMD_EXTENSIONS
4332 case glslang::EOpMinInvocations:
4333 case glslang::EOpMaxInvocations:
4334 case glslang::EOpAddInvocations:
4335 case glslang::EOpMinInvocationsNonUniform:
4336 case glslang::EOpMaxInvocationsNonUniform:
4337 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004338 case glslang::EOpMinInvocationsInclusiveScan:
4339 case glslang::EOpMaxInvocationsInclusiveScan:
4340 case glslang::EOpAddInvocationsInclusiveScan:
4341 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4342 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4343 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4344 case glslang::EOpMinInvocationsExclusiveScan:
4345 case glslang::EOpMaxInvocationsExclusiveScan:
4346 case glslang::EOpAddInvocationsExclusiveScan:
4347 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4348 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4349 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004350#endif
Rex Xu51596642016-09-21 18:56:12 +08004351 {
4352 std::vector<spv::Id> operands;
4353 operands.push_back(operand);
4354 return createInvocationsOperation(op, typeId, operands, typeProxy);
4355 }
Rex Xu9d93a232016-05-05 12:30:44 +08004356
4357#ifdef AMD_EXTENSIONS
4358 case glslang::EOpMbcnt:
4359 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4360 libCall = spv::MbcntAMD;
4361 break;
4362
4363 case glslang::EOpCubeFaceIndex:
4364 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4365 libCall = spv::CubeFaceIndexAMD;
4366 break;
4367
4368 case glslang::EOpCubeFaceCoord:
4369 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4370 libCall = spv::CubeFaceCoordAMD;
4371 break;
4372#endif
Rex Xu338b1852016-05-05 20:38:33 +08004373
John Kessenich140f3df2015-06-26 16:58:36 -06004374 default:
4375 return 0;
4376 }
4377
4378 spv::Id id;
4379 if (libCall >= 0) {
4380 std::vector<spv::Id> args;
4381 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004382 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004383 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004384 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004385 }
John Kessenich140f3df2015-06-26 16:58:36 -06004386
qining25262b32016-05-06 17:25:16 -04004387 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004388 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004389}
4390
John Kessenich7a53f762016-01-20 11:19:27 -07004391// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004392spv::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 -07004393{
4394 // Handle unary operations vector by vector.
4395 // The result type is the same type as the original type.
4396 // The algorithm is to:
4397 // - break the matrix into vectors
4398 // - apply the operation to each vector
4399 // - make a matrix out the vector results
4400
4401 // get the types sorted out
4402 int numCols = builder.getNumColumns(operand);
4403 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004404 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4405 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004406 std::vector<spv::Id> results;
4407
4408 // do each vector op
4409 for (int c = 0; c < numCols; ++c) {
4410 std::vector<unsigned int> indexes;
4411 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004412 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4413 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4414 addDecoration(destVec, noContraction);
4415 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004416 }
4417
4418 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004419 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004420}
4421
Rex Xu73e3ce72016-04-27 18:48:17 +08004422spv::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 -06004423{
4424 spv::Op convOp = spv::OpNop;
4425 spv::Id zero = 0;
4426 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004427 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004428
4429 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4430
4431 switch (op) {
4432 case glslang::EOpConvIntToBool:
4433 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004434 case glslang::EOpConvInt64ToBool:
4435 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004436#ifdef AMD_EXTENSIONS
4437 case glslang::EOpConvInt16ToBool:
4438 case glslang::EOpConvUint16ToBool:
4439#endif
4440 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4441 zero = builder.makeUint64Constant(0);
4442#ifdef AMD_EXTENSIONS
4443 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4444 zero = builder.makeUint16Constant(0);
4445#endif
4446 else
4447 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004448 zero = makeSmearedConstant(zero, vectorSize);
4449 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4450
4451 case glslang::EOpConvFloatToBool:
4452 zero = builder.makeFloatConstant(0.0F);
4453 zero = makeSmearedConstant(zero, vectorSize);
4454 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4455
4456 case glslang::EOpConvDoubleToBool:
4457 zero = builder.makeDoubleConstant(0.0);
4458 zero = makeSmearedConstant(zero, vectorSize);
4459 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4460
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004461#ifdef AMD_EXTENSIONS
4462 case glslang::EOpConvFloat16ToBool:
4463 zero = builder.makeFloat16Constant(0.0F);
4464 zero = makeSmearedConstant(zero, vectorSize);
4465 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4466#endif
4467
John Kessenich140f3df2015-06-26 16:58:36 -06004468 case glslang::EOpConvBoolToFloat:
4469 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004470 zero = builder.makeFloatConstant(0.0F);
4471 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004472 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004473
John Kessenich140f3df2015-06-26 16:58:36 -06004474 case glslang::EOpConvBoolToDouble:
4475 convOp = spv::OpSelect;
4476 zero = builder.makeDoubleConstant(0.0);
4477 one = builder.makeDoubleConstant(1.0);
4478 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004479
4480#ifdef AMD_EXTENSIONS
4481 case glslang::EOpConvBoolToFloat16:
4482 convOp = spv::OpSelect;
4483 zero = builder.makeFloat16Constant(0.0F);
4484 one = builder.makeFloat16Constant(1.0F);
4485 break;
4486#endif
4487
John Kessenich140f3df2015-06-26 16:58:36 -06004488 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004489 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004490#ifdef AMD_EXTENSIONS
4491 case glslang::EOpConvBoolToInt16:
4492#endif
4493 if (op == glslang::EOpConvBoolToInt64)
4494 zero = builder.makeInt64Constant(0);
4495#ifdef AMD_EXTENSIONS
4496 else if (op == glslang::EOpConvBoolToInt16)
4497 zero = builder.makeInt16Constant(0);
4498#endif
4499 else
4500 zero = builder.makeIntConstant(0);
4501
4502 if (op == glslang::EOpConvBoolToInt64)
4503 one = builder.makeInt64Constant(1);
4504#ifdef AMD_EXTENSIONS
4505 else if (op == glslang::EOpConvBoolToInt16)
4506 one = builder.makeInt16Constant(1);
4507#endif
4508 else
4509 one = builder.makeIntConstant(1);
4510
John Kessenich140f3df2015-06-26 16:58:36 -06004511 convOp = spv::OpSelect;
4512 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004513
John Kessenich140f3df2015-06-26 16:58:36 -06004514 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004515 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004516#ifdef AMD_EXTENSIONS
4517 case glslang::EOpConvBoolToUint16:
4518#endif
4519 if (op == glslang::EOpConvBoolToUint64)
4520 zero = builder.makeUint64Constant(0);
4521#ifdef AMD_EXTENSIONS
4522 else if (op == glslang::EOpConvBoolToUint16)
4523 zero = builder.makeUint16Constant(0);
4524#endif
4525 else
4526 zero = builder.makeUintConstant(0);
4527
4528 if (op == glslang::EOpConvBoolToUint64)
4529 one = builder.makeUint64Constant(1);
4530#ifdef AMD_EXTENSIONS
4531 else if (op == glslang::EOpConvBoolToUint16)
4532 one = builder.makeUint16Constant(1);
4533#endif
4534 else
4535 one = builder.makeUintConstant(1);
4536
John Kessenich140f3df2015-06-26 16:58:36 -06004537 convOp = spv::OpSelect;
4538 break;
4539
4540 case glslang::EOpConvIntToFloat:
4541 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004542 case glslang::EOpConvInt64ToFloat:
4543 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004544#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004545 case glslang::EOpConvInt16ToFloat:
4546 case glslang::EOpConvInt16ToDouble:
4547 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004548 case glslang::EOpConvIntToFloat16:
4549 case glslang::EOpConvInt64ToFloat16:
4550#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004551 convOp = spv::OpConvertSToF;
4552 break;
4553
4554 case glslang::EOpConvUintToFloat:
4555 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004556 case glslang::EOpConvUint64ToFloat:
4557 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004558#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004559 case glslang::EOpConvUint16ToFloat:
4560 case glslang::EOpConvUint16ToDouble:
4561 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004562 case glslang::EOpConvUintToFloat16:
4563 case glslang::EOpConvUint64ToFloat16:
4564#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004565 convOp = spv::OpConvertUToF;
4566 break;
4567
4568 case glslang::EOpConvDoubleToFloat:
4569 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004570#ifdef AMD_EXTENSIONS
4571 case glslang::EOpConvDoubleToFloat16:
4572 case glslang::EOpConvFloat16ToDouble:
4573 case glslang::EOpConvFloatToFloat16:
4574 case glslang::EOpConvFloat16ToFloat:
4575#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004576 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004577 if (builder.isMatrixType(destType))
4578 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004579 break;
4580
4581 case glslang::EOpConvFloatToInt:
4582 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004583 case glslang::EOpConvFloatToInt64:
4584 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004585#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004586 case glslang::EOpConvFloatToInt16:
4587 case glslang::EOpConvDoubleToInt16:
4588 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004589 case glslang::EOpConvFloat16ToInt:
4590 case glslang::EOpConvFloat16ToInt64:
4591#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004592 convOp = spv::OpConvertFToS;
4593 break;
4594
4595 case glslang::EOpConvUintToInt:
4596 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004597 case glslang::EOpConvUint64ToInt64:
4598 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004599#ifdef AMD_EXTENSIONS
4600 case glslang::EOpConvUint16ToInt16:
4601 case glslang::EOpConvInt16ToUint16:
4602#endif
qininge24aa5e2016-04-07 15:40:27 -04004603 if (builder.isInSpecConstCodeGenMode()) {
4604 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004605 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4606 zero = builder.makeUint64Constant(0);
4607#ifdef AMD_EXTENSIONS
4608 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4609 zero = builder.makeUint16Constant(0);
4610#endif
4611 else
4612 zero = builder.makeUintConstant(0);
4613
qining189b2032016-04-12 23:16:20 -04004614 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004615 // Use OpIAdd, instead of OpBitcast to do the conversion when
4616 // generating for OpSpecConstantOp instruction.
4617 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4618 }
4619 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004620 convOp = spv::OpBitcast;
4621 break;
4622
4623 case glslang::EOpConvFloatToUint:
4624 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004625 case glslang::EOpConvFloatToUint64:
4626 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004627#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004628 case glslang::EOpConvFloatToUint16:
4629 case glslang::EOpConvDoubleToUint16:
4630 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004631 case glslang::EOpConvFloat16ToUint:
4632 case glslang::EOpConvFloat16ToUint64:
4633#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004634 convOp = spv::OpConvertFToU;
4635 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004636
4637 case glslang::EOpConvIntToInt64:
4638 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004639#ifdef AMD_EXTENSIONS
4640 case glslang::EOpConvIntToInt16:
4641 case glslang::EOpConvInt16ToInt:
4642 case glslang::EOpConvInt64ToInt16:
4643 case glslang::EOpConvInt16ToInt64:
4644#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004645 convOp = spv::OpSConvert;
4646 break;
4647
4648 case glslang::EOpConvUintToUint64:
4649 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004650#ifdef AMD_EXTENSIONS
4651 case glslang::EOpConvUintToUint16:
4652 case glslang::EOpConvUint16ToUint:
4653 case glslang::EOpConvUint64ToUint16:
4654 case glslang::EOpConvUint16ToUint64:
4655#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004656 convOp = spv::OpUConvert;
4657 break;
4658
4659 case glslang::EOpConvIntToUint64:
4660 case glslang::EOpConvInt64ToUint:
4661 case glslang::EOpConvUint64ToInt:
4662 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004663#ifdef AMD_EXTENSIONS
4664 case glslang::EOpConvInt16ToUint:
4665 case glslang::EOpConvUintToInt16:
4666 case glslang::EOpConvInt16ToUint64:
4667 case glslang::EOpConvUint64ToInt16:
4668 case glslang::EOpConvUint16ToInt:
4669 case glslang::EOpConvIntToUint16:
4670 case glslang::EOpConvUint16ToInt64:
4671 case glslang::EOpConvInt64ToUint16:
4672#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004673 // OpSConvert/OpUConvert + OpBitCast
4674 switch (op) {
4675 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004676#ifdef AMD_EXTENSIONS
4677 case glslang::EOpConvInt16ToUint64:
4678#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004679 convOp = spv::OpSConvert;
4680 type = builder.makeIntType(64);
4681 break;
4682 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004683#ifdef AMD_EXTENSIONS
4684 case glslang::EOpConvInt16ToUint:
4685#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004686 convOp = spv::OpSConvert;
4687 type = builder.makeIntType(32);
4688 break;
4689 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004690#ifdef AMD_EXTENSIONS
4691 case glslang::EOpConvUint16ToInt:
4692#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004693 convOp = spv::OpUConvert;
4694 type = builder.makeUintType(32);
4695 break;
4696 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004697#ifdef AMD_EXTENSIONS
4698 case glslang::EOpConvUint16ToInt64:
4699#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004700 convOp = spv::OpUConvert;
4701 type = builder.makeUintType(64);
4702 break;
Rex Xucabbb782017-03-24 13:41:14 +08004703#ifdef AMD_EXTENSIONS
4704 case glslang::EOpConvUintToInt16:
4705 case glslang::EOpConvUint64ToInt16:
4706 convOp = spv::OpUConvert;
4707 type = builder.makeUintType(16);
4708 break;
4709 case glslang::EOpConvIntToUint16:
4710 case glslang::EOpConvInt64ToUint16:
4711 convOp = spv::OpSConvert;
4712 type = builder.makeIntType(16);
4713 break;
4714#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004715 default:
4716 assert(0);
4717 break;
4718 }
4719
4720 if (vectorSize > 0)
4721 type = builder.makeVectorType(type, vectorSize);
4722
4723 operand = builder.createUnaryOp(convOp, type, operand);
4724
4725 if (builder.isInSpecConstCodeGenMode()) {
4726 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004727#ifdef AMD_EXTENSIONS
4728 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4729 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4730 zero = builder.makeUint64Constant(0);
4731 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4732 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4733 zero = builder.makeUint16Constant(0);
4734 else
4735 zero = builder.makeUintConstant(0);
4736#else
4737 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4738 zero = builder.makeUint64Constant(0);
4739 else
4740 zero = builder.makeUintConstant(0);
4741#endif
4742
Rex Xu8ff43de2016-04-22 16:51:45 +08004743 zero = makeSmearedConstant(zero, vectorSize);
4744 // Use OpIAdd, instead of OpBitcast to do the conversion when
4745 // generating for OpSpecConstantOp instruction.
4746 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4747 }
4748 // For normal run-time conversion instruction, use OpBitcast.
4749 convOp = spv::OpBitcast;
4750 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004751 default:
4752 break;
4753 }
4754
4755 spv::Id result = 0;
4756 if (convOp == spv::OpNop)
4757 return result;
4758
4759 if (convOp == spv::OpSelect) {
4760 zero = makeSmearedConstant(zero, vectorSize);
4761 one = makeSmearedConstant(one, vectorSize);
4762 result = builder.createTriOp(convOp, destType, operand, one, zero);
4763 } else
4764 result = builder.createUnaryOp(convOp, destType, operand);
4765
John Kessenich32cfd492016-02-02 12:37:46 -07004766 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004767}
4768
4769spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4770{
4771 if (vectorSize == 0)
4772 return constant;
4773
4774 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4775 std::vector<spv::Id> components;
4776 for (int c = 0; c < vectorSize; ++c)
4777 components.push_back(constant);
4778 return builder.makeCompositeConstant(vectorTypeId, components);
4779}
4780
John Kessenich426394d2015-07-23 10:22:48 -06004781// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004782spv::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 -06004783{
4784 spv::Op opCode = spv::OpNop;
4785
4786 switch (op) {
4787 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004788 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004789 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004790 opCode = spv::OpAtomicIAdd;
4791 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004792 case glslang::EOpAtomicCounterSubtract:
4793 opCode = spv::OpAtomicISub;
4794 break;
John Kessenich426394d2015-07-23 10:22:48 -06004795 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004796 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004797 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004798 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004799 break;
4800 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004801 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004802 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004803 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004804 break;
4805 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004806 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004807 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004808 opCode = spv::OpAtomicAnd;
4809 break;
4810 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004811 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004812 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004813 opCode = spv::OpAtomicOr;
4814 break;
4815 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004816 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004817 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004818 opCode = spv::OpAtomicXor;
4819 break;
4820 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004821 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004822 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004823 opCode = spv::OpAtomicExchange;
4824 break;
4825 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004826 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004827 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004828 opCode = spv::OpAtomicCompareExchange;
4829 break;
4830 case glslang::EOpAtomicCounterIncrement:
4831 opCode = spv::OpAtomicIIncrement;
4832 break;
4833 case glslang::EOpAtomicCounterDecrement:
4834 opCode = spv::OpAtomicIDecrement;
4835 break;
4836 case glslang::EOpAtomicCounter:
4837 opCode = spv::OpAtomicLoad;
4838 break;
4839 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004840 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004841 break;
4842 }
4843
Rex Xue8fe8b02017-09-26 15:42:56 +08004844 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4845 builder.addCapability(spv::CapabilityInt64Atomics);
4846
John Kessenich426394d2015-07-23 10:22:48 -06004847 // Sort out the operands
4848 // - mapping from glslang -> SPV
4849 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004850 // - compare-exchange swaps the value and comparator
4851 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004852 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004853 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4854 auto opIt = operands.begin(); // walk the glslang operands
4855 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004856 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4857 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4858 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004859 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4860 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004861 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004862 spvAtomicOperands.push_back(*(opIt + 1));
4863 spvAtomicOperands.push_back(*opIt);
4864 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004865 }
John Kessenich426394d2015-07-23 10:22:48 -06004866
John Kessenich3e60a6f2015-09-14 22:45:16 -06004867 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004868 for (; opIt != operands.end(); ++opIt)
4869 spvAtomicOperands.push_back(*opIt);
4870
John Kessenich48d6e792017-10-06 21:21:48 -06004871 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4872
4873 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4874 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4875 if (op == glslang::EOpAtomicCounterDecrement)
4876 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4877
4878 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004879}
4880
John Kessenich91cef522016-05-05 16:45:40 -06004881// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004882spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004883{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004884#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004885 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004886 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004887#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004888
Rex Xu51596642016-09-21 18:56:12 +08004889 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004890 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004891 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4892
chaocf200da82016-12-20 12:44:35 -08004893 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4894 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004895 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4896 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004897 } else if (op == glslang::EOpAnyInvocation ||
4898 op == glslang::EOpAllInvocations ||
4899 op == glslang::EOpAllInvocationsEqual) {
4900 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4901 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004902 } else {
4903 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004904#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004905 if (op == glslang::EOpMinInvocationsNonUniform ||
4906 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004907 op == glslang::EOpAddInvocationsNonUniform ||
4908 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4909 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4910 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4911 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4912 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4913 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004914 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004915#endif
Rex Xu51596642016-09-21 18:56:12 +08004916
4917 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004918#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004919 switch (op) {
4920 case glslang::EOpMinInvocations:
4921 case glslang::EOpMaxInvocations:
4922 case glslang::EOpAddInvocations:
4923 case glslang::EOpMinInvocationsNonUniform:
4924 case glslang::EOpMaxInvocationsNonUniform:
4925 case glslang::EOpAddInvocationsNonUniform:
4926 groupOperation = spv::GroupOperationReduce;
4927 spvGroupOperands.push_back(groupOperation);
4928 break;
4929 case glslang::EOpMinInvocationsInclusiveScan:
4930 case glslang::EOpMaxInvocationsInclusiveScan:
4931 case glslang::EOpAddInvocationsInclusiveScan:
4932 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4933 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4934 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4935 groupOperation = spv::GroupOperationInclusiveScan;
4936 spvGroupOperands.push_back(groupOperation);
4937 break;
4938 case glslang::EOpMinInvocationsExclusiveScan:
4939 case glslang::EOpMaxInvocationsExclusiveScan:
4940 case glslang::EOpAddInvocationsExclusiveScan:
4941 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4942 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4943 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4944 groupOperation = spv::GroupOperationExclusiveScan;
4945 spvGroupOperands.push_back(groupOperation);
4946 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004947 default:
4948 break;
Rex Xu430ef402016-10-14 17:22:23 +08004949 }
Rex Xu9d93a232016-05-05 12:30:44 +08004950#endif
Rex Xu51596642016-09-21 18:56:12 +08004951 }
4952
4953 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4954 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004955
4956 switch (op) {
4957 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004958 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004959 break;
John Kessenich91cef522016-05-05 16:45:40 -06004960 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004961 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004962 break;
John Kessenich91cef522016-05-05 16:45:40 -06004963 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004964 opCode = spv::OpSubgroupAllEqualKHR;
4965 break;
Rex Xu51596642016-09-21 18:56:12 +08004966 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004967 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004968 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004969 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004970 break;
4971 case glslang::EOpReadFirstInvocation:
4972 opCode = spv::OpSubgroupFirstInvocationKHR;
4973 break;
4974 case glslang::EOpBallot:
4975 {
4976 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4977 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4978 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4979 //
4980 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4981 //
4982 spv::Id uintType = builder.makeUintType(32);
4983 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4984 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4985
4986 std::vector<spv::Id> components;
4987 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4988 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4989
4990 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4991 return builder.createUnaryOp(spv::OpBitcast, typeId,
4992 builder.createCompositeConstruct(uvec2Type, components));
4993 }
4994
Rex Xu9d93a232016-05-05 12:30:44 +08004995#ifdef AMD_EXTENSIONS
4996 case glslang::EOpMinInvocations:
4997 case glslang::EOpMaxInvocations:
4998 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004999 case glslang::EOpMinInvocationsInclusiveScan:
5000 case glslang::EOpMaxInvocationsInclusiveScan:
5001 case glslang::EOpAddInvocationsInclusiveScan:
5002 case glslang::EOpMinInvocationsExclusiveScan:
5003 case glslang::EOpMaxInvocationsExclusiveScan:
5004 case glslang::EOpAddInvocationsExclusiveScan:
5005 if (op == glslang::EOpMinInvocations ||
5006 op == glslang::EOpMinInvocationsInclusiveScan ||
5007 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005008 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005009 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005010 else {
5011 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005012 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005013 else
Rex Xu51596642016-09-21 18:56:12 +08005014 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005015 }
Rex Xu430ef402016-10-14 17:22:23 +08005016 } else if (op == glslang::EOpMaxInvocations ||
5017 op == glslang::EOpMaxInvocationsInclusiveScan ||
5018 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005019 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005020 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005021 else {
5022 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005023 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005024 else
Rex Xu51596642016-09-21 18:56:12 +08005025 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005026 }
5027 } else {
5028 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005029 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005030 else
Rex Xu51596642016-09-21 18:56:12 +08005031 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005032 }
5033
Rex Xu2bbbe062016-08-23 15:41:05 +08005034 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005035 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005036
5037 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005038 case glslang::EOpMinInvocationsNonUniform:
5039 case glslang::EOpMaxInvocationsNonUniform:
5040 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005041 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5042 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5043 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5044 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5045 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5046 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5047 if (op == glslang::EOpMinInvocationsNonUniform ||
5048 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5049 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005050 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005051 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005052 else {
5053 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005054 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005055 else
Rex Xu51596642016-09-21 18:56:12 +08005056 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005057 }
5058 }
Rex Xu430ef402016-10-14 17:22:23 +08005059 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5060 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5061 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005062 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005063 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005064 else {
5065 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005066 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005067 else
Rex Xu51596642016-09-21 18:56:12 +08005068 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005069 }
5070 }
5071 else {
5072 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005073 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005074 else
Rex Xu51596642016-09-21 18:56:12 +08005075 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005076 }
5077
Rex Xu2bbbe062016-08-23 15:41:05 +08005078 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005079 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005080
5081 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005082#endif
John Kessenich91cef522016-05-05 16:45:40 -06005083 default:
5084 logger->missingFunctionality("invocation operation");
5085 return spv::NoResult;
5086 }
Rex Xu51596642016-09-21 18:56:12 +08005087
5088 assert(opCode != spv::OpNop);
5089 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005090}
5091
Rex Xu2bbbe062016-08-23 15:41:05 +08005092// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005093spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005094{
Rex Xub7072052016-09-26 15:53:40 +08005095#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005096 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5097 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005098 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005099 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005100 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5101 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5102 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005103#else
5104 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5105 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005106 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5107 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005108#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005109
5110 // Handle group invocation operations scalar by scalar.
5111 // The result type is the same type as the original type.
5112 // The algorithm is to:
5113 // - break the vector into scalars
5114 // - apply the operation to each scalar
5115 // - make a vector out the scalar results
5116
5117 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005118 int numComponents = builder.getNumComponents(operands[0]);
5119 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005120 std::vector<spv::Id> results;
5121
5122 // do each scalar op
5123 for (int comp = 0; comp < numComponents; ++comp) {
5124 std::vector<unsigned int> indexes;
5125 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005126 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005127 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005128 if (op == spv::OpSubgroupReadInvocationKHR) {
5129 spvGroupOperands.push_back(scalar);
5130 spvGroupOperands.push_back(operands[1]);
5131 } else if (op == spv::OpGroupBroadcast) {
5132 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005133 spvGroupOperands.push_back(scalar);
5134 spvGroupOperands.push_back(operands[1]);
5135 } else {
chaocf200da82016-12-20 12:44:35 -08005136 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005137 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005138 spvGroupOperands.push_back(scalar);
5139 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005140
Rex Xub7072052016-09-26 15:53:40 +08005141 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005142 }
5143
5144 // put the pieces together
5145 return builder.createCompositeConstruct(typeId, results);
5146}
Rex Xu2bbbe062016-08-23 15:41:05 +08005147
John Kessenich5e4b1242015-08-06 22:53:06 -06005148spv::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 -06005149{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005150#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005151 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005152 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5153#else
Rex Xucabbb782017-03-24 13:41:14 +08005154 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005155 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005156#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005157
John Kessenich140f3df2015-06-26 16:58:36 -06005158 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005159 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005160 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005161 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005162 spv::Id typeId0 = 0;
5163 if (consumedOperands > 0)
5164 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005165 spv::Id typeId1 = 0;
5166 if (consumedOperands > 1)
5167 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005168 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005169
5170 switch (op) {
5171 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005172 if (isFloat)
5173 libCall = spv::GLSLstd450FMin;
5174 else if (isUnsigned)
5175 libCall = spv::GLSLstd450UMin;
5176 else
5177 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005178 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005179 break;
5180 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005181 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005184 if (isFloat)
5185 libCall = spv::GLSLstd450FMax;
5186 else if (isUnsigned)
5187 libCall = spv::GLSLstd450UMax;
5188 else
5189 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005190 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005191 break;
5192 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005193 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005194 break;
5195 case glslang::EOpDot:
5196 opCode = spv::OpDot;
5197 break;
5198 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005199 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005200 break;
5201
5202 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005203 if (isFloat)
5204 libCall = spv::GLSLstd450FClamp;
5205 else if (isUnsigned)
5206 libCall = spv::GLSLstd450UClamp;
5207 else
5208 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005209 builder.promoteScalar(precision, operands.front(), operands[1]);
5210 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005211 break;
5212 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005213 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5214 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005215 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005216 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005217 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005218 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005219 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005220 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005221 break;
5222 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005223 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005224 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005228 builder.promoteScalar(precision, operands[0], operands[2]);
5229 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005230 break;
5231
5232 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005233 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005234 break;
5235 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005236 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005237 break;
5238 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005239 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005240 break;
5241 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005242 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005243 break;
5244 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005245 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005246 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005247 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005248 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005249 libCall = spv::GLSLstd450InterpolateAtSample;
5250 break;
5251 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005252 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005253 libCall = spv::GLSLstd450InterpolateAtOffset;
5254 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005255 case glslang::EOpAddCarry:
5256 opCode = spv::OpIAddCarry;
5257 typeId = builder.makeStructResultType(typeId0, typeId0);
5258 consumedOperands = 2;
5259 break;
5260 case glslang::EOpSubBorrow:
5261 opCode = spv::OpISubBorrow;
5262 typeId = builder.makeStructResultType(typeId0, typeId0);
5263 consumedOperands = 2;
5264 break;
5265 case glslang::EOpUMulExtended:
5266 opCode = spv::OpUMulExtended;
5267 typeId = builder.makeStructResultType(typeId0, typeId0);
5268 consumedOperands = 2;
5269 break;
5270 case glslang::EOpIMulExtended:
5271 opCode = spv::OpSMulExtended;
5272 typeId = builder.makeStructResultType(typeId0, typeId0);
5273 consumedOperands = 2;
5274 break;
5275 case glslang::EOpBitfieldExtract:
5276 if (isUnsigned)
5277 opCode = spv::OpBitFieldUExtract;
5278 else
5279 opCode = spv::OpBitFieldSExtract;
5280 break;
5281 case glslang::EOpBitfieldInsert:
5282 opCode = spv::OpBitFieldInsert;
5283 break;
5284
5285 case glslang::EOpFma:
5286 libCall = spv::GLSLstd450Fma;
5287 break;
5288 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005289 {
5290 libCall = spv::GLSLstd450FrexpStruct;
5291 assert(builder.isPointerType(typeId1));
5292 typeId1 = builder.getContainedTypeId(typeId1);
5293#ifdef AMD_EXTENSIONS
5294 int width = builder.getScalarTypeWidth(typeId1);
5295#else
5296 int width = 32;
5297#endif
5298 if (builder.getNumComponents(operands[0]) == 1)
5299 frexpIntType = builder.makeIntegerType(width, true);
5300 else
5301 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5302 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5303 consumedOperands = 1;
5304 }
John Kessenich55e7d112015-11-15 21:33:39 -07005305 break;
5306 case glslang::EOpLdexp:
5307 libCall = spv::GLSLstd450Ldexp;
5308 break;
5309
Rex Xu574ab042016-04-14 16:53:07 +08005310 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005311 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005312
Rex Xu9d93a232016-05-05 12:30:44 +08005313#ifdef AMD_EXTENSIONS
5314 case glslang::EOpSwizzleInvocations:
5315 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5316 libCall = spv::SwizzleInvocationsAMD;
5317 break;
5318 case glslang::EOpSwizzleInvocationsMasked:
5319 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5320 libCall = spv::SwizzleInvocationsMaskedAMD;
5321 break;
5322 case glslang::EOpWriteInvocation:
5323 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5324 libCall = spv::WriteInvocationAMD;
5325 break;
5326
5327 case glslang::EOpMin3:
5328 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5329 if (isFloat)
5330 libCall = spv::FMin3AMD;
5331 else {
5332 if (isUnsigned)
5333 libCall = spv::UMin3AMD;
5334 else
5335 libCall = spv::SMin3AMD;
5336 }
5337 break;
5338 case glslang::EOpMax3:
5339 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5340 if (isFloat)
5341 libCall = spv::FMax3AMD;
5342 else {
5343 if (isUnsigned)
5344 libCall = spv::UMax3AMD;
5345 else
5346 libCall = spv::SMax3AMD;
5347 }
5348 break;
5349 case glslang::EOpMid3:
5350 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5351 if (isFloat)
5352 libCall = spv::FMid3AMD;
5353 else {
5354 if (isUnsigned)
5355 libCall = spv::UMid3AMD;
5356 else
5357 libCall = spv::SMid3AMD;
5358 }
5359 break;
5360
5361 case glslang::EOpInterpolateAtVertex:
5362 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5363 libCall = spv::InterpolateAtVertexAMD;
5364 break;
5365#endif
5366
John Kessenich140f3df2015-06-26 16:58:36 -06005367 default:
5368 return 0;
5369 }
5370
5371 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005372 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005373 // Use an extended instruction from the standard library.
5374 // Construct the call arguments, without modifying the original operands vector.
5375 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5376 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005377 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005378 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005379 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005380 case 0:
5381 // should all be handled by visitAggregate and createNoArgOperation
5382 assert(0);
5383 return 0;
5384 case 1:
5385 // should all be handled by createUnaryOperation
5386 assert(0);
5387 return 0;
5388 case 2:
5389 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005391 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005392 // anything 3 or over doesn't have l-value operands, so all should be consumed
5393 assert(consumedOperands == operands.size());
5394 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005395 break;
5396 }
5397 }
5398
John Kessenich55e7d112015-11-15 21:33:39 -07005399 // Decode the return types that were structures
5400 switch (op) {
5401 case glslang::EOpAddCarry:
5402 case glslang::EOpSubBorrow:
5403 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5404 id = builder.createCompositeExtract(id, typeId0, 0);
5405 break;
5406 case glslang::EOpUMulExtended:
5407 case glslang::EOpIMulExtended:
5408 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5409 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5410 break;
5411 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005412 {
5413 assert(operands.size() == 2);
5414 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5415 // "exp" is floating-point type (from HLSL intrinsic)
5416 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5417 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5418 builder.createStore(member1, operands[1]);
5419 } else
5420 // "exp" is integer type (from GLSL built-in function)
5421 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5422 id = builder.createCompositeExtract(id, typeId0, 0);
5423 }
John Kessenich55e7d112015-11-15 21:33:39 -07005424 break;
5425 default:
5426 break;
5427 }
5428
John Kessenich32cfd492016-02-02 12:37:46 -07005429 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005430}
5431
Rex Xu9d93a232016-05-05 12:30:44 +08005432// Intrinsics with no arguments (or no return value, and no precision).
5433spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005434{
5435 // TODO: get the barrier operands correct
5436
5437 switch (op) {
5438 case glslang::EOpEmitVertex:
5439 builder.createNoResultOp(spv::OpEmitVertex);
5440 return 0;
5441 case glslang::EOpEndPrimitive:
5442 builder.createNoResultOp(spv::OpEndPrimitive);
5443 return 0;
5444 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005445 if (glslangIntermediate->getStage() == EShLangTessControl) {
5446 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5447 // TODO: prefer the following, when available:
5448 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5449 // spv::MemorySemanticsPatchMask |
5450 // spv::MemorySemanticsAcquireReleaseMask);
5451 } else {
5452 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5453 spv::MemorySemanticsWorkgroupMemoryMask |
5454 spv::MemorySemanticsAcquireReleaseMask);
5455 }
John Kessenich140f3df2015-06-26 16:58:36 -06005456 return 0;
5457 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005458 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5459 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005460 return 0;
5461 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005462 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5463 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005464 return 0;
5465 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005466 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5467 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005468 return 0;
5469 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005470 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5471 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005472 return 0;
5473 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005474 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5475 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005476 return 0;
5477 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005478 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5479 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005480 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005481 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005482 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005483 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005484 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005485 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005486 case glslang::EOpDeviceMemoryBarrier:
5487 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5488 spv::MemorySemanticsImageMemoryMask |
5489 spv::MemorySemanticsAcquireReleaseMask);
5490 return 0;
5491 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5492 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5493 spv::MemorySemanticsImageMemoryMask |
5494 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005495 return 0;
5496 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005497 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5498 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005499 return 0;
5500 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005501 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5502 spv::MemorySemanticsWorkgroupMemoryMask |
5503 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005504 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005505#ifdef AMD_EXTENSIONS
5506 case glslang::EOpTime:
5507 {
5508 std::vector<spv::Id> args; // Dummy arguments
5509 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5510 return builder.setPrecision(id, precision);
5511 }
5512#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005513 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005514 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005515 return 0;
5516 }
5517}
5518
5519spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5520{
John Kessenich2f273362015-07-18 22:34:27 -06005521 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005522 spv::Id id;
5523 if (symbolValues.end() != iter) {
5524 id = iter->second;
5525 return id;
5526 }
5527
5528 // it was not found, create it
5529 id = createSpvVariable(symbol);
5530 symbolValues[symbol->getId()] = id;
5531
Rex Xuc884b4a2016-06-29 15:03:44 +08005532 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005533 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005534 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005535 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005536 if (symbol->getType().getQualifier().hasSpecConstantId())
5537 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005538 if (symbol->getQualifier().hasIndex())
5539 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5540 if (symbol->getQualifier().hasComponent())
5541 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005542 // atomic counters use this:
5543 if (symbol->getQualifier().hasOffset())
5544 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005545 }
5546
scygan2c864272016-05-18 18:09:17 +02005547 if (symbol->getQualifier().hasLocation())
5548 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005549 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005550 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005551 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005552 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005553 }
John Kessenich140f3df2015-06-26 16:58:36 -06005554 if (symbol->getQualifier().hasSet())
5555 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005556 else if (IsDescriptorResource(symbol->getType())) {
5557 // default to 0
5558 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5559 }
John Kessenich140f3df2015-06-26 16:58:36 -06005560 if (symbol->getQualifier().hasBinding())
5561 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005562 if (symbol->getQualifier().hasAttachment())
5563 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005564 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005565 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005566 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005567 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005568 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005569 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005570 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5571 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5572 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5573 }
5574 if (symbol->getQualifier().hasXfbOffset())
5575 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005576 }
5577
Rex Xu1da878f2016-02-21 20:59:01 +08005578 if (symbol->getType().isImage()) {
5579 std::vector<spv::Decoration> memory;
5580 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5581 for (unsigned int i = 0; i < memory.size(); ++i)
5582 addDecoration(id, memory[i]);
5583 }
5584
John Kessenich140f3df2015-06-26 16:58:36 -06005585 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005586 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005587 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005588 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005589
John Kessenichecba76f2017-01-06 00:34:48 -07005590#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005591 if (builtIn == spv::BuiltInSampleMask) {
5592 spv::Decoration decoration;
5593 // GL_NV_sample_mask_override_coverage extension
5594 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005595 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005596 else
5597 decoration = (spv::Decoration)spv::DecorationMax;
5598 addDecoration(id, decoration);
5599 if (decoration != spv::DecorationMax) {
5600 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5601 }
5602 }
chaoc771d89f2017-01-13 01:10:53 -08005603 else if (builtIn == spv::BuiltInLayer) {
5604 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005605 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005606 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5607 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5608 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5609 }
John Kessenichb41bff62017-08-11 13:07:17 -06005610 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005611 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5612 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5613 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5614 }
5615 }
5616
chaoc6e5acae2016-12-20 13:28:52 -08005617 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005618 addDecoration(id, spv::DecorationPassthroughNV);
5619 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005620 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5621 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005622#endif
5623
John Kessenich140f3df2015-06-26 16:58:36 -06005624 return id;
5625}
5626
John Kessenich55e7d112015-11-15 21:33:39 -07005627// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005628void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5629{
John Kessenich4016e382016-07-15 11:53:56 -06005630 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005631 builder.addDecoration(id, dec);
5632}
5633
John Kessenich55e7d112015-11-15 21:33:39 -07005634// If 'dec' is valid, add a one-operand decoration to an object
5635void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5636{
John Kessenich4016e382016-07-15 11:53:56 -06005637 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005638 builder.addDecoration(id, dec, value);
5639}
5640
5641// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005642void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5643{
John Kessenich4016e382016-07-15 11:53:56 -06005644 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005645 builder.addMemberDecoration(id, (unsigned)member, dec);
5646}
5647
John Kessenich92187592016-02-01 13:45:25 -07005648// If 'dec' is valid, add a one-operand decoration to a struct member
5649void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5650{
John Kessenich4016e382016-07-15 11:53:56 -06005651 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005652 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5653}
5654
John Kessenich55e7d112015-11-15 21:33:39 -07005655// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005656// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005657//
5658// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5659//
5660// Recursively walk the nodes. The nodes form a tree whose leaves are
5661// regular constants, which themselves are trees that createSpvConstant()
5662// recursively walks. So, this function walks the "top" of the tree:
5663// - emit specialization constant-building instructions for specConstant
5664// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005665spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005666{
John Kessenich7cc0e282016-03-20 00:46:02 -06005667 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005668
qining4f4bb812016-04-03 23:55:17 -04005669 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005670 if (! node.getQualifier().specConstant) {
5671 // hand off to the non-spec-constant path
5672 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5673 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005674 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005675 nextConst, false);
5676 }
5677
5678 // We now know we have a specialization constant to build
5679
John Kessenichd94c0032016-05-30 19:29:40 -06005680 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005681 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5682 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5683 std::vector<spv::Id> dimConstId;
5684 for (int dim = 0; dim < 3; ++dim) {
5685 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5686 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5687 if (specConst)
5688 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5689 }
5690 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5691 }
5692
5693 // An AST node labelled as specialization constant should be a symbol node.
5694 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5695 if (auto* sn = node.getAsSymbolNode()) {
5696 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005697 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5698 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5699 // will set the builder into spec constant op instruction generating mode.
5700 sub_tree->traverse(this);
5701 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005702 } else if (auto* const_union_array = &sn->getConstArray()){
5703 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005704 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5705 builder.addName(id, sn->getName().c_str());
5706 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005707 }
5708 }
qining4f4bb812016-04-03 23:55:17 -04005709
5710 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5711 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005712 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005713 exit(1);
5714 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005715}
5716
John Kessenich140f3df2015-06-26 16:58:36 -06005717// Use 'consts' as the flattened glslang source of scalar constants to recursively
5718// build the aggregate SPIR-V constant.
5719//
5720// If there are not enough elements present in 'consts', 0 will be substituted;
5721// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5722//
qining08408382016-03-21 09:51:37 -04005723spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005724{
5725 // vector of constants for SPIR-V
5726 std::vector<spv::Id> spvConsts;
5727
5728 // Type is used for struct and array constants
5729 spv::Id typeId = convertGlslangToSpvType(glslangType);
5730
5731 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005732 glslang::TType elementType(glslangType, 0);
5733 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005734 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005735 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005736 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005737 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005738 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005739 } else if (glslangType.getStruct()) {
5740 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5741 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005742 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005743 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005744 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5745 bool zero = nextConst >= consts.size();
5746 switch (glslangType.getBasicType()) {
5747 case glslang::EbtInt:
5748 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5749 break;
5750 case glslang::EbtUint:
5751 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5752 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005753 case glslang::EbtInt64:
5754 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5755 break;
5756 case glslang::EbtUint64:
5757 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5758 break;
Rex Xucabbb782017-03-24 13:41:14 +08005759#ifdef AMD_EXTENSIONS
5760 case glslang::EbtInt16:
5761 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5762 break;
5763 case glslang::EbtUint16:
5764 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5765 break;
5766#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005767 case glslang::EbtFloat:
5768 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5769 break;
5770 case glslang::EbtDouble:
5771 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5772 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005773#ifdef AMD_EXTENSIONS
5774 case glslang::EbtFloat16:
5775 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5776 break;
5777#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005778 case glslang::EbtBool:
5779 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5780 break;
5781 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005782 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005783 break;
5784 }
5785 ++nextConst;
5786 }
5787 } else {
5788 // we have a non-aggregate (scalar) constant
5789 bool zero = nextConst >= consts.size();
5790 spv::Id scalar = 0;
5791 switch (glslangType.getBasicType()) {
5792 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005793 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005794 break;
5795 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005796 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005797 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005798 case glslang::EbtInt64:
5799 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5800 break;
5801 case glslang::EbtUint64:
5802 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5803 break;
Rex Xucabbb782017-03-24 13:41:14 +08005804#ifdef AMD_EXTENSIONS
5805 case glslang::EbtInt16:
5806 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5807 break;
5808 case glslang::EbtUint16:
5809 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5810 break;
5811#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005812 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005813 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005814 break;
5815 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005816 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005818#ifdef AMD_EXTENSIONS
5819 case glslang::EbtFloat16:
5820 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5821 break;
5822#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005823 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005824 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005827 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 }
5830 ++nextConst;
5831 return scalar;
5832 }
5833
5834 return builder.makeCompositeConstant(typeId, spvConsts);
5835}
5836
John Kessenich7c1aa102015-10-15 13:29:11 -06005837// Return true if the node is a constant or symbol whose reading has no
5838// non-trivial observable cost or effect.
5839bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5840{
5841 // don't know what this is
5842 if (node == nullptr)
5843 return false;
5844
5845 // a constant is safe
5846 if (node->getAsConstantUnion() != nullptr)
5847 return true;
5848
5849 // not a symbol means non-trivial
5850 if (node->getAsSymbolNode() == nullptr)
5851 return false;
5852
5853 // a symbol, depends on what's being read
5854 switch (node->getType().getQualifier().storage) {
5855 case glslang::EvqTemporary:
5856 case glslang::EvqGlobal:
5857 case glslang::EvqIn:
5858 case glslang::EvqInOut:
5859 case glslang::EvqConst:
5860 case glslang::EvqConstReadOnly:
5861 case glslang::EvqUniform:
5862 return true;
5863 default:
5864 return false;
5865 }
qining25262b32016-05-06 17:25:16 -04005866}
John Kessenich7c1aa102015-10-15 13:29:11 -06005867
5868// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005869// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005870// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005871// Return true if trivial.
5872bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5873{
5874 if (node == nullptr)
5875 return false;
5876
John Kessenich84cc15f2017-05-24 16:44:47 -06005877 // count non scalars as trivial, as well as anything coming from HLSL
5878 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005879 return true;
5880
John Kessenich7c1aa102015-10-15 13:29:11 -06005881 // symbols and constants are trivial
5882 if (isTrivialLeaf(node))
5883 return true;
5884
5885 // otherwise, it needs to be a simple operation or one or two leaf nodes
5886
5887 // not a simple operation
5888 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5889 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5890 if (binaryNode == nullptr && unaryNode == nullptr)
5891 return false;
5892
5893 // not on leaf nodes
5894 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5895 return false;
5896
5897 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5898 return false;
5899 }
5900
5901 switch (node->getAsOperator()->getOp()) {
5902 case glslang::EOpLogicalNot:
5903 case glslang::EOpConvIntToBool:
5904 case glslang::EOpConvUintToBool:
5905 case glslang::EOpConvFloatToBool:
5906 case glslang::EOpConvDoubleToBool:
5907 case glslang::EOpEqual:
5908 case glslang::EOpNotEqual:
5909 case glslang::EOpLessThan:
5910 case glslang::EOpGreaterThan:
5911 case glslang::EOpLessThanEqual:
5912 case glslang::EOpGreaterThanEqual:
5913 case glslang::EOpIndexDirect:
5914 case glslang::EOpIndexDirectStruct:
5915 case glslang::EOpLogicalXor:
5916 case glslang::EOpAny:
5917 case glslang::EOpAll:
5918 return true;
5919 default:
5920 return false;
5921 }
5922}
5923
5924// Emit short-circuiting code, where 'right' is never evaluated unless
5925// the left side is true (for &&) or false (for ||).
5926spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5927{
5928 spv::Id boolTypeId = builder.makeBoolType();
5929
5930 // emit left operand
5931 builder.clearAccessChain();
5932 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005933 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005934
5935 // Operands to accumulate OpPhi operands
5936 std::vector<spv::Id> phiOperands;
5937 // accumulate left operand's phi information
5938 phiOperands.push_back(leftId);
5939 phiOperands.push_back(builder.getBuildPoint()->getId());
5940
5941 // Make the two kinds of operation symmetric with a "!"
5942 // || => emit "if (! left) result = right"
5943 // && => emit "if ( left) result = right"
5944 //
5945 // TODO: this runtime "not" for || could be avoided by adding functionality
5946 // to 'builder' to have an "else" without an "then"
5947 if (op == glslang::EOpLogicalOr)
5948 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5949
5950 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005951 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005952
5953 // emit right operand as the "then" part of the "if"
5954 builder.clearAccessChain();
5955 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005956 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005957
5958 // accumulate left operand's phi information
5959 phiOperands.push_back(rightId);
5960 phiOperands.push_back(builder.getBuildPoint()->getId());
5961
5962 // finish the "if"
5963 ifBuilder.makeEndIf();
5964
5965 // phi together the two results
5966 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5967}
5968
Frank Henigman541f7bb2018-01-16 00:18:26 -05005969#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08005970// Return type Id of the imported set of extended instructions corresponds to the name.
5971// Import this set if it has not been imported yet.
5972spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5973{
5974 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5975 return extBuiltinMap[name];
5976 else {
Rex Xu51596642016-09-21 18:56:12 +08005977 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005978 spv::Id extBuiltins = builder.import(name);
5979 extBuiltinMap[name] = extBuiltins;
5980 return extBuiltins;
5981 }
5982}
Frank Henigman541f7bb2018-01-16 00:18:26 -05005983#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005984
John Kessenich140f3df2015-06-26 16:58:36 -06005985}; // end anonymous namespace
5986
5987namespace glslang {
5988
John Kessenich68d78fd2015-07-12 19:28:10 -06005989void GetSpirvVersion(std::string& version)
5990{
John Kessenich9e55f632015-07-15 10:03:39 -06005991 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005992 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005993 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005994 version = buf;
5995}
5996
John Kessenicha372a3e2017-11-02 22:32:14 -06005997// For low-order part of the generator's magic number. Bump up
5998// when there is a change in the style (e.g., if SSA form changes,
5999// or a different instruction sequence to do something gets used).
6000int GetSpirvGeneratorVersion()
6001{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006002 // return 1; // start
6003 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
6004 return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenicha372a3e2017-11-02 22:32:14 -06006005}
6006
John Kessenich140f3df2015-06-26 16:58:36 -06006007// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006008void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006009{
6010 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006011 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006012 if (out.fail())
6013 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006014 for (int i = 0; i < (int)spirv.size(); ++i) {
6015 unsigned int word = spirv[i];
6016 out.write((const char*)&word, 4);
6017 }
6018 out.close();
6019}
6020
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006021// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006022void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006023{
6024 std::ofstream out;
6025 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006026 if (out.fail())
6027 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006028 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006029 if (varName != nullptr) {
6030 out << "\t #pragma once" << std::endl;
6031 out << "const uint32_t " << varName << "[] = {" << std::endl;
6032 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006033 const int WORDS_PER_LINE = 8;
6034 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6035 out << "\t";
6036 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6037 const unsigned int word = spirv[i + j];
6038 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6039 if (i + j + 1 < (int)spirv.size()) {
6040 out << ",";
6041 }
6042 }
6043 out << std::endl;
6044 }
Flavio15017db2017-02-15 14:29:33 -08006045 if (varName != nullptr) {
6046 out << "};";
6047 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006048 out.close();
6049}
6050
GregFcd1f1692017-09-21 18:40:22 -06006051#ifdef ENABLE_OPT
6052void errHandler(const std::string& str) {
6053 std::cerr << str << std::endl;
6054}
6055#endif
6056
John Kessenich140f3df2015-06-26 16:58:36 -06006057//
6058// Set up the glslang traversal
6059//
John Kessenich121853f2017-05-31 17:11:16 -06006060void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006061{
Lei Zhang17535f72016-05-04 15:55:59 -04006062 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006063 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006064}
6065
John Kessenich121853f2017-05-31 17:11:16 -06006066void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6067 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006068{
John Kessenich140f3df2015-06-26 16:58:36 -06006069 TIntermNode* root = intermediate.getTreeRoot();
6070
6071 if (root == 0)
6072 return;
6073
John Kessenich121853f2017-05-31 17:11:16 -06006074 glslang::SpvOptions defaultOptions;
6075 if (options == nullptr)
6076 options = &defaultOptions;
6077
John Kessenich140f3df2015-06-26 16:58:36 -06006078 glslang::GetThreadPoolAllocator().push();
6079
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006080 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006081 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006082 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006083 it.dumpSpv(spirv);
6084
GregFcd1f1692017-09-21 18:40:22 -06006085#ifdef ENABLE_OPT
6086 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6087 // eg. forward and remove memory writes of opaque types.
6088 if ((intermediate.getSource() == EShSourceHlsl ||
6089 options->optimizeSize) &&
6090 !options->disableOptimizer) {
6091 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6092
6093 spvtools::Optimizer optimizer(target_env);
6094 optimizer.SetMessageConsumer([](spv_message_level_t level,
6095 const char* source,
6096 const spv_position_t& position,
6097 const char* message) {
6098 std::cerr << StringifyMessage(level, source, position, message)
6099 << std::endl;
6100 });
6101
6102 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006103 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6104 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006105 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6106 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6107 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6108 optimizer.RegisterPass(CreateInsertExtractElimPass());
6109 optimizer.RegisterPass(CreateAggressiveDCEPass());
6110 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006111 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006112 optimizer.RegisterPass(CreateBlockMergePass());
6113 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6114 optimizer.RegisterPass(CreateInsertExtractElimPass());
6115 optimizer.RegisterPass(CreateAggressiveDCEPass());
6116 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6117 // if (options->optimizeSize)
6118 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6119
6120 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6121 return;
6122
6123 // Remove dead module-level objects: functions, types, vars
6124 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6125 spv::spirvbin_t Remapper(0);
6126 Remapper.registerErrorHandler(errHandler);
6127 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6128 }
6129#endif
6130
John Kessenich140f3df2015-06-26 16:58:36 -06006131 glslang::GetThreadPoolAllocator().pop();
6132}
6133
6134}; // end namespace glslang