blob: 7c69242e1dd5e6b3d51baddf41fbb8da1808d05a [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070047 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080048#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080050#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080051#ifdef NV_EXTENSIONS
52 #include "GLSL.ext.NV.h"
53#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060054}
John Kessenich140f3df2015-06-26 16:58:36 -060055
GregFcd1f1692017-09-21 18:40:22 -060056#ifdef ENABLE_OPT
57 #include "spirv-tools/optimizer.hpp"
58 #include "message.h"
59 #include "SPVRemapper.h"
60#endif
61
62#ifdef ENABLE_OPT
63using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
101}
102
John Kessenich140f3df2015-06-26 16:58:36 -0600103//
104// The main holder of information for translating glslang to SPIR-V.
105//
106// Derives from the AST walking base class.
107//
108class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
109public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700110 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
111 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700112 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600113
114 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
115 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
116 void visitConstantUnion(glslang::TIntermConstantUnion*);
117 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
118 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
119 void visitSymbol(glslang::TIntermSymbol* symbol);
120 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
121 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
122 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
123
John Kessenichfca82622016-11-26 13:23:20 -0700124 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700125 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800128 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800129 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100130 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700131 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700132 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
133 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700134 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600135 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
137 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600138 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
139 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
140 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700142 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600143 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600144 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
145 glslang::TLayoutPacking, const glslang::TQualifier&);
146 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
147 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700148 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700149 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800150 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600151 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700152 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
154 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
155 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100156 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
John Kessenich6fccb3c2016-09-19 16:01:41 -0600158 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600159 bool writableParam(glslang::TStorageQualifier);
160 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 void makeFunctions(const glslang::TIntermSequence&);
162 void makeGlobalInitializers(const glslang::TIntermSequence&);
163 void visitFunctions(const glslang::TIntermSequence&);
164 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600166 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
167 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
169
qining25262b32016-05-06 17:25:16 -0400170 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
171 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
172 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800173 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800174 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800176 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800177 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800178 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600179 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
182 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700183 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600184 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700185 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400186 spv::Id createSpvConstant(const glslang::TIntermTyped&);
187 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600188 bool isTrivialLeaf(const glslang::TIntermTyped* node);
189 bool isTrivial(const glslang::TIntermTyped* node);
190 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500191#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800192 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500193#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600194
John Kessenich121853f2017-05-31 17:11:16 -0600195 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600197 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700198 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600199 int sequenceDepth;
200
Lei Zhang17535f72016-05-04 15:55:59 -0400201 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400202
John Kessenich140f3df2015-06-26 16:58:36 -0600203 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
204 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700205 bool inEntryPoint;
206 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700207 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700208 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600209 const glslang::TIntermediate* glslangIntermediate;
210 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800211 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600212
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600214 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600215 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700216 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600217 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600218 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600219};
220
221//
222// Helper functions for translating glslang representations to SPIR-V enumerants.
223//
224
225// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700226spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600227{
John Kessenich66e2faf2016-03-12 18:34:36 -0700228 switch (source) {
229 case glslang::EShSourceGlsl:
230 switch (profile) {
231 case ENoProfile:
232 case ECoreProfile:
233 case ECompatibilityProfile:
234 return spv::SourceLanguageGLSL;
235 case EEsProfile:
236 return spv::SourceLanguageESSL;
237 default:
238 return spv::SourceLanguageUnknown;
239 }
240 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600241 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 default:
243 return spv::SourceLanguageUnknown;
244 }
245}
246
247// Translate glslang language (stage) to SPIR-V execution model.
248spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
249{
250 switch (stage) {
251 case EShLangVertex: return spv::ExecutionModelVertex;
252 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
253 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
254 case EShLangGeometry: return spv::ExecutionModelGeometry;
255 case EShLangFragment: return spv::ExecutionModelFragment;
256 case EShLangCompute: return spv::ExecutionModelGLCompute;
257 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700258 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600259 return spv::ExecutionModelFragment;
260 }
261}
262
John Kessenich140f3df2015-06-26 16:58:36 -0600263// Translate glslang sampler type to SPIR-V dimensionality.
264spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
265{
266 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::Esd1D: return spv::Dim1D;
268 case glslang::Esd2D: return spv::Dim2D;
269 case glslang::Esd3D: return spv::Dim3D;
270 case glslang::EsdCube: return spv::DimCube;
271 case glslang::EsdRect: return spv::DimRect;
272 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700273 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700275 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::Dim2D;
277 }
278}
279
John Kessenichf6640762016-08-01 19:44:00 -0600280// Translate glslang precision to SPIR-V precision decorations.
281spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600282{
John Kessenichf6640762016-08-01 19:44:00 -0600283 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700284 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
287 return spv::NoPrecision;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang type to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
293{
294 return TranslatePrecisionDecoration(type.getQualifier().precision);
295}
296
John Kessenich140f3df2015-06-26 16:58:36 -0600297// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600298spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600299{
300 if (type.getBasicType() == glslang::EbtBlock) {
301 switch (type.getQualifier().storage) {
302 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600303 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 case glslang::EvqVaryingIn: return spv::DecorationBlock;
305 case glslang::EvqVaryingOut: return spv::DecorationBlock;
306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 break;
309 }
310 }
311
John Kessenich4016e382016-07-15 11:53:56 -0600312 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600313}
314
Rex Xu1da878f2016-02-21 20:59:01 +0800315// Translate glslang type to SPIR-V memory decorations.
316void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
317{
318 if (qualifier.coherent)
319 memory.push_back(spv::DecorationCoherent);
320 if (qualifier.volatil)
321 memory.push_back(spv::DecorationVolatile);
322 if (qualifier.restrict)
323 memory.push_back(spv::DecorationRestrict);
324 if (qualifier.readonly)
325 memory.push_back(spv::DecorationNonWritable);
326 if (qualifier.writeonly)
327 memory.push_back(spv::DecorationNonReadable);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700331spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElmRowMajor:
336 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700339 default:
340 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 } else {
344 switch (type.getBasicType()) {
345 default:
John Kessenich4016e382016-07-15 11:53:56 -0600346 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 case glslang::EbtBlock:
349 switch (type.getQualifier().storage) {
350 case glslang::EvqUniform:
351 case glslang::EvqBuffer:
352 switch (type.getQualifier().layoutPacking) {
353 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 case glslang::EvqVaryingIn:
359 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700363 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 }
367 }
368}
369
370// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600371// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700372// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800373spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
Rex Xubbceed72016-05-21 09:40:44 +0800375 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700379 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800382#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800383 else if (qualifier.explicitInterp) {
384 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800385 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800386 }
Rex Xu9d93a232016-05-05 12:30:44 +0800387#endif
Rex Xubbceed72016-05-21 09:40:44 +0800388 else
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800390}
391
392// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800394// should be applied.
395spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
396{
397 if (qualifier.patch)
398 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700401 else if (qualifier.sample) {
402 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700404 } else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600406}
407
John Kessenich92187592016-02-01 13:45:25 -0700408// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600410{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700411 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationInvariant;
413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
qining9220dbb2016-05-04 17:34:38 -0400417// If glslang type is noContraction, return SPIR-V NoContraction decoration.
418spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
419{
420 if (qualifier.noContraction)
421 return spv::DecorationNoContraction;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400424}
425
David Netoa901ffe2016-06-08 14:11:40 +0100426// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
427// associated capabilities when required. For some built-in variables, a capability
428// is generated only when using the variable in an executable instruction, but not when
429// just declaring a struct member variable with it. This is true for PointSize,
430// ClipDistance, and CullDistance.
431spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
433 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700434 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600435 // Defer adding the capability until the built-in is actually used.
436 if (! memberDeclaration) {
437 switch (glslangIntermediate->getStage()) {
438 case EShLangGeometry:
439 builder.addCapability(spv::CapabilityGeometryPointSize);
440 break;
441 case EShLangTessControl:
442 case EShLangTessEvaluation:
443 builder.addCapability(spv::CapabilityTessellationPointSize);
444 break;
445 default:
446 break;
447 }
John Kessenich92187592016-02-01 13:45:25 -0700448 }
449 return spv::BuiltInPointSize;
450
John Kessenichebb50532016-05-16 19:22:05 -0600451 // These *Distance capabilities logically belong here, but if the member is declared and
452 // then never used, consumers of SPIR-V prefer the capability not be declared.
453 // They are now generated when used, rather than here when declared.
454 // Potentially, the specification should be more clear what the minimum
455 // use needed is to trigger the capability.
456 //
John Kessenich92187592016-02-01 13:45:25 -0700457 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800459 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInClipDistance;
461
462 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100463 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800464 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700465 return spv::BuiltInCullDistance;
466
467 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600468 builder.addCapability(spv::CapabilityMultiViewport);
469 if (glslangIntermediate->getStage() == EShLangVertex ||
470 glslangIntermediate->getStage() == EShLangTessControl ||
471 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800472
John Kessenichba6a3c22017-09-13 13:22:50 -0600473 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
474 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800475 }
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInViewportIndex;
477
John Kessenich5e801132016-02-15 11:09:46 -0700478 case glslang::EbvSampleId:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleId;
481
482 case glslang::EbvSamplePosition:
483 builder.addCapability(spv::CapabilitySampleRateShading);
484 return spv::BuiltInSamplePosition;
485
486 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700487 return spv::BuiltInSampleMask;
488
John Kessenich78a45572016-07-08 14:05:15 -0600489 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600490 builder.addCapability(spv::CapabilityGeometry);
491 if (glslangIntermediate->getStage() == EShLangVertex ||
492 glslangIntermediate->getStage() == EShLangTessControl ||
493 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800494
John Kessenichba6a3c22017-09-13 13:22:50 -0600495 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
496 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800497 }
John Kessenich78a45572016-07-08 14:05:15 -0600498 return spv::BuiltInLayer;
499
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600501 case glslang::EbvVertexId: return spv::BuiltInVertexId;
502 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700503 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
504 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800505
John Kessenichda581a22015-10-14 14:10:30 -0600506 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800507 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
508 builder.addCapability(spv::CapabilityDrawParameters);
509 return spv::BuiltInBaseVertex;
510
John Kessenichda581a22015-10-14 14:10:30 -0600511 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800512 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
513 builder.addCapability(spv::CapabilityDrawParameters);
514 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200515
John Kessenichda581a22015-10-14 14:10:30 -0600516 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800517 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
518 builder.addCapability(spv::CapabilityDrawParameters);
519 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200520
521 case glslang::EbvPrimitiveId:
522 if (glslangIntermediate->getStage() == EShLangFragment)
523 builder.addCapability(spv::CapabilityGeometry);
524 return spv::BuiltInPrimitiveId;
525
Rex Xu37cdcee2017-06-29 17:46:34 +0800526 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800527 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
528 builder.addCapability(spv::CapabilityStencilExportEXT);
529 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800530
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600532 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
533 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
534 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
535 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
536 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
537 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
538 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600539 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
540 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
541 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
542 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
543 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
544 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
545 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
546 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800547
Rex Xu574ab042016-04-14 16:53:07 +0800548 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800549 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
551 return spv::BuiltInSubgroupSize;
552
Rex Xu574ab042016-04-14 16:53:07 +0800553 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800554 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
556 return spv::BuiltInSubgroupLocalInvocationId;
557
Rex Xu574ab042016-04-14 16:53:07 +0800558 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800559 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
560 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
561 return spv::BuiltInSubgroupEqMaskKHR;
562
Rex Xu574ab042016-04-14 16:53:07 +0800563 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800564 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
565 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
566 return spv::BuiltInSubgroupGeMaskKHR;
567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupGtMaskKHR;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLeMaskKHR;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupLtMaskKHR;
582
Rex Xu9d93a232016-05-05 12:30:44 +0800583#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800584 case glslang::EbvBaryCoordNoPersp:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspAMD;
587
588 case glslang::EbvBaryCoordNoPerspCentroid:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
591
592 case glslang::EbvBaryCoordNoPerspSample:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordNoPerspSampleAMD;
595
596 case glslang::EbvBaryCoordSmooth:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothAMD;
599
600 case glslang::EbvBaryCoordSmoothCentroid:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothCentroidAMD;
603
604 case glslang::EbvBaryCoordSmoothSample:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordSmoothSampleAMD;
607
608 case glslang::EbvBaryCoordPullModel:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800611#endif
chaoc771d89f2017-01-13 01:10:53 -0800612
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613 case glslang::EbvDeviceIndex:
614 builder.addExtension(spv::E_SPV_KHR_device_group);
615 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700616 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700617
618 case glslang::EbvViewIndex:
619 builder.addExtension(spv::E_SPV_KHR_multiview);
620 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700621 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700622
chaoc771d89f2017-01-13 01:10:53 -0800623#ifdef NV_EXTENSIONS
624 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800625 if (!memberDeclaration) {
626 builder.addExtension(spv::E_SPV_NV_viewport_array2);
627 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
628 }
chaoc771d89f2017-01-13 01:10:53 -0800629 return spv::BuiltInViewportMaskNV;
630 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800631 if (!memberDeclaration) {
632 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
633 builder.addCapability(spv::CapabilityShaderStereoViewNV);
634 }
chaoc771d89f2017-01-13 01:10:53 -0800635 return spv::BuiltInSecondaryPositionNV;
636 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800637 if (!memberDeclaration) {
638 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
640 }
chaoc771d89f2017-01-13 01:10:53 -0800641 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800642 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800643 if (!memberDeclaration) {
644 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
645 builder.addCapability(spv::CapabilityPerViewAttributesNV);
646 }
chaocdf3956c2017-02-14 14:52:34 -0800647 return spv::BuiltInPositionPerViewNV;
648 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800649 if (!memberDeclaration) {
650 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
651 builder.addCapability(spv::CapabilityPerViewAttributesNV);
652 }
chaocdf3956c2017-02-14 14:52:34 -0800653 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700654 case glslang::EbvFragFullyCoveredNV:
655 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
656 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
657 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800658#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800659 default:
660 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600661 }
662}
663
Rex Xufc618912015-09-09 16:42:49 +0800664// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700665spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800666{
667 assert(type.getBasicType() == glslang::EbtSampler);
668
John Kessenich5d0fa972016-02-15 11:57:00 -0700669 // Check for capabilities
670 switch (type.getQualifier().layoutFormat) {
671 case glslang::ElfRg32f:
672 case glslang::ElfRg16f:
673 case glslang::ElfR11fG11fB10f:
674 case glslang::ElfR16f:
675 case glslang::ElfRgba16:
676 case glslang::ElfRgb10A2:
677 case glslang::ElfRg16:
678 case glslang::ElfRg8:
679 case glslang::ElfR16:
680 case glslang::ElfR8:
681 case glslang::ElfRgba16Snorm:
682 case glslang::ElfRg16Snorm:
683 case glslang::ElfRg8Snorm:
684 case glslang::ElfR16Snorm:
685 case glslang::ElfR8Snorm:
686
687 case glslang::ElfRg32i:
688 case glslang::ElfRg16i:
689 case glslang::ElfRg8i:
690 case glslang::ElfR16i:
691 case glslang::ElfR8i:
692
693 case glslang::ElfRgb10a2ui:
694 case glslang::ElfRg32ui:
695 case glslang::ElfRg16ui:
696 case glslang::ElfRg8ui:
697 case glslang::ElfR16ui:
698 case glslang::ElfR8ui:
699 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
700 break;
701
702 default:
703 break;
704 }
705
706 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800707 switch (type.getQualifier().layoutFormat) {
708 case glslang::ElfNone: return spv::ImageFormatUnknown;
709 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
710 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
711 case glslang::ElfR32f: return spv::ImageFormatR32f;
712 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
713 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
714 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
715 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
716 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
717 case glslang::ElfR16f: return spv::ImageFormatR16f;
718 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
719 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
720 case glslang::ElfRg16: return spv::ImageFormatRg16;
721 case glslang::ElfRg8: return spv::ImageFormatRg8;
722 case glslang::ElfR16: return spv::ImageFormatR16;
723 case glslang::ElfR8: return spv::ImageFormatR8;
724 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
725 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
726 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
727 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
728 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
729 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
730 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
731 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
732 case glslang::ElfR32i: return spv::ImageFormatR32i;
733 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
734 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
735 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
736 case glslang::ElfR16i: return spv::ImageFormatR16i;
737 case glslang::ElfR8i: return spv::ImageFormatR8i;
738 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
739 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
740 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
741 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
742 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
743 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
744 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
745 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
746 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
747 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800749 }
750}
751
John Kesseniche18fd202018-01-30 11:01:39 -0700752spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800753{
John Kesseniche18fd202018-01-30 11:01:39 -0700754 if (selectionNode.getFlatten())
755 return spv::SelectionControlFlattenMask;
756 if (selectionNode.getDontFlatten())
757 return spv::SelectionControlDontFlattenMask;
758 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800759}
760
John Kesseniche18fd202018-01-30 11:01:39 -0700761spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600762{
John Kesseniche18fd202018-01-30 11:01:39 -0700763 if (switchNode.getFlatten())
764 return spv::SelectionControlFlattenMask;
765 if (switchNode.getDontFlatten())
766 return spv::SelectionControlDontFlattenMask;
767 return spv::SelectionControlMaskNone;
768}
769
John Kessenicha2858d92018-01-31 08:11:18 -0700770// return a non-0 dependency if the dependency argument must be set
771spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
772 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700773{
774 spv::LoopControlMask control = spv::LoopControlMaskNone;
775
776 if (loopNode.getDontUnroll())
777 control = control | spv::LoopControlDontUnrollMask;
778 if (loopNode.getUnroll())
779 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700780 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700781 control = control | spv::LoopControlDependencyInfiniteMask;
782 else if (loopNode.getLoopDependency() > 0) {
783 control = control | spv::LoopControlDependencyLengthMask;
784 dependencyLength = loopNode.getLoopDependency();
785 }
John Kesseniche18fd202018-01-30 11:01:39 -0700786
787 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600788}
789
John Kessenicha5c5fb62017-05-05 05:09:58 -0600790// Translate glslang type to SPIR-V storage class.
791spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
792{
793 if (type.getQualifier().isPipeInput())
794 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600795 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600796 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600797
798 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
799 type.getQualifier().storage == glslang::EvqUniform) {
800 if (type.getBasicType() == glslang::EbtAtomicUint)
801 return spv::StorageClassAtomicCounter;
802 if (type.containsOpaque())
803 return spv::StorageClassUniformConstant;
804 }
805
806 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600807 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
808 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600809 }
810
811 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600812 if (type.getQualifier().layoutPushConstant)
813 return spv::StorageClassPushConstant;
814 if (type.getBasicType() == glslang::EbtBlock)
815 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600816 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600817 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600818
819 switch (type.getQualifier().storage) {
820 case glslang::EvqShared: return spv::StorageClassWorkgroup;
821 case glslang::EvqGlobal: return spv::StorageClassPrivate;
822 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
823 case glslang::EvqTemporary: return spv::StorageClassFunction;
824 default:
825 assert(0);
826 break;
827 }
828
829 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600830}
831
qining25262b32016-05-06 17:25:16 -0400832// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700833// descriptor set.
834bool IsDescriptorResource(const glslang::TType& type)
835{
John Kessenichf7497e22016-03-08 21:36:22 -0700836 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700837 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700838 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700839
840 // non block...
841 // basically samplerXXX/subpass/sampler/texture are all included
842 // if they are the global-scope-class, not the function parameter
843 // (or local, if they ever exist) class.
844 if (type.getBasicType() == glslang::EbtSampler)
845 return type.getQualifier().isUniformOrBuffer();
846
847 // None of the above.
848 return false;
849}
850
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
852{
853 if (child.layoutMatrix == glslang::ElmNone)
854 child.layoutMatrix = parent.layoutMatrix;
855
856 if (parent.invariant)
857 child.invariant = true;
858 if (parent.nopersp)
859 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800860#ifdef AMD_EXTENSIONS
861 if (parent.explicitInterp)
862 child.explicitInterp = true;
863#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864 if (parent.flat)
865 child.flat = true;
866 if (parent.centroid)
867 child.centroid = true;
868 if (parent.patch)
869 child.patch = true;
870 if (parent.sample)
871 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800872 if (parent.coherent)
873 child.coherent = true;
874 if (parent.volatil)
875 child.volatil = true;
876 if (parent.restrict)
877 child.restrict = true;
878 if (parent.readonly)
879 child.readonly = true;
880 if (parent.writeonly)
881 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700882}
883
John Kessenichf2b7f332016-09-01 17:05:23 -0600884bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700885{
John Kessenich7b9fa252016-01-21 18:56:57 -0700886 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600887 // - struct members might inherit from a struct declaration
888 // (note that non-block structs don't explicitly inherit,
889 // only implicitly, meaning no decoration involved)
890 // - affect decorations on the struct members
891 // (note smooth does not, and expecting something like volatile
892 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700893 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600894 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700895}
896
John Kessenich140f3df2015-06-26 16:58:36 -0600897//
898// Implement the TGlslangToSpvTraverser class.
899//
900
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700901TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600902 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
903 : TIntermTraverser(true, false, true),
904 options(options),
905 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600906 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700907 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700908 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600909 glslangIntermediate(glslangIntermediate)
910{
911 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
912
913 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600914 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
915 glslangIntermediate->getVersion());
916
John Kessenich121853f2017-05-31 17:11:16 -0600917 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600918 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600919 builder.setSourceFile(glslangIntermediate->getSourceFile());
920
921 // Set the source shader's text. If for SPV version 1.0, include
922 // a preamble in comments stating the OpModuleProcessed instructions.
923 // Otherwise, emit those as actual instructions.
924 std::string text;
925 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
926 for (int p = 0; p < (int)processes.size(); ++p) {
927 if (glslangIntermediate->getSpv().spv < 0x00010100) {
928 text.append("// OpModuleProcessed ");
929 text.append(processes[p]);
930 text.append("\n");
931 } else
932 builder.addModuleProcessed(processes[p]);
933 }
934 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
935 text.append("#line 1\n");
936 text.append(glslangIntermediate->getSourceText());
937 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939 stdBuiltins = builder.import("GLSL.std.450");
940 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600941 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
942 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600943
944 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600945 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
946 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600947 builder.addSourceExtension(it->c_str());
948
949 // Add the top-level modes for this shader.
950
John Kessenich92187592016-02-01 13:45:25 -0700951 if (glslangIntermediate->getXfbMode()) {
952 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700954 }
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 unsigned int mode;
957 switch (glslangIntermediate->getStage()) {
958 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600959 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600960 break;
961
steve-lunarge7412492017-03-23 11:56:07 -0600962 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600963 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600965
steve-lunarge7412492017-03-23 11:56:07 -0600966 glslang::TLayoutGeometry primitive;
967
968 if (glslangIntermediate->getStage() == EShLangTessControl) {
969 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
970 primitive = glslangIntermediate->getOutputPrimitive();
971 } else {
972 primitive = glslangIntermediate->getInputPrimitive();
973 }
974
975 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700976 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
977 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
978 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600979 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600980 }
John Kessenich4016e382016-07-15 11:53:56 -0600981 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600982 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
983
John Kesseniche6903322015-10-13 16:29:02 -0600984 switch (glslangIntermediate->getVertexSpacing()) {
985 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
986 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
987 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600988 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600989 }
John Kessenich4016e382016-07-15 11:53:56 -0600990 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600991 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
992
993 switch (glslangIntermediate->getVertexOrder()) {
994 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
995 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600996 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600997 }
John Kessenich4016e382016-07-15 11:53:56 -0600998 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600999 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1000
1001 if (glslangIntermediate->getPointMode())
1002 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 break;
1004
1005 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001006 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001007 switch (glslangIntermediate->getInputPrimitive()) {
1008 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1009 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1010 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001011 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001012 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001013 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001014 }
John Kessenich4016e382016-07-15 11:53:56 -06001015 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001016 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001017
John Kessenich140f3df2015-06-26 16:58:36 -06001018 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1019
1020 switch (glslangIntermediate->getOutputPrimitive()) {
1021 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1022 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1023 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001024 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001025 }
John Kessenich4016e382016-07-15 11:53:56 -06001026 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001027 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1028 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1029 break;
1030
1031 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001032 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001033 if (glslangIntermediate->getPixelCenterInteger())
1034 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 if (glslangIntermediate->getOriginUpperLeft())
1037 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001038 else
1039 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001040
1041 if (glslangIntermediate->getEarlyFragmentTests())
1042 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1043
chaocc1204522017-06-30 17:14:30 -07001044 if (glslangIntermediate->getPostDepthCoverage()) {
1045 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1046 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1047 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1048 }
1049
John Kesseniche6903322015-10-13 16:29:02 -06001050 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001051 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1052 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001053 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001054 }
John Kessenich4016e382016-07-15 11:53:56 -06001055 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001056 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1057
1058 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1059 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001060 break;
1061
1062 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001063 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001064 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1065 glslangIntermediate->getLocalSize(1),
1066 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001067 break;
1068
1069 default:
1070 break;
1071 }
John Kessenich140f3df2015-06-26 16:58:36 -06001072}
1073
John Kessenichfca82622016-11-26 13:23:20 -07001074// Finish creating SPV, after the traversal is complete.
1075void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001076{
John Kessenich517fe7a2016-11-26 13:31:47 -07001077 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001078 builder.setBuildPoint(shaderEntry->getLastBlock());
1079 builder.leaveFunction();
1080 }
1081
John Kessenich7ba63412015-12-20 17:37:07 -07001082 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001083 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1084 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001085
qiningda397332016-03-09 19:54:03 -05001086 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001087}
1088
John Kessenichfca82622016-11-26 13:23:20 -07001089// Write the SPV into 'out'.
1090void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001091{
John Kessenichfca82622016-11-26 13:23:20 -07001092 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001093}
1094
1095//
1096// Implement the traversal functions.
1097//
1098// Return true from interior nodes to have the external traversal
1099// continue on to children. Return false if children were
1100// already processed.
1101//
1102
1103//
qining25262b32016-05-06 17:25:16 -04001104// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001105// - uniform/input reads
1106// - output writes
1107// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1108// - something simple that degenerates into the last bullet
1109//
1110void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1111{
qining75d1d802016-04-06 14:42:01 -04001112 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1113 if (symbol->getType().getQualifier().isSpecConstant())
1114 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1115
John Kessenich140f3df2015-06-26 16:58:36 -06001116 // getSymbolId() will set up all the IO decorations on the first call.
1117 // Formal function parameters were mapped during makeFunctions().
1118 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001119
1120 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1121 if (builder.isPointer(id)) {
1122 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001123 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1124 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1125 iOSet.insert(id);
1126 }
John Kessenich7ba63412015-12-20 17:37:07 -07001127 }
1128
1129 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001130 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001131 // Prepare to generate code for the access
1132
1133 // L-value chains will be computed left to right. We're on the symbol now,
1134 // which is the left-most part of the access chain, so now is "clear" time,
1135 // followed by setting the base.
1136 builder.clearAccessChain();
1137
1138 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001139 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001140 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001141 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001142 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001143 // These are also pure R-values.
1144 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001145 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001146 builder.setAccessChainRValue(id);
1147 else
1148 builder.setAccessChainLValue(id);
1149 }
1150}
1151
1152bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1153{
John Kesseniche485c7a2017-05-31 18:50:53 -06001154 builder.setLine(node->getLoc().line);
1155
qining40887662016-04-03 22:20:42 -04001156 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1157 if (node->getType().getQualifier().isSpecConstant())
1158 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1159
John Kessenich140f3df2015-06-26 16:58:36 -06001160 // First, handle special cases
1161 switch (node->getOp()) {
1162 case glslang::EOpAssign:
1163 case glslang::EOpAddAssign:
1164 case glslang::EOpSubAssign:
1165 case glslang::EOpMulAssign:
1166 case glslang::EOpVectorTimesMatrixAssign:
1167 case glslang::EOpVectorTimesScalarAssign:
1168 case glslang::EOpMatrixTimesScalarAssign:
1169 case glslang::EOpMatrixTimesMatrixAssign:
1170 case glslang::EOpDivAssign:
1171 case glslang::EOpModAssign:
1172 case glslang::EOpAndAssign:
1173 case glslang::EOpInclusiveOrAssign:
1174 case glslang::EOpExclusiveOrAssign:
1175 case glslang::EOpLeftShiftAssign:
1176 case glslang::EOpRightShiftAssign:
1177 // A bin-op assign "a += b" means the same thing as "a = a + b"
1178 // where a is evaluated before b. For a simple assignment, GLSL
1179 // says to evaluate the left before the right. So, always, left
1180 // node then right node.
1181 {
1182 // get the left l-value, save it away
1183 builder.clearAccessChain();
1184 node->getLeft()->traverse(this);
1185 spv::Builder::AccessChain lValue = builder.getAccessChain();
1186
1187 // evaluate the right
1188 builder.clearAccessChain();
1189 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001190 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 if (node->getOp() != glslang::EOpAssign) {
1193 // the left is also an r-value
1194 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001195 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001196
1197 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001198 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001199 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001200 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1201 node->getType().getBasicType());
1202
1203 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001204 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206
1207 // store the result
1208 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001209 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001210
1211 // assignments are expressions having an rValue after they are evaluated...
1212 builder.clearAccessChain();
1213 builder.setAccessChainRValue(rValue);
1214 }
1215 return false;
1216 case glslang::EOpIndexDirect:
1217 case glslang::EOpIndexDirectStruct:
1218 {
1219 // Get the left part of the access chain.
1220 node->getLeft()->traverse(this);
1221
1222 // Add the next element in the chain
1223
David Netoa901ffe2016-06-08 14:11:40 +01001224 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001225 if (! node->getLeft()->getType().isArray() &&
1226 node->getLeft()->getType().isVector() &&
1227 node->getOp() == glslang::EOpIndexDirect) {
1228 // This is essentially a hard-coded vector swizzle of size 1,
1229 // so short circuit the access-chain stuff with a swizzle.
1230 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001231 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001232 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001233 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001234 int spvIndex = glslangIndex;
1235 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1236 node->getOp() == glslang::EOpIndexDirectStruct)
1237 {
1238 // This may be, e.g., an anonymous block-member selection, which generally need
1239 // index remapping due to hidden members in anonymous blocks.
1240 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1241 assert(remapper.size() > 0);
1242 spvIndex = remapper[glslangIndex];
1243 }
John Kessenichebb50532016-05-16 19:22:05 -06001244
David Netoa901ffe2016-06-08 14:11:40 +01001245 // normal case for indexing array or structure or block
1246 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1247
1248 // Add capabilities here for accessing PointSize and clip/cull distance.
1249 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001250 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001251 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001252 }
1253 }
1254 return false;
1255 case glslang::EOpIndexIndirect:
1256 {
1257 // Structure or array or vector indirection.
1258 // Will use native SPIR-V access-chain for struct and array indirection;
1259 // matrices are arrays of vectors, so will also work for a matrix.
1260 // Will use the access chain's 'component' for variable index into a vector.
1261
1262 // This adapter is building access chains left to right.
1263 // Set up the access chain to the left.
1264 node->getLeft()->traverse(this);
1265
1266 // save it so that computing the right side doesn't trash it
1267 spv::Builder::AccessChain partial = builder.getAccessChain();
1268
1269 // compute the next index in the chain
1270 builder.clearAccessChain();
1271 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001272 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001273
1274 // restore the saved access chain
1275 builder.setAccessChain(partial);
1276
1277 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001278 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001279 else
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001281 }
1282 return false;
1283 case glslang::EOpVectorSwizzle:
1284 {
1285 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001286 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001287 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001288 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001289 }
1290 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001291 case glslang::EOpMatrixSwizzle:
1292 logger->missingFunctionality("matrix swizzle");
1293 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001294 case glslang::EOpLogicalOr:
1295 case glslang::EOpLogicalAnd:
1296 {
1297
1298 // These may require short circuiting, but can sometimes be done as straight
1299 // binary operations. The right operand must be short circuited if it has
1300 // side effects, and should probably be if it is complex.
1301 if (isTrivial(node->getRight()->getAsTyped()))
1302 break; // handle below as a normal binary operation
1303 // otherwise, we need to do dynamic short circuiting on the right operand
1304 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1305 builder.clearAccessChain();
1306 builder.setAccessChainRValue(result);
1307 }
1308 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001309 default:
1310 break;
1311 }
1312
1313 // Assume generic binary op...
1314
John Kessenich32cfd492016-02-02 12:37:46 -07001315 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001316 builder.clearAccessChain();
1317 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001318 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001319
John Kessenich32cfd492016-02-02 12:37:46 -07001320 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001321 builder.clearAccessChain();
1322 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001323 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001324
John Kessenich32cfd492016-02-02 12:37:46 -07001325 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001326 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001327 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001328 convertGlslangToSpvType(node->getType()), left, right,
1329 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001330
John Kessenich50e57562015-12-21 21:21:11 -07001331 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001332 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001333 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001334 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001335 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001336 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001337 return false;
1338 }
John Kessenich140f3df2015-06-26 16:58:36 -06001339}
1340
1341bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1342{
John Kesseniche485c7a2017-05-31 18:50:53 -06001343 builder.setLine(node->getLoc().line);
1344
qining40887662016-04-03 22:20:42 -04001345 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1346 if (node->getType().getQualifier().isSpecConstant())
1347 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1348
John Kessenichfc51d282015-08-19 13:34:18 -06001349 spv::Id result = spv::NoResult;
1350
1351 // try texturing first
1352 result = createImageTextureFunctionCall(node);
1353 if (result != spv::NoResult) {
1354 builder.clearAccessChain();
1355 builder.setAccessChainRValue(result);
1356
1357 return false; // done with this node
1358 }
1359
1360 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001361
1362 if (node->getOp() == glslang::EOpArrayLength) {
1363 // Quite special; won't want to evaluate the operand.
1364
1365 // Normal .length() would have been constant folded by the front-end.
1366 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001367 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001368 assert(node->getOperand()->getType().isRuntimeSizedArray());
1369 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1370 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001371 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1372 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001373
1374 builder.clearAccessChain();
1375 builder.setAccessChainRValue(length);
1376
1377 return false;
1378 }
1379
John Kessenichfc51d282015-08-19 13:34:18 -06001380 // Start by evaluating the operand
1381
John Kessenich8c8505c2016-07-26 12:50:38 -06001382 // Does it need a swizzle inversion? If so, evaluation is inverted;
1383 // operate first on the swizzle base, then apply the swizzle.
1384 spv::Id invertedType = spv::NoType;
1385 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1386 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1387 invertedType = getInvertedSwizzleType(*node->getOperand());
1388
John Kessenich140f3df2015-06-26 16:58:36 -06001389 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 if (invertedType != spv::NoType)
1391 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1392 else
1393 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001394
Rex Xufc618912015-09-09 16:42:49 +08001395 spv::Id operand = spv::NoResult;
1396
1397 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1398 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001399 node->getOp() == glslang::EOpAtomicCounter ||
1400 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001401 operand = builder.accessChainGetLValue(); // Special case l-value operands
1402 else
John Kessenich32cfd492016-02-02 12:37:46 -07001403 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
John Kessenichf6640762016-08-01 19:44:00 -06001405 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001406 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001407
1408 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001409 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001410 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 // if not, then possibly an operation
1413 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001414 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001415
1416 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001417 if (invertedType)
1418 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1419
John Kessenich140f3df2015-06-26 16:58:36 -06001420 builder.clearAccessChain();
1421 builder.setAccessChainRValue(result);
1422
1423 return false; // done with this node
1424 }
1425
1426 // it must be a special case, check...
1427 switch (node->getOp()) {
1428 case glslang::EOpPostIncrement:
1429 case glslang::EOpPostDecrement:
1430 case glslang::EOpPreIncrement:
1431 case glslang::EOpPreDecrement:
1432 {
1433 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001434 spv::Id one = 0;
1435 if (node->getBasicType() == glslang::EbtFloat)
1436 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001437 else if (node->getBasicType() == glslang::EbtDouble)
1438 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001439#ifdef AMD_EXTENSIONS
1440 else if (node->getBasicType() == glslang::EbtFloat16)
1441 one = builder.makeFloat16Constant(1.0F);
1442#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001443 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1444 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001445#ifdef AMD_EXTENSIONS
1446 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1447 one = builder.makeInt16Constant(1);
1448#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001449 else
1450 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001451 glslang::TOperator op;
1452 if (node->getOp() == glslang::EOpPreIncrement ||
1453 node->getOp() == glslang::EOpPostIncrement)
1454 op = glslang::EOpAdd;
1455 else
1456 op = glslang::EOpSub;
1457
John Kessenichf6640762016-08-01 19:44:00 -06001458 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001459 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001460 convertGlslangToSpvType(node->getType()), operand, one,
1461 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001462 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001463
1464 // The result of operation is always stored, but conditionally the
1465 // consumed result. The consumed result is always an r-value.
1466 builder.accessChainStore(result);
1467 builder.clearAccessChain();
1468 if (node->getOp() == glslang::EOpPreIncrement ||
1469 node->getOp() == glslang::EOpPreDecrement)
1470 builder.setAccessChainRValue(result);
1471 else
1472 builder.setAccessChainRValue(operand);
1473 }
1474
1475 return false;
1476
1477 case glslang::EOpEmitStreamVertex:
1478 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1479 return false;
1480 case glslang::EOpEndStreamPrimitive:
1481 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1482 return false;
1483
1484 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001485 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001486 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001487 }
John Kessenich140f3df2015-06-26 16:58:36 -06001488}
1489
1490bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1491{
qining27e04a02016-04-14 16:40:20 -04001492 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1493 if (node->getType().getQualifier().isSpecConstant())
1494 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1495
John Kessenichfc51d282015-08-19 13:34:18 -06001496 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001497 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1498 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001499
1500 // try texturing
1501 result = createImageTextureFunctionCall(node);
1502 if (result != spv::NoResult) {
1503 builder.clearAccessChain();
1504 builder.setAccessChainRValue(result);
1505
1506 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001507#ifdef AMD_EXTENSIONS
1508 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1509#else
John Kessenich56bab042015-09-16 10:54:31 -06001510 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001511#endif
Rex Xufc618912015-09-09 16:42:49 +08001512 // "imageStore" is a special case, which has no result
1513 return false;
1514 }
John Kessenichfc51d282015-08-19 13:34:18 -06001515
John Kessenich140f3df2015-06-26 16:58:36 -06001516 glslang::TOperator binOp = glslang::EOpNull;
1517 bool reduceComparison = true;
1518 bool isMatrix = false;
1519 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001520 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001521
1522 assert(node->getOp());
1523
John Kessenichf6640762016-08-01 19:44:00 -06001524 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001525
1526 switch (node->getOp()) {
1527 case glslang::EOpSequence:
1528 {
1529 if (preVisit)
1530 ++sequenceDepth;
1531 else
1532 --sequenceDepth;
1533
1534 if (sequenceDepth == 1) {
1535 // If this is the parent node of all the functions, we want to see them
1536 // early, so all call points have actual SPIR-V functions to reference.
1537 // In all cases, still let the traverser visit the children for us.
1538 makeFunctions(node->getAsAggregate()->getSequence());
1539
John Kessenich6fccb3c2016-09-19 16:01:41 -06001540 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001541 // anything else gets there, so visit out of order, doing them all now.
1542 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1543
John Kessenich6a60c2f2016-12-08 21:01:59 -07001544 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001545 // so do them manually.
1546 visitFunctions(node->getAsAggregate()->getSequence());
1547
1548 return false;
1549 }
1550
1551 return true;
1552 }
1553 case glslang::EOpLinkerObjects:
1554 {
1555 if (visit == glslang::EvPreVisit)
1556 linkageOnly = true;
1557 else
1558 linkageOnly = false;
1559
1560 return true;
1561 }
1562 case glslang::EOpComma:
1563 {
1564 // processing from left to right naturally leaves the right-most
1565 // lying around in the access chain
1566 glslang::TIntermSequence& glslangOperands = node->getSequence();
1567 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1568 glslangOperands[i]->traverse(this);
1569
1570 return false;
1571 }
1572 case glslang::EOpFunction:
1573 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001574 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001575 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001577 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001578 } else {
1579 handleFunctionEntry(node);
1580 }
1581 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001582 if (inEntryPoint)
1583 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001584 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001585 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001586 }
1587
1588 return true;
1589 case glslang::EOpParameters:
1590 // Parameters will have been consumed by EOpFunction processing, but not
1591 // the body, so we still visited the function node's children, making this
1592 // child redundant.
1593 return false;
1594 case glslang::EOpFunctionCall:
1595 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001596 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001597 if (node->isUserDefined())
1598 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001599 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001600 if (result) {
1601 builder.clearAccessChain();
1602 builder.setAccessChainRValue(result);
1603 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001604 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001605
1606 return false;
1607 }
1608 case glslang::EOpConstructMat2x2:
1609 case glslang::EOpConstructMat2x3:
1610 case glslang::EOpConstructMat2x4:
1611 case glslang::EOpConstructMat3x2:
1612 case glslang::EOpConstructMat3x3:
1613 case glslang::EOpConstructMat3x4:
1614 case glslang::EOpConstructMat4x2:
1615 case glslang::EOpConstructMat4x3:
1616 case glslang::EOpConstructMat4x4:
1617 case glslang::EOpConstructDMat2x2:
1618 case glslang::EOpConstructDMat2x3:
1619 case glslang::EOpConstructDMat2x4:
1620 case glslang::EOpConstructDMat3x2:
1621 case glslang::EOpConstructDMat3x3:
1622 case glslang::EOpConstructDMat3x4:
1623 case glslang::EOpConstructDMat4x2:
1624 case glslang::EOpConstructDMat4x3:
1625 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001626 case glslang::EOpConstructIMat2x2:
1627 case glslang::EOpConstructIMat2x3:
1628 case glslang::EOpConstructIMat2x4:
1629 case glslang::EOpConstructIMat3x2:
1630 case glslang::EOpConstructIMat3x3:
1631 case glslang::EOpConstructIMat3x4:
1632 case glslang::EOpConstructIMat4x2:
1633 case glslang::EOpConstructIMat4x3:
1634 case glslang::EOpConstructIMat4x4:
1635 case glslang::EOpConstructUMat2x2:
1636 case glslang::EOpConstructUMat2x3:
1637 case glslang::EOpConstructUMat2x4:
1638 case glslang::EOpConstructUMat3x2:
1639 case glslang::EOpConstructUMat3x3:
1640 case glslang::EOpConstructUMat3x4:
1641 case glslang::EOpConstructUMat4x2:
1642 case glslang::EOpConstructUMat4x3:
1643 case glslang::EOpConstructUMat4x4:
1644 case glslang::EOpConstructBMat2x2:
1645 case glslang::EOpConstructBMat2x3:
1646 case glslang::EOpConstructBMat2x4:
1647 case glslang::EOpConstructBMat3x2:
1648 case glslang::EOpConstructBMat3x3:
1649 case glslang::EOpConstructBMat3x4:
1650 case glslang::EOpConstructBMat4x2:
1651 case glslang::EOpConstructBMat4x3:
1652 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001653#ifdef AMD_EXTENSIONS
1654 case glslang::EOpConstructF16Mat2x2:
1655 case glslang::EOpConstructF16Mat2x3:
1656 case glslang::EOpConstructF16Mat2x4:
1657 case glslang::EOpConstructF16Mat3x2:
1658 case glslang::EOpConstructF16Mat3x3:
1659 case glslang::EOpConstructF16Mat3x4:
1660 case glslang::EOpConstructF16Mat4x2:
1661 case glslang::EOpConstructF16Mat4x3:
1662 case glslang::EOpConstructF16Mat4x4:
1663#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001664 isMatrix = true;
1665 // fall through
1666 case glslang::EOpConstructFloat:
1667 case glslang::EOpConstructVec2:
1668 case glslang::EOpConstructVec3:
1669 case glslang::EOpConstructVec4:
1670 case glslang::EOpConstructDouble:
1671 case glslang::EOpConstructDVec2:
1672 case glslang::EOpConstructDVec3:
1673 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001674#ifdef AMD_EXTENSIONS
1675 case glslang::EOpConstructFloat16:
1676 case glslang::EOpConstructF16Vec2:
1677 case glslang::EOpConstructF16Vec3:
1678 case glslang::EOpConstructF16Vec4:
1679#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001680 case glslang::EOpConstructBool:
1681 case glslang::EOpConstructBVec2:
1682 case glslang::EOpConstructBVec3:
1683 case glslang::EOpConstructBVec4:
1684 case glslang::EOpConstructInt:
1685 case glslang::EOpConstructIVec2:
1686 case glslang::EOpConstructIVec3:
1687 case glslang::EOpConstructIVec4:
1688 case glslang::EOpConstructUint:
1689 case glslang::EOpConstructUVec2:
1690 case glslang::EOpConstructUVec3:
1691 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001692 case glslang::EOpConstructInt64:
1693 case glslang::EOpConstructI64Vec2:
1694 case glslang::EOpConstructI64Vec3:
1695 case glslang::EOpConstructI64Vec4:
1696 case glslang::EOpConstructUint64:
1697 case glslang::EOpConstructU64Vec2:
1698 case glslang::EOpConstructU64Vec3:
1699 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001700#ifdef AMD_EXTENSIONS
1701 case glslang::EOpConstructInt16:
1702 case glslang::EOpConstructI16Vec2:
1703 case glslang::EOpConstructI16Vec3:
1704 case glslang::EOpConstructI16Vec4:
1705 case glslang::EOpConstructUint16:
1706 case glslang::EOpConstructU16Vec2:
1707 case glslang::EOpConstructU16Vec3:
1708 case glslang::EOpConstructU16Vec4:
1709#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001710 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001711 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001712 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001713 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001714 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001715 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001717 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001718 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001719 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001720 std::vector<spv::Id> constituents;
1721 for (int c = 0; c < (int)arguments.size(); ++c)
1722 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001723 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001724 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001725 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001726 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001727 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001728
1729 builder.clearAccessChain();
1730 builder.setAccessChainRValue(constructed);
1731
1732 return false;
1733 }
1734
1735 // These six are component-wise compares with component-wise results.
1736 // Forward on to createBinaryOperation(), requesting a vector result.
1737 case glslang::EOpLessThan:
1738 case glslang::EOpGreaterThan:
1739 case glslang::EOpLessThanEqual:
1740 case glslang::EOpGreaterThanEqual:
1741 case glslang::EOpVectorEqual:
1742 case glslang::EOpVectorNotEqual:
1743 {
1744 // Map the operation to a binary
1745 binOp = node->getOp();
1746 reduceComparison = false;
1747 switch (node->getOp()) {
1748 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1749 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1750 default: binOp = node->getOp(); break;
1751 }
1752
1753 break;
1754 }
1755 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001756 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001757 binOp = glslang::EOpMul;
1758 break;
1759 case glslang::EOpOuterProduct:
1760 // two vectors multiplied to make a matrix
1761 binOp = glslang::EOpOuterProduct;
1762 break;
1763 case glslang::EOpDot:
1764 {
qining25262b32016-05-06 17:25:16 -04001765 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001766 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001767 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001768 binOp = glslang::EOpMul;
1769 break;
1770 }
1771 case glslang::EOpMod:
1772 // when an aggregate, this is the floating-point mod built-in function,
1773 // which can be emitted by the one in createBinaryOperation()
1774 binOp = glslang::EOpMod;
1775 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001776 case glslang::EOpEmitVertex:
1777 case glslang::EOpEndPrimitive:
1778 case glslang::EOpBarrier:
1779 case glslang::EOpMemoryBarrier:
1780 case glslang::EOpMemoryBarrierAtomicCounter:
1781 case glslang::EOpMemoryBarrierBuffer:
1782 case glslang::EOpMemoryBarrierImage:
1783 case glslang::EOpMemoryBarrierShared:
1784 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001785 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001786 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001787 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001788 case glslang::EOpWorkgroupMemoryBarrier:
1789 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001790 noReturnValue = true;
1791 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1792 break;
1793
John Kessenich426394d2015-07-23 10:22:48 -06001794 case glslang::EOpAtomicAdd:
1795 case glslang::EOpAtomicMin:
1796 case glslang::EOpAtomicMax:
1797 case glslang::EOpAtomicAnd:
1798 case glslang::EOpAtomicOr:
1799 case glslang::EOpAtomicXor:
1800 case glslang::EOpAtomicExchange:
1801 case glslang::EOpAtomicCompSwap:
1802 atomic = true;
1803 break;
1804
John Kessenich0d0c6d32017-07-23 16:08:26 -06001805 case glslang::EOpAtomicCounterAdd:
1806 case glslang::EOpAtomicCounterSubtract:
1807 case glslang::EOpAtomicCounterMin:
1808 case glslang::EOpAtomicCounterMax:
1809 case glslang::EOpAtomicCounterAnd:
1810 case glslang::EOpAtomicCounterOr:
1811 case glslang::EOpAtomicCounterXor:
1812 case glslang::EOpAtomicCounterExchange:
1813 case glslang::EOpAtomicCounterCompSwap:
1814 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1815 builder.addCapability(spv::CapabilityAtomicStorageOps);
1816 atomic = true;
1817 break;
1818
John Kessenich140f3df2015-06-26 16:58:36 -06001819 default:
1820 break;
1821 }
1822
1823 //
1824 // See if it maps to a regular operation.
1825 //
John Kessenich140f3df2015-06-26 16:58:36 -06001826 if (binOp != glslang::EOpNull) {
1827 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1828 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1829 assert(left && right);
1830
1831 builder.clearAccessChain();
1832 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001833 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001834
1835 builder.clearAccessChain();
1836 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001837 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001838
John Kesseniche485c7a2017-05-31 18:50:53 -06001839 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001840 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001841 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001842 left->getType().getBasicType(), reduceComparison);
1843
1844 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001845 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 builder.clearAccessChain();
1847 builder.setAccessChainRValue(result);
1848
1849 return false;
1850 }
1851
John Kessenich426394d2015-07-23 10:22:48 -06001852 //
1853 // Create the list of operands.
1854 //
John Kessenich140f3df2015-06-26 16:58:36 -06001855 glslang::TIntermSequence& glslangOperands = node->getSequence();
1856 std::vector<spv::Id> operands;
1857 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 // special case l-value operands; there are just a few
1859 bool lvalue = false;
1860 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001861 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001862 case glslang::EOpModf:
1863 if (arg == 1)
1864 lvalue = true;
1865 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001866 case glslang::EOpInterpolateAtSample:
1867 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001868#ifdef AMD_EXTENSIONS
1869 case glslang::EOpInterpolateAtVertex:
1870#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001871 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001872 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001873
1874 // Does it need a swizzle inversion? If so, evaluation is inverted;
1875 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001876 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001877 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1878 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1879 }
Rex Xu7a26c172015-12-08 17:12:09 +08001880 break;
Rex Xud4782c12015-09-06 16:30:11 +08001881 case glslang::EOpAtomicAdd:
1882 case glslang::EOpAtomicMin:
1883 case glslang::EOpAtomicMax:
1884 case glslang::EOpAtomicAnd:
1885 case glslang::EOpAtomicOr:
1886 case glslang::EOpAtomicXor:
1887 case glslang::EOpAtomicExchange:
1888 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001889 case glslang::EOpAtomicCounterAdd:
1890 case glslang::EOpAtomicCounterSubtract:
1891 case glslang::EOpAtomicCounterMin:
1892 case glslang::EOpAtomicCounterMax:
1893 case glslang::EOpAtomicCounterAnd:
1894 case glslang::EOpAtomicCounterOr:
1895 case glslang::EOpAtomicCounterXor:
1896 case glslang::EOpAtomicCounterExchange:
1897 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001898 if (arg == 0)
1899 lvalue = true;
1900 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001901 case glslang::EOpAddCarry:
1902 case glslang::EOpSubBorrow:
1903 if (arg == 2)
1904 lvalue = true;
1905 break;
1906 case glslang::EOpUMulExtended:
1907 case glslang::EOpIMulExtended:
1908 if (arg >= 2)
1909 lvalue = true;
1910 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001911 default:
1912 break;
1913 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001914 builder.clearAccessChain();
1915 if (invertedType != spv::NoType && arg == 0)
1916 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1917 else
1918 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 if (lvalue)
1920 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001921 else {
1922 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001923 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001924 }
John Kessenich140f3df2015-06-26 16:58:36 -06001925 }
John Kessenich426394d2015-07-23 10:22:48 -06001926
John Kesseniche485c7a2017-05-31 18:50:53 -06001927 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001928 if (atomic) {
1929 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001930 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001931 } else {
1932 // Pass through to generic operations.
1933 switch (glslangOperands.size()) {
1934 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001935 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001936 break;
1937 case 1:
qining25262b32016-05-06 17:25:16 -04001938 result = createUnaryOperation(
1939 node->getOp(), precision,
1940 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001941 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001942 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001943 break;
1944 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001945 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001946 break;
1947 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001948 if (invertedType)
1949 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 }
1951
1952 if (noReturnValue)
1953 return false;
1954
1955 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001956 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001957 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001958 } else {
1959 builder.clearAccessChain();
1960 builder.setAccessChainRValue(result);
1961 return false;
1962 }
1963}
1964
John Kessenich433e9ff2017-01-26 20:31:11 -07001965// This path handles both if-then-else and ?:
1966// The if-then-else has a node type of void, while
1967// ?: has either a void or a non-void node type
1968//
1969// Leaving the result, when not void:
1970// GLSL only has r-values as the result of a :?, but
1971// if we have an l-value, that can be more efficient if it will
1972// become the base of a complex r-value expression, because the
1973// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001974bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1975{
John Kessenich4bee5312018-02-20 21:29:05 -07001976 // See if it simple and safe, or required, to execute both sides.
1977 // Crucially, side effects must be either semantically required or avoided,
1978 // and there are performance trade-offs.
1979 // Return true if required or a good idea (and safe) to execute both sides,
1980 // false otherwise.
1981 const auto bothSidesPolicy = [&]() -> bool {
1982 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07001983 if (node->getTrueBlock() == nullptr ||
1984 node->getFalseBlock() == nullptr)
1985 return false;
1986
John Kessenich4bee5312018-02-20 21:29:05 -07001987 // required? (unless we write additional code to look for side effects
1988 // and make performance trade-offs if none are present)
1989 if (!node->getShortCircuit())
1990 return true;
1991
1992 // if not required to execute both, decide based on performance/practicality...
1993
1994 // see if OpSelect can handle it
1995 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1996 node->getBasicType() == glslang::EbtVoid)
1997 return false;
1998
John Kessenich433e9ff2017-01-26 20:31:11 -07001999 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2000 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2001
2002 // return true if a single operand to ? : is okay for OpSelect
2003 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002004 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002005 };
2006
2007 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2008 operandOkay(node->getFalseBlock()->getAsTyped());
2009 };
2010
John Kessenich4bee5312018-02-20 21:29:05 -07002011 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2012 // emit the condition before doing anything with selection
2013 node->getCondition()->traverse(this);
2014 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2015
2016 // Find a way of executing both sides and selecting the right result.
2017 const auto executeBothSides = [&]() -> void {
2018 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002019 node->getTrueBlock()->traverse(this);
2020 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2021 node->getFalseBlock()->traverse(this);
2022 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2023
John Kesseniche485c7a2017-05-31 18:50:53 -06002024 builder.setLine(node->getLoc().line);
2025
John Kessenich4bee5312018-02-20 21:29:05 -07002026 // done if void
2027 if (node->getBasicType() == glslang::EbtVoid)
2028 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002029
John Kessenich4bee5312018-02-20 21:29:05 -07002030 // emit code to select between trueValue and falseValue
2031
2032 // see if OpSelect can handle it
2033 if (node->getType().isScalar() || node->getType().isVector()) {
2034 // Emit OpSelect for this selection.
2035
2036 // smear condition to vector, if necessary (AST is always scalar)
2037 if (builder.isVector(trueValue))
2038 condition = builder.smearScalar(spv::NoPrecision, condition,
2039 builder.makeVectorType(builder.makeBoolType(),
2040 builder.getNumComponents(trueValue)));
2041
2042 // OpSelect
2043 result = builder.createTriOp(spv::OpSelect,
2044 convertGlslangToSpvType(node->getType()), condition,
2045 trueValue, falseValue);
2046
2047 builder.clearAccessChain();
2048 builder.setAccessChainRValue(result);
2049 } else {
2050 // We need control flow to select the result.
2051 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2052 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2053
2054 // Selection control:
2055 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2056
2057 // make an "if" based on the value created by the condition
2058 spv::Builder::If ifBuilder(condition, control, builder);
2059
2060 // emit the "then" statement
2061 builder.createStore(trueValue, result);
2062 ifBuilder.makeBeginElse();
2063 // emit the "else" statement
2064 builder.createStore(falseValue, result);
2065
2066 // finish off the control flow
2067 ifBuilder.makeEndIf();
2068
2069 builder.clearAccessChain();
2070 builder.setAccessChainLValue(result);
2071 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002072 };
2073
John Kessenich4bee5312018-02-20 21:29:05 -07002074 // Execute the one side needed, as per the condition
2075 const auto executeOneSide = [&]() {
2076 // Always emit control flow.
2077 if (node->getBasicType() != glslang::EbtVoid)
2078 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002079
John Kessenich4bee5312018-02-20 21:29:05 -07002080 // Selection control:
2081 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2082
2083 // make an "if" based on the value created by the condition
2084 spv::Builder::If ifBuilder(condition, control, builder);
2085
2086 // emit the "then" statement
2087 if (node->getTrueBlock() != nullptr) {
2088 node->getTrueBlock()->traverse(this);
2089 if (result != spv::NoResult)
2090 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2091 }
2092
2093 if (node->getFalseBlock() != nullptr) {
2094 ifBuilder.makeBeginElse();
2095 // emit the "else" statement
2096 node->getFalseBlock()->traverse(this);
2097 if (result != spv::NoResult)
2098 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2099 }
2100
2101 // finish off the control flow
2102 ifBuilder.makeEndIf();
2103
2104 if (result != spv::NoResult) {
2105 builder.clearAccessChain();
2106 builder.setAccessChainLValue(result);
2107 }
2108 };
2109
2110 // Try for OpSelect (or a requirement to execute both sides)
2111 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002112 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2113 if (node->getType().getQualifier().isSpecConstant())
2114 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002115 executeBothSides();
2116 } else
2117 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002118
2119 return false;
2120}
2121
2122bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2123{
2124 // emit and get the condition before doing anything with switch
2125 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002126 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002127
Rex Xu57e65922017-07-04 23:23:40 +08002128 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002129 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002130
John Kessenich140f3df2015-06-26 16:58:36 -06002131 // browse the children to sort out code segments
2132 int defaultSegment = -1;
2133 std::vector<TIntermNode*> codeSegments;
2134 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2135 std::vector<int> caseValues;
2136 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2137 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2138 TIntermNode* child = *c;
2139 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002140 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002141 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002142 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002143 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2144 } else
2145 codeSegments.push_back(child);
2146 }
2147
qining25262b32016-05-06 17:25:16 -04002148 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002149 // statements between the last case and the end of the switch statement
2150 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2151 (int)codeSegments.size() == defaultSegment)
2152 codeSegments.push_back(nullptr);
2153
2154 // make the switch statement
2155 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002156 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002157
2158 // emit all the code in the segments
2159 breakForLoop.push(false);
2160 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2161 builder.nextSwitchSegment(segmentBlocks, s);
2162 if (codeSegments[s])
2163 codeSegments[s]->traverse(this);
2164 else
2165 builder.addSwitchBreak();
2166 }
2167 breakForLoop.pop();
2168
2169 builder.endSwitch(segmentBlocks);
2170
2171 return false;
2172}
2173
2174void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2175{
2176 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002177 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002178
2179 builder.clearAccessChain();
2180 builder.setAccessChainRValue(constant);
2181}
2182
2183bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2184{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002185 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002186 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002187
2188 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002189 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2190 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002191
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002192 // Spec requires back edges to target header blocks, and every header block
2193 // must dominate its merge block. Make a header block first to ensure these
2194 // conditions are met. By definition, it will contain OpLoopMerge, followed
2195 // by a block-ending branch. But we don't want to put any other body/test
2196 // instructions in it, since the body/test may have arbitrary instructions,
2197 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002198 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002199 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002200 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002201 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002202 spv::Block& test = builder.makeNewBlock();
2203 builder.createBranch(&test);
2204
2205 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002206 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002207 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002208 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2209
2210 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002211 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002212 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002213 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002214 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002215 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002216
2217 builder.setBuildPoint(&blocks.continue_target);
2218 if (node->getTerminal())
2219 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002220 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002221 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002222 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002223 builder.createBranch(&blocks.body);
2224
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002225 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002226 builder.setBuildPoint(&blocks.body);
2227 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002228 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002229 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002230 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002231
2232 builder.setBuildPoint(&blocks.continue_target);
2233 if (node->getTerminal())
2234 node->getTerminal()->traverse(this);
2235 if (node->getTest()) {
2236 node->getTest()->traverse(this);
2237 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002238 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002239 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002240 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002241 // TODO: unless there was a break/return/discard instruction
2242 // somewhere in the body, this is an infinite loop, so we should
2243 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002244 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002245 }
John Kessenich140f3df2015-06-26 16:58:36 -06002246 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002247 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002248 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002249 return false;
2250}
2251
2252bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2253{
2254 if (node->getExpression())
2255 node->getExpression()->traverse(this);
2256
John Kesseniche485c7a2017-05-31 18:50:53 -06002257 builder.setLine(node->getLoc().line);
2258
John Kessenich140f3df2015-06-26 16:58:36 -06002259 switch (node->getFlowOp()) {
2260 case glslang::EOpKill:
2261 builder.makeDiscard();
2262 break;
2263 case glslang::EOpBreak:
2264 if (breakForLoop.top())
2265 builder.createLoopExit();
2266 else
2267 builder.addSwitchBreak();
2268 break;
2269 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002270 builder.createLoopContinue();
2271 break;
2272 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002273 if (node->getExpression()) {
2274 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2275 spv::Id returnId = accessChainLoad(glslangReturnType);
2276 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2277 builder.clearAccessChain();
2278 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2279 builder.setAccessChainLValue(copyId);
2280 multiTypeStore(glslangReturnType, returnId);
2281 returnId = builder.createLoad(copyId);
2282 }
2283 builder.makeReturn(false, returnId);
2284 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002285 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002286
2287 builder.clearAccessChain();
2288 break;
2289
2290 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002292 break;
2293 }
2294
2295 return false;
2296}
2297
2298spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2299{
qining25262b32016-05-06 17:25:16 -04002300 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002301 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002302 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002303 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002304 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002305 }
2306
2307 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002308 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002309 spv::Id spvType = convertGlslangToSpvType(node->getType());
2310
Rex Xuf89ad982017-04-07 23:22:33 +08002311#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002312 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2313 node->getType().containsBasicType(glslang::EbtInt16) ||
2314 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002315 if (contains16BitType) {
2316 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2317 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2318 builder.addCapability(spv::CapabilityStorageInputOutput16);
2319 } else if (storageClass == spv::StorageClassPushConstant) {
2320 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2321 builder.addCapability(spv::CapabilityStoragePushConstant16);
2322 } else if (storageClass == spv::StorageClassUniform) {
2323 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2324 builder.addCapability(spv::CapabilityStorageUniform16);
2325 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2326 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2327 }
2328 }
2329#endif
2330
John Kessenich140f3df2015-06-26 16:58:36 -06002331 const char* name = node->getName().c_str();
2332 if (glslang::IsAnonymous(name))
2333 name = "";
2334
2335 return builder.createVariable(storageClass, spvType, name);
2336}
2337
2338// Return type Id of the sampled type.
2339spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2340{
2341 switch (sampler.type) {
2342 case glslang::EbtFloat: return builder.makeFloatType(32);
2343 case glslang::EbtInt: return builder.makeIntType(32);
2344 case glslang::EbtUint: return builder.makeUintType(32);
2345 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002346 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002347 return builder.makeFloatType(32);
2348 }
2349}
2350
John Kessenich8c8505c2016-07-26 12:50:38 -06002351// If node is a swizzle operation, return the type that should be used if
2352// the swizzle base is first consumed by another operation, before the swizzle
2353// is applied.
2354spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2355{
John Kessenichecba76f2017-01-06 00:34:48 -07002356 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002357 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2358 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2359 else
2360 return spv::NoType;
2361}
2362
2363// When inverting a swizzle with a parent op, this function
2364// will apply the swizzle operation to a completed parent operation.
2365spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2366{
2367 std::vector<unsigned> swizzle;
2368 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2369 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2370}
2371
John Kessenich8c8505c2016-07-26 12:50:38 -06002372// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2373void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2374{
2375 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2376 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2377 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2378}
2379
John Kessenich3ac051e2015-12-20 11:29:16 -07002380// Convert from a glslang type to an SPV type, by calling into a
2381// recursive version of this function. This establishes the inherited
2382// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002383spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2384{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002385 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002386}
2387
2388// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002389// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002390// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002391spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002392{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002393 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002394
2395 switch (type.getBasicType()) {
2396 case glslang::EbtVoid:
2397 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002398 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002399 break;
2400 case glslang::EbtFloat:
2401 spvType = builder.makeFloatType(32);
2402 break;
2403 case glslang::EbtDouble:
2404 spvType = builder.makeFloatType(64);
2405 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002406#ifdef AMD_EXTENSIONS
2407 case glslang::EbtFloat16:
2408 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002409 spvType = builder.makeFloatType(16);
2410 break;
2411#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002412 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002413 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2414 // a 32-bit int where non-0 means true.
2415 if (explicitLayout != glslang::ElpNone)
2416 spvType = builder.makeUintType(32);
2417 else
2418 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002419 break;
2420 case glslang::EbtInt:
2421 spvType = builder.makeIntType(32);
2422 break;
2423 case glslang::EbtUint:
2424 spvType = builder.makeUintType(32);
2425 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002426 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002427 spvType = builder.makeIntType(64);
2428 break;
2429 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002430 spvType = builder.makeUintType(64);
2431 break;
Rex Xucabbb782017-03-24 13:41:14 +08002432#ifdef AMD_EXTENSIONS
2433 case glslang::EbtInt16:
2434 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2435 spvType = builder.makeIntType(16);
2436 break;
2437 case glslang::EbtUint16:
2438 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2439 spvType = builder.makeUintType(16);
2440 break;
2441#endif
John Kessenich426394d2015-07-23 10:22:48 -06002442 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002443 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002444 spvType = builder.makeUintType(32);
2445 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002446 case glslang::EbtSampler:
2447 {
2448 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002449 if (sampler.sampler) {
2450 // pure sampler
2451 spvType = builder.makeSamplerType();
2452 } else {
2453 // an image is present, make its type
2454 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2455 sampler.image ? 2 : 1, TranslateImageFormat(type));
2456 if (sampler.combined) {
2457 // already has both image and sampler, make the combined type
2458 spvType = builder.makeSampledImageType(spvType);
2459 }
John Kessenich55e7d112015-11-15 21:33:39 -07002460 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002461 }
John Kessenich140f3df2015-06-26 16:58:36 -06002462 break;
2463 case glslang::EbtStruct:
2464 case glslang::EbtBlock:
2465 {
2466 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002467 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002468
2469 // Try to share structs for different layouts, but not yet for other
2470 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002471 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002472 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002473 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002474 break;
2475
2476 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002477 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002478 memberRemapper[glslangMembers].resize(glslangMembers->size());
2479 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002480 }
2481 break;
2482 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002483 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002484 break;
2485 }
2486
2487 if (type.isMatrix())
2488 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2489 else {
2490 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2491 if (type.getVectorSize() > 1)
2492 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2493 }
2494
2495 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002496 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2497
John Kessenichc9a80832015-09-12 12:17:44 -06002498 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002499 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002500 // We need to decorate array strides for types needing explicit layout, except blocks.
2501 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002502 // Use a dummy glslang type for querying internal strides of
2503 // arrays of arrays, but using just a one-dimensional array.
2504 glslang::TType simpleArrayType(type, 0); // deference type of the array
2505 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2506 simpleArrayType.getArraySizes().dereference();
2507
2508 // Will compute the higher-order strides here, rather than making a whole
2509 // pile of types and doing repetitive recursion on their contents.
2510 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2511 }
John Kessenichf8842e52016-01-04 19:22:56 -07002512
2513 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002514 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002515 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002516 if (stride > 0)
2517 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002518 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002519 }
2520 } else {
2521 // single-dimensional array, and don't yet have stride
2522
John Kessenichf8842e52016-01-04 19:22:56 -07002523 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002524 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2525 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002526 }
John Kessenich31ed4832015-09-09 17:51:38 -06002527
John Kessenichc9a80832015-09-12 12:17:44 -06002528 // Do the outer dimension, which might not be known for a runtime-sized array
2529 if (type.isRuntimeSizedArray()) {
2530 spvType = builder.makeRuntimeArray(spvType);
2531 } else {
2532 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002533 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002534 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002535 if (stride > 0)
2536 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002537 }
2538
2539 return spvType;
2540}
2541
John Kessenich0e737842017-03-24 18:38:16 -06002542// TODO: this functionality should exist at a higher level, in creating the AST
2543//
2544// Identify interface members that don't have their required extension turned on.
2545//
2546bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2547{
2548 auto& extensions = glslangIntermediate->getRequestedExtensions();
2549
Rex Xubcf291a2017-03-29 23:01:36 +08002550 if (member.getFieldName() == "gl_ViewportMask" &&
2551 extensions.find("GL_NV_viewport_array2") == extensions.end())
2552 return true;
2553 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2554 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2555 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002556 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2557 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2558 return true;
2559 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2560 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2561 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002562 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2563 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2564 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002565
2566 return false;
2567};
2568
John Kessenich6090df02016-06-30 21:18:02 -06002569// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2570// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2571// Mutually recursive with convertGlslangToSpvType().
2572spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2573 const glslang::TTypeList* glslangMembers,
2574 glslang::TLayoutPacking explicitLayout,
2575 const glslang::TQualifier& qualifier)
2576{
2577 // Create a vector of struct types for SPIR-V to consume
2578 std::vector<spv::Id> spvMembers;
2579 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 -06002580 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2581 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2582 if (glslangMember.hiddenMember()) {
2583 ++memberDelta;
2584 if (type.getBasicType() == glslang::EbtBlock)
2585 memberRemapper[glslangMembers][i] = -1;
2586 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002587 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002588 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002589 if (filterMember(glslangMember))
2590 continue;
2591 }
John Kessenich6090df02016-06-30 21:18:02 -06002592 // modify just this child's view of the qualifier
2593 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2594 InheritQualifiers(memberQualifier, qualifier);
2595
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002596 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002597 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002598 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002599
2600 // recurse
2601 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2602 }
2603 }
2604
2605 // Make the SPIR-V type
2606 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002607 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002608 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2609
2610 // Decorate it
2611 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2612
2613 return spvType;
2614}
2615
2616void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2617 const glslang::TTypeList* glslangMembers,
2618 glslang::TLayoutPacking explicitLayout,
2619 const glslang::TQualifier& qualifier,
2620 spv::Id spvType)
2621{
2622 // Name and decorate the non-hidden members
2623 int offset = -1;
2624 int locationOffset = 0; // for use within the members of this struct
2625 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2626 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2627 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002628 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002629 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002630 if (filterMember(glslangMember))
2631 continue;
2632 }
John Kessenich6090df02016-06-30 21:18:02 -06002633
2634 // modify just this child's view of the qualifier
2635 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2636 InheritQualifiers(memberQualifier, qualifier);
2637
2638 // using -1 above to indicate a hidden member
2639 if (member >= 0) {
2640 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2641 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2642 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2643 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002644 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2645 type.getQualifier().storage == glslang::EvqVaryingOut) {
2646 if (type.getBasicType() == glslang::EbtBlock ||
2647 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002648 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2649 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2650 }
2651 }
2652 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2653
Rex Xu286ca432017-07-27 14:33:16 +08002654 if (type.getBasicType() == glslang::EbtBlock &&
2655 qualifier.storage == glslang::EvqBuffer) {
2656 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002657 std::vector<spv::Decoration> memory;
2658 TranslateMemoryDecoration(memberQualifier, memory);
2659 for (unsigned int i = 0; i < memory.size(); ++i)
2660 addMemberDecoration(spvType, member, memory[i]);
2661 }
2662
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002663 // Location assignment was already completed correctly by the front end,
2664 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002665 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002666 // ill-specified and decisions have been made to not allow this.
2667 if (! type.isArray() && memberQualifier.hasLocation())
2668 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002669
John Kessenich2f47bc92016-06-30 21:47:35 -06002670 if (qualifier.hasLocation()) // track for upcoming inheritance
2671 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2672
John Kessenich6090df02016-06-30 21:18:02 -06002673 // component, XFB, others
2674 if (glslangMember.getQualifier().hasComponent())
2675 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2676 if (glslangMember.getQualifier().hasXfbOffset())
2677 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2678 else if (explicitLayout != glslang::ElpNone) {
2679 // figure out what to do with offset, which is accumulating
2680 int nextOffset;
2681 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2682 if (offset >= 0)
2683 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2684 offset = nextOffset;
2685 }
2686
2687 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2688 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2689
2690 // built-in variable decorations
2691 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002692 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002693 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002694
2695#ifdef NV_EXTENSIONS
2696 if (builtIn == spv::BuiltInLayer) {
2697 // SPV_NV_viewport_array2 extension
2698 if (glslangMember.getQualifier().layoutViewportRelative){
2699 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2700 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2701 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2702 }
2703 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2704 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2705 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2706 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2707 }
2708 }
chaocdf3956c2017-02-14 14:52:34 -08002709 if (glslangMember.getQualifier().layoutPassthrough) {
2710 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2711 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2712 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2713 }
chaoc771d89f2017-01-13 01:10:53 -08002714#endif
John Kessenich6090df02016-06-30 21:18:02 -06002715 }
2716 }
2717
2718 // Decorate the structure
2719 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002720 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002721 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2722 builder.addCapability(spv::CapabilityGeometryStreams);
2723 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2724 }
John Kessenich6090df02016-06-30 21:18:02 -06002725}
2726
John Kessenich6c292d32016-02-15 20:58:50 -07002727// Turn the expression forming the array size into an id.
2728// This is not quite trivial, because of specialization constants.
2729// Sometimes, a raw constant is turned into an Id, and sometimes
2730// a specialization constant expression is.
2731spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2732{
2733 // First, see if this is sized with a node, meaning a specialization constant:
2734 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2735 if (specNode != nullptr) {
2736 builder.clearAccessChain();
2737 specNode->traverse(this);
2738 return accessChainLoad(specNode->getAsTyped()->getType());
2739 }
qining25262b32016-05-06 17:25:16 -04002740
John Kessenich6c292d32016-02-15 20:58:50 -07002741 // Otherwise, need a compile-time (front end) size, get it:
2742 int size = arraySizes.getDimSize(dim);
2743 assert(size > 0);
2744 return builder.makeUintConstant(size);
2745}
2746
John Kessenich103bef92016-02-08 21:38:15 -07002747// Wrap the builder's accessChainLoad to:
2748// - localize handling of RelaxedPrecision
2749// - use the SPIR-V inferred type instead of another conversion of the glslang type
2750// (avoids unnecessary work and possible type punning for structures)
2751// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002752spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2753{
John Kessenich103bef92016-02-08 21:38:15 -07002754 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2755 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2756
2757 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002758 if (type.getBasicType() == glslang::EbtBool) {
2759 if (builder.isScalarType(nominalTypeId)) {
2760 // Conversion for bool
2761 spv::Id boolType = builder.makeBoolType();
2762 if (nominalTypeId != boolType)
2763 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2764 } else if (builder.isVectorType(nominalTypeId)) {
2765 // Conversion for bvec
2766 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2767 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2768 if (nominalTypeId != bvecType)
2769 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2770 }
2771 }
John Kessenich103bef92016-02-08 21:38:15 -07002772
2773 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002774}
2775
Rex Xu27253232016-02-23 17:51:09 +08002776// Wrap the builder's accessChainStore to:
2777// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002778//
2779// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002780void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2781{
2782 // Need to convert to abstract types when necessary
2783 if (type.getBasicType() == glslang::EbtBool) {
2784 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2785
2786 if (builder.isScalarType(nominalTypeId)) {
2787 // Conversion for bool
2788 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002789 if (nominalTypeId != boolType) {
2790 // keep these outside arguments, for determinant order-of-evaluation
2791 spv::Id one = builder.makeUintConstant(1);
2792 spv::Id zero = builder.makeUintConstant(0);
2793 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2794 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002795 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002796 } else if (builder.isVectorType(nominalTypeId)) {
2797 // Conversion for bvec
2798 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2799 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002800 if (nominalTypeId != bvecType) {
2801 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002802 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2803 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2804 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002805 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002806 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2807 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002808 }
2809 }
2810
2811 builder.accessChainStore(rvalue);
2812}
2813
John Kessenich4bf71552016-09-02 11:20:21 -06002814// For storing when types match at the glslang level, but not might match at the
2815// SPIR-V level.
2816//
2817// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002818// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002819// as in a member-decorated way.
2820//
2821// NOTE: This function can handle any store request; if it's not special it
2822// simplifies to a simple OpStore.
2823//
2824// Implicitly uses the existing builder.accessChain as the storage target.
2825void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2826{
John Kessenichb3e24e42016-09-11 12:33:43 -06002827 // we only do the complex path here if it's an aggregate
2828 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002829 accessChainStore(type, rValue);
2830 return;
2831 }
2832
John Kessenichb3e24e42016-09-11 12:33:43 -06002833 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002834 spv::Id rType = builder.getTypeId(rValue);
2835 spv::Id lValue = builder.accessChainGetLValue();
2836 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2837 if (lType == rType) {
2838 accessChainStore(type, rValue);
2839 return;
2840 }
2841
John Kessenichb3e24e42016-09-11 12:33:43 -06002842 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002843 // where the two types were the same type in GLSL. This requires member
2844 // by member copy, recursively.
2845
John Kessenichb3e24e42016-09-11 12:33:43 -06002846 // If an array, copy element by element.
2847 if (type.isArray()) {
2848 glslang::TType glslangElementType(type, 0);
2849 spv::Id elementRType = builder.getContainedTypeId(rType);
2850 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2851 // get the source member
2852 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002853
John Kessenichb3e24e42016-09-11 12:33:43 -06002854 // set up the target storage
2855 builder.clearAccessChain();
2856 builder.setAccessChainLValue(lValue);
2857 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002858
John Kessenichb3e24e42016-09-11 12:33:43 -06002859 // store the member
2860 multiTypeStore(glslangElementType, elementRValue);
2861 }
2862 } else {
2863 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002864
John Kessenichb3e24e42016-09-11 12:33:43 -06002865 // loop over structure members
2866 const glslang::TTypeList& members = *type.getStruct();
2867 for (int m = 0; m < (int)members.size(); ++m) {
2868 const glslang::TType& glslangMemberType = *members[m].type;
2869
2870 // get the source member
2871 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2872 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2873
2874 // set up the target storage
2875 builder.clearAccessChain();
2876 builder.setAccessChainLValue(lValue);
2877 builder.accessChainPush(builder.makeIntConstant(m));
2878
2879 // store the member
2880 multiTypeStore(glslangMemberType, memberRValue);
2881 }
John Kessenich4bf71552016-09-02 11:20:21 -06002882 }
2883}
2884
John Kessenichf85e8062015-12-19 13:57:10 -07002885// Decide whether or not this type should be
2886// decorated with offsets and strides, and if so
2887// whether std140 or std430 rules should be applied.
2888glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002889{
John Kessenichf85e8062015-12-19 13:57:10 -07002890 // has to be a block
2891 if (type.getBasicType() != glslang::EbtBlock)
2892 return glslang::ElpNone;
2893
2894 // has to be a uniform or buffer block
2895 if (type.getQualifier().storage != glslang::EvqUniform &&
2896 type.getQualifier().storage != glslang::EvqBuffer)
2897 return glslang::ElpNone;
2898
2899 // return the layout to use
2900 switch (type.getQualifier().layoutPacking) {
2901 case glslang::ElpStd140:
2902 case glslang::ElpStd430:
2903 return type.getQualifier().layoutPacking;
2904 default:
2905 return glslang::ElpNone;
2906 }
John Kessenich31ed4832015-09-09 17:51:38 -06002907}
2908
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002909// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002910int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002911{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002912 int size;
John Kessenich49987892015-12-29 17:11:44 -07002913 int stride;
2914 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002915
2916 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002917}
2918
John Kessenich49987892015-12-29 17:11:44 -07002919// 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 -07002920// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002921int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002922{
John Kessenich49987892015-12-29 17:11:44 -07002923 glslang::TType elementType;
2924 elementType.shallowCopy(matrixType);
2925 elementType.clearArraySizes();
2926
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002927 int size;
John Kessenich49987892015-12-29 17:11:44 -07002928 int stride;
2929 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2930
2931 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002932}
2933
John Kessenich5e4b1242015-08-06 22:53:06 -06002934// Given a member type of a struct, realign the current offset for it, and compute
2935// the next (not yet aligned) offset for the next member, which will get aligned
2936// on the next call.
2937// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2938// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2939// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002940void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002941 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002942{
2943 // this will get a positive value when deemed necessary
2944 nextOffset = -1;
2945
John Kessenich5e4b1242015-08-06 22:53:06 -06002946 // override anything in currentOffset with user-set offset
2947 if (memberType.getQualifier().hasOffset())
2948 currentOffset = memberType.getQualifier().layoutOffset;
2949
2950 // It could be that current linker usage in glslang updated all the layoutOffset,
2951 // in which case the following code does not matter. But, that's not quite right
2952 // once cross-compilation unit GLSL validation is done, as the original user
2953 // settings are needed in layoutOffset, and then the following will come into play.
2954
John Kessenichf85e8062015-12-19 13:57:10 -07002955 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 if (! memberType.getQualifier().hasOffset())
2957 currentOffset = -1;
2958
2959 return;
2960 }
2961
John Kessenichf85e8062015-12-19 13:57:10 -07002962 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002963 if (currentOffset < 0)
2964 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002965
John Kessenich5e4b1242015-08-06 22:53:06 -06002966 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2967 // but possibly not yet correctly aligned.
2968
2969 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002970 int dummyStride;
2971 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002972
2973 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002974 // TODO: make this consistent in early phases of code:
2975 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2976 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2977 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002978 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002979 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002980 int dummySize;
2981 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2982 if (componentAlignment <= 4)
2983 memberAlignment = componentAlignment;
2984 }
2985
2986 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002988
2989 // Bump up to vec4 if there is a bad straddle
2990 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2991 glslang::RoundToPow2(currentOffset, 16);
2992
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 nextOffset = currentOffset + memberSize;
2994}
2995
David Netoa901ffe2016-06-08 14:11:40 +01002996void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002997{
David Netoa901ffe2016-06-08 14:11:40 +01002998 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2999 switch (glslangBuiltIn)
3000 {
3001 case glslang::EbvClipDistance:
3002 case glslang::EbvCullDistance:
3003 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003004#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003005 case glslang::EbvViewportMaskNV:
3006 case glslang::EbvSecondaryPositionNV:
3007 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003008 case glslang::EbvPositionPerViewNV:
3009 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003010#endif
David Netoa901ffe2016-06-08 14:11:40 +01003011 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3012 // Alternately, we could just call this for any glslang built-in, since the
3013 // capability already guards against duplicates.
3014 TranslateBuiltInDecoration(glslangBuiltIn, false);
3015 break;
3016 default:
3017 // Capabilities were already generated when the struct was declared.
3018 break;
3019 }
John Kessenichebb50532016-05-16 19:22:05 -06003020}
3021
John Kessenich6fccb3c2016-09-19 16:01:41 -06003022bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003023{
John Kessenicheee9d532016-09-19 18:09:30 -06003024 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003025}
3026
John Kessenichd41993d2017-09-10 15:21:05 -06003027// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003028// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3029// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003030bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3031{
John Kessenich6a14f782017-12-04 02:48:10 -07003032 assert(qualifier == glslang::EvqIn ||
3033 qualifier == glslang::EvqOut ||
3034 qualifier == glslang::EvqInOut ||
3035 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003036 return qualifier != glslang::EvqConstReadOnly;
3037}
3038
3039// Is parameter pass-by-original?
3040bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3041 bool implicitThisParam)
3042{
3043 if (implicitThisParam) // implicit this
3044 return true;
3045 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003046 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003047 return paramType.containsOpaque() || // sampler, etc.
3048 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3049}
3050
John Kessenich140f3df2015-06-26 16:58:36 -06003051// Make all the functions, skeletally, without actually visiting their bodies.
3052void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3053{
John Kessenichfad62972017-07-18 02:35:46 -06003054 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3055 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3056 if (paramPrecision != spv::NoPrecision)
3057 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003058 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003059 };
3060
John Kessenich140f3df2015-06-26 16:58:36 -06003061 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3062 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003063 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003064 continue;
3065
3066 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003067 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003068 //
qining25262b32016-05-06 17:25:16 -04003069 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003070 // function. What it is an address of varies:
3071 //
John Kessenich4bf71552016-09-02 11:20:21 -06003072 // - "in" parameters not marked as "const" can be written to without modifying the calling
3073 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003074 //
3075 // - "const in" parameters can just be the r-value, as no writes need occur.
3076 //
John Kessenich4bf71552016-09-02 11:20:21 -06003077 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3078 // 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 -06003079
3080 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003081 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003082 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3083
John Kessenichfad62972017-07-18 02:35:46 -06003084 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3085 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003086
John Kessenichfad62972017-07-18 02:35:46 -06003087 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003088 for (int p = 0; p < (int)parameters.size(); ++p) {
3089 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3090 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003091 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003092 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003093 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003094 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3095 else
John Kessenich4bf71552016-09-02 11:20:21 -06003096 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003097 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003098 paramTypes.push_back(typeId);
3099 }
3100
3101 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003102 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3103 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003104 glslFunction->getName().c_str(), paramTypes,
3105 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003106 if (implicitThis)
3107 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003108
3109 // Track function to emit/call later
3110 functionMap[glslFunction->getName().c_str()] = function;
3111
3112 // Set the parameter id's
3113 for (int p = 0; p < (int)parameters.size(); ++p) {
3114 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3115 // give a name too
3116 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3117 }
3118 }
3119}
3120
3121// Process all the initializers, while skipping the functions and link objects
3122void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3123{
3124 builder.setBuildPoint(shaderEntry->getLastBlock());
3125 for (int i = 0; i < (int)initializers.size(); ++i) {
3126 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3127 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3128
3129 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003130 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003131 initializer->traverse(this);
3132 }
3133 }
3134}
3135
3136// Process all the functions, while skipping initializers.
3137void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3138{
3139 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3140 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003141 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003142 node->traverse(this);
3143 }
3144}
3145
3146void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3147{
qining25262b32016-05-06 17:25:16 -04003148 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003149 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003150 currentFunction = functionMap[node->getName().c_str()];
3151 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003152 builder.setBuildPoint(functionBlock);
3153}
3154
Rex Xu04db3f52015-09-16 11:44:02 +08003155void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003156{
Rex Xufc618912015-09-09 16:42:49 +08003157 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003158
3159 glslang::TSampler sampler = {};
3160 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003161 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003162 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3163 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3164 }
3165
John Kessenich140f3df2015-06-26 16:58:36 -06003166 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3167 builder.clearAccessChain();
3168 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003169
3170 // Special case l-value operands
3171 bool lvalue = false;
3172 switch (node.getOp()) {
3173 case glslang::EOpImageAtomicAdd:
3174 case glslang::EOpImageAtomicMin:
3175 case glslang::EOpImageAtomicMax:
3176 case glslang::EOpImageAtomicAnd:
3177 case glslang::EOpImageAtomicOr:
3178 case glslang::EOpImageAtomicXor:
3179 case glslang::EOpImageAtomicExchange:
3180 case glslang::EOpImageAtomicCompSwap:
3181 if (i == 0)
3182 lvalue = true;
3183 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003184 case glslang::EOpSparseImageLoad:
3185 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3186 lvalue = true;
3187 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003188 case glslang::EOpSparseTexture:
3189 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3190 lvalue = true;
3191 break;
3192 case glslang::EOpSparseTextureClamp:
3193 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3194 lvalue = true;
3195 break;
3196 case glslang::EOpSparseTextureLod:
3197 case glslang::EOpSparseTextureOffset:
3198 if (i == 3)
3199 lvalue = true;
3200 break;
3201 case glslang::EOpSparseTextureFetch:
3202 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3203 lvalue = true;
3204 break;
3205 case glslang::EOpSparseTextureFetchOffset:
3206 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3207 lvalue = true;
3208 break;
3209 case glslang::EOpSparseTextureLodOffset:
3210 case glslang::EOpSparseTextureGrad:
3211 case glslang::EOpSparseTextureOffsetClamp:
3212 if (i == 4)
3213 lvalue = true;
3214 break;
3215 case glslang::EOpSparseTextureGradOffset:
3216 case glslang::EOpSparseTextureGradClamp:
3217 if (i == 5)
3218 lvalue = true;
3219 break;
3220 case glslang::EOpSparseTextureGradOffsetClamp:
3221 if (i == 6)
3222 lvalue = true;
3223 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003224 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003225 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3226 lvalue = true;
3227 break;
3228 case glslang::EOpSparseTextureGatherOffset:
3229 case glslang::EOpSparseTextureGatherOffsets:
3230 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3231 lvalue = true;
3232 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003233#ifdef AMD_EXTENSIONS
3234 case glslang::EOpSparseTextureGatherLod:
3235 if (i == 3)
3236 lvalue = true;
3237 break;
3238 case glslang::EOpSparseTextureGatherLodOffset:
3239 case glslang::EOpSparseTextureGatherLodOffsets:
3240 if (i == 4)
3241 lvalue = true;
3242 break;
Rex Xu129799a2017-07-05 17:23:28 +08003243 case glslang::EOpSparseImageLoadLod:
3244 if (i == 3)
3245 lvalue = true;
3246 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003247#endif
Rex Xufc618912015-09-09 16:42:49 +08003248 default:
3249 break;
3250 }
3251
Rex Xu6b86d492015-09-16 17:48:22 +08003252 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003253 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003254 else
John Kessenich32cfd492016-02-02 12:37:46 -07003255 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003256 }
3257}
3258
John Kessenichfc51d282015-08-19 13:34:18 -06003259void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003260{
John Kessenichfc51d282015-08-19 13:34:18 -06003261 builder.clearAccessChain();
3262 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003263 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003264}
John Kessenich140f3df2015-06-26 16:58:36 -06003265
John Kessenichfc51d282015-08-19 13:34:18 -06003266spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3267{
John Kesseniche485c7a2017-05-31 18:50:53 -06003268 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003269 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003270
3271 builder.setLine(node->getLoc().line);
3272
John Kessenichfc51d282015-08-19 13:34:18 -06003273 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003274 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3275 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3276 std::vector<spv::Id> arguments;
3277 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003278 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003279 else
3280 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003281 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003282
3283 spv::Builder::TextureParameters params = { };
3284 params.sampler = arguments[0];
3285
Rex Xu04db3f52015-09-16 11:44:02 +08003286 glslang::TCrackedTextureOp cracked;
3287 node->crackTexture(sampler, cracked);
3288
amhagan05506bb2017-06-13 16:53:02 -04003289 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003290
John Kessenichfc51d282015-08-19 13:34:18 -06003291 // Check for queries
3292 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003293 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3294 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003295 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003296
John Kessenichfc51d282015-08-19 13:34:18 -06003297 switch (node->getOp()) {
3298 case glslang::EOpImageQuerySize:
3299 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003300 if (arguments.size() > 1) {
3301 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003302 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003303 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003304 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003305 case glslang::EOpImageQuerySamples:
3306 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003307 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003308 case glslang::EOpTextureQueryLod:
3309 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003310 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003311 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003312 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003313 case glslang::EOpSparseTexelsResident:
3314 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003315 default:
3316 assert(0);
3317 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 }
John Kessenich140f3df2015-06-26 16:58:36 -06003319 }
3320
LoopDawg4425f242018-02-18 11:40:01 -07003321 int components = node->getType().getVectorSize();
3322
3323 if (node->getOp() == glslang::EOpTextureFetch) {
3324 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3325 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3326 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3327 // here around e.g. which ones return scalars or other types.
3328 components = 4;
3329 }
3330
3331 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3332
3333 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3334
Rex Xufc618912015-09-09 16:42:49 +08003335 // Check for image functions other than queries
3336 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003337 std::vector<spv::Id> operands;
3338 auto opIt = arguments.begin();
3339 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003340
3341 // Handle subpass operations
3342 // TODO: GLSL should change to have the "MS" only on the type rather than the
3343 // built-in function.
3344 if (cracked.subpass) {
3345 // add on the (0,0) coordinate
3346 spv::Id zero = builder.makeIntConstant(0);
3347 std::vector<spv::Id> comps;
3348 comps.push_back(zero);
3349 comps.push_back(zero);
3350 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3351 if (sampler.ms) {
3352 operands.push_back(spv::ImageOperandsSampleMask);
3353 operands.push_back(*(opIt++));
3354 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003355 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3356 builder.setPrecision(result, precision);
3357 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003358 }
3359
John Kessenich56bab042015-09-16 10:54:31 -06003360 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003361#ifdef AMD_EXTENSIONS
3362 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3363#else
John Kessenich56bab042015-09-16 10:54:31 -06003364 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003365#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003366 if (sampler.ms) {
3367 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003368 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003369#ifdef AMD_EXTENSIONS
3370 } else if (cracked.lod) {
3371 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3372 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3373
3374 operands.push_back(spv::ImageOperandsLodMask);
3375 operands.push_back(*opIt);
3376#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003377 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003378 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3379 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003380
LoopDawg4425f242018-02-18 11:40:01 -07003381 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3382 builder.setPrecision(result[0], precision);
3383
3384 // If needed, add a conversion constructor to the proper size.
3385 if (components != node->getType().getVectorSize())
3386 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3387
3388 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003389#ifdef AMD_EXTENSIONS
3390 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3391#else
John Kessenich56bab042015-09-16 10:54:31 -06003392 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003393#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003394 if (sampler.ms) {
3395 operands.push_back(*(opIt + 1));
3396 operands.push_back(spv::ImageOperandsSampleMask);
3397 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003398#ifdef AMD_EXTENSIONS
3399 } else if (cracked.lod) {
3400 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3401 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3402
3403 operands.push_back(*(opIt + 1));
3404 operands.push_back(spv::ImageOperandsLodMask);
3405 operands.push_back(*opIt);
3406#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003407 } else
3408 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003409 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003410 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3411 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003412 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003413#ifdef AMD_EXTENSIONS
3414 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3415#else
Rex Xu5eafa472016-02-19 22:24:03 +08003416 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003417#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003418 builder.addCapability(spv::CapabilitySparseResidency);
3419 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3420 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3421
3422 if (sampler.ms) {
3423 operands.push_back(spv::ImageOperandsSampleMask);
3424 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003425#ifdef AMD_EXTENSIONS
3426 } else if (cracked.lod) {
3427 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3428 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3429
3430 operands.push_back(spv::ImageOperandsLodMask);
3431 operands.push_back(*opIt++);
3432#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003433 }
3434
3435 // Create the return type that was a special structure
3436 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003437 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003438 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3439 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3440
3441 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3442
3443 // Decode the return type
3444 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3445 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003446 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003447 // Process image atomic operations
3448
3449 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3450 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003451 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003452
John Kessenich8c8505c2016-07-26 12:50:38 -06003453 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003454 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003455
3456 std::vector<spv::Id> operands;
3457 operands.push_back(pointer);
3458 for (; opIt != arguments.end(); ++opIt)
3459 operands.push_back(*opIt);
3460
John Kessenich8c8505c2016-07-26 12:50:38 -06003461 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003462 }
3463 }
3464
amhagan05506bb2017-06-13 16:53:02 -04003465#ifdef AMD_EXTENSIONS
3466 // Check for fragment mask functions other than queries
3467 if (cracked.fragMask) {
3468 assert(sampler.ms);
3469
3470 auto opIt = arguments.begin();
3471 std::vector<spv::Id> operands;
3472
3473 // Extract the image if necessary
3474 if (builder.isSampledImage(params.sampler))
3475 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3476
3477 operands.push_back(params.sampler);
3478 ++opIt;
3479
3480 if (sampler.isSubpass()) {
3481 // add on the (0,0) coordinate
3482 spv::Id zero = builder.makeIntConstant(0);
3483 std::vector<spv::Id> comps;
3484 comps.push_back(zero);
3485 comps.push_back(zero);
3486 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3487 }
3488
3489 for (; opIt != arguments.end(); ++opIt)
3490 operands.push_back(*opIt);
3491
3492 spv::Op fragMaskOp = spv::OpNop;
3493 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3494 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3495 else if (node->getOp() == glslang::EOpFragmentFetch)
3496 fragMaskOp = spv::OpFragmentFetchAMD;
3497
3498 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3499 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3500 return builder.createOp(fragMaskOp, resultType(), operands);
3501 }
3502#endif
3503
Rex Xufc618912015-09-09 16:42:49 +08003504 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003505 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003506 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3507
John Kessenichfc51d282015-08-19 13:34:18 -06003508 // check for bias argument
3509 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003510#ifdef AMD_EXTENSIONS
3511 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3512#else
Rex Xu71519fe2015-11-11 15:35:47 +08003513 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003514#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003515 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003516#ifdef AMD_EXTENSIONS
3517 if (cracked.gather)
3518 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3519#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003520 if (cracked.offset)
3521 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003522#ifdef AMD_EXTENSIONS
3523 else if (cracked.offsets)
3524 ++nonBiasArgCount;
3525#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003526 if (cracked.grad)
3527 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003528 if (cracked.lodClamp)
3529 ++nonBiasArgCount;
3530 if (sparse)
3531 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003532
3533 if ((int)arguments.size() > nonBiasArgCount)
3534 bias = true;
3535 }
3536
John Kessenicha5c33d62016-06-02 23:45:21 -06003537 // See if the sampler param should really be just the SPV image part
3538 if (cracked.fetch) {
3539 // a fetch needs to have the image extracted first
3540 if (builder.isSampledImage(params.sampler))
3541 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3542 }
3543
Rex Xu225e0fc2016-11-17 17:47:59 +08003544#ifdef AMD_EXTENSIONS
3545 if (cracked.gather) {
3546 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3547 if (bias || cracked.lod ||
3548 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3549 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003550 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003551 }
3552 }
3553#endif
3554
John Kessenichfc51d282015-08-19 13:34:18 -06003555 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003556
John Kessenichfc51d282015-08-19 13:34:18 -06003557 params.coords = arguments[1];
3558 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003559 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003560
3561 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003562 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003563 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003564 ++extraArgs;
3565 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003566 params.Dref = arguments[2];
3567 ++extraArgs;
3568 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003569 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003570 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003571 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003572 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003573 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003574 dRefComp = builder.getNumComponents(params.coords) - 1;
3575 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003576 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3577 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003578
3579 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003580 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003581 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003582 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003583 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3584 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3585 noImplicitLod = true;
3586 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003587
3588 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003589 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003590 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003591 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003592 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003593
3594 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003595 if (cracked.grad) {
3596 params.gradX = arguments[2 + extraArgs];
3597 params.gradY = arguments[3 + extraArgs];
3598 extraArgs += 2;
3599 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003600
3601 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003602 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003603 params.offset = arguments[2 + extraArgs];
3604 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003605 } else if (cracked.offsets) {
3606 params.offsets = arguments[2 + extraArgs];
3607 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003608 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003609
3610 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003611 if (cracked.lodClamp) {
3612 params.lodClamp = arguments[2 + extraArgs];
3613 ++extraArgs;
3614 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003615
3616 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003617 if (sparse) {
3618 params.texelOut = arguments[2 + extraArgs];
3619 ++extraArgs;
3620 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003621
John Kessenich76d4dfc2016-06-16 12:43:23 -06003622 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003623 if (cracked.gather && ! sampler.shadow) {
3624 // default component is 0, if missing, otherwise an argument
3625 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003626 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003627 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003628 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003629 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003630 }
3631
3632 // bias
3633 if (bias) {
3634 params.bias = arguments[2 + extraArgs];
3635 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003636 }
John Kessenichfc51d282015-08-19 13:34:18 -06003637
John Kessenich65336482016-06-16 14:06:26 -06003638 // projective component (might not to move)
3639 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3640 // are divided by the last component of P."
3641 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3642 // unused components will appear after all used components."
3643 if (cracked.proj) {
3644 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3645 int projTargetComp;
3646 switch (sampler.dim) {
3647 case glslang::Esd1D: projTargetComp = 1; break;
3648 case glslang::Esd2D: projTargetComp = 2; break;
3649 case glslang::EsdRect: projTargetComp = 2; break;
3650 default: projTargetComp = projSourceComp; break;
3651 }
3652 // copy the projective coordinate if we have to
3653 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003654 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003655 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3656 projSourceComp);
3657 params.coords = builder.createCompositeInsert(projComp, params.coords,
3658 builder.getTypeId(params.coords), projTargetComp);
3659 }
3660 }
3661
LoopDawg4425f242018-02-18 11:40:01 -07003662 std::vector<spv::Id> result = {
3663 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3664 };
3665
3666 if (components != node->getType().getVectorSize())
3667 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3668
3669 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003670}
3671
3672spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3673{
3674 // Grab the function's pointer from the previously created function
3675 spv::Function* function = functionMap[node->getName().c_str()];
3676 if (! function)
3677 return 0;
3678
3679 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3680 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3681
3682 // See comments in makeFunctions() for details about the semantics for parameter passing.
3683 //
3684 // These imply we need a four step process:
3685 // 1. Evaluate the arguments
3686 // 2. Allocate and make copies of in, out, and inout arguments
3687 // 3. Make the call
3688 // 4. Copy back the results
3689
3690 // 1. Evaluate the arguments
3691 std::vector<spv::Builder::AccessChain> lValues;
3692 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003693 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003695 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003696 // build l-value
3697 builder.clearAccessChain();
3698 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003699 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003700 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003701 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3702 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003703 // save l-value
3704 lValues.push_back(builder.getAccessChain());
3705 } else {
3706 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003707 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003708 }
3709 }
3710
3711 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3712 // copy the original into that space.
3713 //
3714 // Also, build up the list of actual arguments to pass in for the call
3715 int lValueCount = 0;
3716 int rValueCount = 0;
3717 std::vector<spv::Id> spvArgs;
3718 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003719 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003720 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003721 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003722 builder.setAccessChain(lValues[lValueCount]);
3723 arg = builder.accessChainGetLValue();
3724 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003725 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003726 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003727 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3728 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3729 // need to copy the input into output space
3730 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003731 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003732 builder.clearAccessChain();
3733 builder.setAccessChainLValue(arg);
3734 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003735 }
3736 ++lValueCount;
3737 } else {
3738 arg = rValues[rValueCount];
3739 ++rValueCount;
3740 }
3741 spvArgs.push_back(arg);
3742 }
3743
3744 // 3. Make the call.
3745 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003746 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003747
3748 // 4. Copy back out an "out" arguments.
3749 lValueCount = 0;
3750 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003751 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003752 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3753 ++lValueCount;
3754 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003755 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3756 spv::Id copy = builder.createLoad(spvArgs[a]);
3757 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003758 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003759 }
3760 ++lValueCount;
3761 }
3762 }
3763
3764 return result;
3765}
3766
3767// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003768spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3769 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003770 spv::Id typeId, spv::Id left, spv::Id right,
3771 glslang::TBasicType typeProxy, bool reduceComparison)
3772{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003773#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003774 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003775 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3776#else
Rex Xucabbb782017-03-24 13:41:14 +08003777 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003779#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003780 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003781
3782 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003783 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003784 bool comparison = false;
3785
3786 switch (op) {
3787 case glslang::EOpAdd:
3788 case glslang::EOpAddAssign:
3789 if (isFloat)
3790 binOp = spv::OpFAdd;
3791 else
3792 binOp = spv::OpIAdd;
3793 break;
3794 case glslang::EOpSub:
3795 case glslang::EOpSubAssign:
3796 if (isFloat)
3797 binOp = spv::OpFSub;
3798 else
3799 binOp = spv::OpISub;
3800 break;
3801 case glslang::EOpMul:
3802 case glslang::EOpMulAssign:
3803 if (isFloat)
3804 binOp = spv::OpFMul;
3805 else
3806 binOp = spv::OpIMul;
3807 break;
3808 case glslang::EOpVectorTimesScalar:
3809 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003810 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003811 if (builder.isVector(right))
3812 std::swap(left, right);
3813 assert(builder.isScalar(right));
3814 needMatchingVectors = false;
3815 binOp = spv::OpVectorTimesScalar;
3816 } else
3817 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003818 break;
3819 case glslang::EOpVectorTimesMatrix:
3820 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003821 binOp = spv::OpVectorTimesMatrix;
3822 break;
3823 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003824 binOp = spv::OpMatrixTimesVector;
3825 break;
3826 case glslang::EOpMatrixTimesScalar:
3827 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003828 binOp = spv::OpMatrixTimesScalar;
3829 break;
3830 case glslang::EOpMatrixTimesMatrix:
3831 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003832 binOp = spv::OpMatrixTimesMatrix;
3833 break;
3834 case glslang::EOpOuterProduct:
3835 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003836 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003837 break;
3838
3839 case glslang::EOpDiv:
3840 case glslang::EOpDivAssign:
3841 if (isFloat)
3842 binOp = spv::OpFDiv;
3843 else if (isUnsigned)
3844 binOp = spv::OpUDiv;
3845 else
3846 binOp = spv::OpSDiv;
3847 break;
3848 case glslang::EOpMod:
3849 case glslang::EOpModAssign:
3850 if (isFloat)
3851 binOp = spv::OpFMod;
3852 else if (isUnsigned)
3853 binOp = spv::OpUMod;
3854 else
3855 binOp = spv::OpSMod;
3856 break;
3857 case glslang::EOpRightShift:
3858 case glslang::EOpRightShiftAssign:
3859 if (isUnsigned)
3860 binOp = spv::OpShiftRightLogical;
3861 else
3862 binOp = spv::OpShiftRightArithmetic;
3863 break;
3864 case glslang::EOpLeftShift:
3865 case glslang::EOpLeftShiftAssign:
3866 binOp = spv::OpShiftLeftLogical;
3867 break;
3868 case glslang::EOpAnd:
3869 case glslang::EOpAndAssign:
3870 binOp = spv::OpBitwiseAnd;
3871 break;
3872 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003873 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003874 binOp = spv::OpLogicalAnd;
3875 break;
3876 case glslang::EOpInclusiveOr:
3877 case glslang::EOpInclusiveOrAssign:
3878 binOp = spv::OpBitwiseOr;
3879 break;
3880 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003881 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 binOp = spv::OpLogicalOr;
3883 break;
3884 case glslang::EOpExclusiveOr:
3885 case glslang::EOpExclusiveOrAssign:
3886 binOp = spv::OpBitwiseXor;
3887 break;
3888 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003889 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 break;
3892
3893 case glslang::EOpLessThan:
3894 case glslang::EOpGreaterThan:
3895 case glslang::EOpLessThanEqual:
3896 case glslang::EOpGreaterThanEqual:
3897 case glslang::EOpEqual:
3898 case glslang::EOpNotEqual:
3899 case glslang::EOpVectorEqual:
3900 case glslang::EOpVectorNotEqual:
3901 comparison = true;
3902 break;
3903 default:
3904 break;
3905 }
3906
John Kessenich7c1aa102015-10-15 13:29:11 -06003907 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003908 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003909 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003910 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003911 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003912
3913 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003914 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003915 builder.promoteScalar(precision, left, right);
3916
qining25262b32016-05-06 17:25:16 -04003917 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3918 addDecoration(result, noContraction);
3919 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003920 }
3921
3922 if (! comparison)
3923 return 0;
3924
John Kessenich7c1aa102015-10-15 13:29:11 -06003925 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003926
John Kessenich4583b612016-08-07 19:14:22 -06003927 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3928 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003929 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003930
3931 switch (op) {
3932 case glslang::EOpLessThan:
3933 if (isFloat)
3934 binOp = spv::OpFOrdLessThan;
3935 else if (isUnsigned)
3936 binOp = spv::OpULessThan;
3937 else
3938 binOp = spv::OpSLessThan;
3939 break;
3940 case glslang::EOpGreaterThan:
3941 if (isFloat)
3942 binOp = spv::OpFOrdGreaterThan;
3943 else if (isUnsigned)
3944 binOp = spv::OpUGreaterThan;
3945 else
3946 binOp = spv::OpSGreaterThan;
3947 break;
3948 case glslang::EOpLessThanEqual:
3949 if (isFloat)
3950 binOp = spv::OpFOrdLessThanEqual;
3951 else if (isUnsigned)
3952 binOp = spv::OpULessThanEqual;
3953 else
3954 binOp = spv::OpSLessThanEqual;
3955 break;
3956 case glslang::EOpGreaterThanEqual:
3957 if (isFloat)
3958 binOp = spv::OpFOrdGreaterThanEqual;
3959 else if (isUnsigned)
3960 binOp = spv::OpUGreaterThanEqual;
3961 else
3962 binOp = spv::OpSGreaterThanEqual;
3963 break;
3964 case glslang::EOpEqual:
3965 case glslang::EOpVectorEqual:
3966 if (isFloat)
3967 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003968 else if (isBool)
3969 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003970 else
3971 binOp = spv::OpIEqual;
3972 break;
3973 case glslang::EOpNotEqual:
3974 case glslang::EOpVectorNotEqual:
3975 if (isFloat)
3976 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003977 else if (isBool)
3978 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003979 else
3980 binOp = spv::OpINotEqual;
3981 break;
3982 default:
3983 break;
3984 }
3985
qining25262b32016-05-06 17:25:16 -04003986 if (binOp != spv::OpNop) {
3987 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3988 addDecoration(result, noContraction);
3989 return builder.setPrecision(result, precision);
3990 }
John Kessenich140f3df2015-06-26 16:58:36 -06003991
3992 return 0;
3993}
3994
John Kessenich04bb8a02015-12-12 12:28:14 -07003995//
3996// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3997// These can be any of:
3998//
3999// matrix * scalar
4000// scalar * matrix
4001// matrix * matrix linear algebraic
4002// matrix * vector
4003// vector * matrix
4004// matrix * matrix componentwise
4005// matrix op matrix op in {+, -, /}
4006// matrix op scalar op in {+, -, /}
4007// scalar op matrix op in {+, -, /}
4008//
qining25262b32016-05-06 17:25:16 -04004009spv::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 -07004010{
4011 bool firstClass = true;
4012
4013 // First, handle first-class matrix operations (* and matrix/scalar)
4014 switch (op) {
4015 case spv::OpFDiv:
4016 if (builder.isMatrix(left) && builder.isScalar(right)) {
4017 // turn matrix / scalar into a multiply...
4018 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
4019 op = spv::OpMatrixTimesScalar;
4020 } else
4021 firstClass = false;
4022 break;
4023 case spv::OpMatrixTimesScalar:
4024 if (builder.isMatrix(right))
4025 std::swap(left, right);
4026 assert(builder.isScalar(right));
4027 break;
4028 case spv::OpVectorTimesMatrix:
4029 assert(builder.isVector(left));
4030 assert(builder.isMatrix(right));
4031 break;
4032 case spv::OpMatrixTimesVector:
4033 assert(builder.isMatrix(left));
4034 assert(builder.isVector(right));
4035 break;
4036 case spv::OpMatrixTimesMatrix:
4037 assert(builder.isMatrix(left));
4038 assert(builder.isMatrix(right));
4039 break;
4040 default:
4041 firstClass = false;
4042 break;
4043 }
4044
qining25262b32016-05-06 17:25:16 -04004045 if (firstClass) {
4046 spv::Id result = builder.createBinOp(op, typeId, left, right);
4047 addDecoration(result, noContraction);
4048 return builder.setPrecision(result, precision);
4049 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004050
LoopDawg592860c2016-06-09 08:57:35 -06004051 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004052 // The result type of all of them is the same type as the (a) matrix operand.
4053 // The algorithm is to:
4054 // - break the matrix(es) into vectors
4055 // - smear any scalar to a vector
4056 // - do vector operations
4057 // - make a matrix out the vector results
4058 switch (op) {
4059 case spv::OpFAdd:
4060 case spv::OpFSub:
4061 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004062 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004063 case spv::OpFMul:
4064 {
4065 // one time set up...
4066 bool leftMat = builder.isMatrix(left);
4067 bool rightMat = builder.isMatrix(right);
4068 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4069 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4070 spv::Id scalarType = builder.getScalarTypeId(typeId);
4071 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4072 std::vector<spv::Id> results;
4073 spv::Id smearVec = spv::NoResult;
4074 if (builder.isScalar(left))
4075 smearVec = builder.smearScalar(precision, left, vecType);
4076 else if (builder.isScalar(right))
4077 smearVec = builder.smearScalar(precision, right, vecType);
4078
4079 // do each vector op
4080 for (unsigned int c = 0; c < numCols; ++c) {
4081 std::vector<unsigned int> indexes;
4082 indexes.push_back(c);
4083 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4084 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004085 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4086 addDecoration(result, noContraction);
4087 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004088 }
4089
4090 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004091 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004092 }
4093 default:
4094 assert(0);
4095 return spv::NoResult;
4096 }
4097}
4098
qining25262b32016-05-06 17:25:16 -04004099spv::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 -06004100{
4101 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004102 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004104#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004105 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004106 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4107#else
Rex Xucabbb782017-03-24 13:41:14 +08004108 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004109 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004110#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004111
4112 switch (op) {
4113 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004114 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004115 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004116 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004117 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004118 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004119 unaryOp = spv::OpSNegate;
4120 break;
4121
4122 case glslang::EOpLogicalNot:
4123 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004124 unaryOp = spv::OpLogicalNot;
4125 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004126 case glslang::EOpBitwiseNot:
4127 unaryOp = spv::OpNot;
4128 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004129
John Kessenich140f3df2015-06-26 16:58:36 -06004130 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004131 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004132 break;
4133 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004134 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004135 break;
4136 case glslang::EOpTranspose:
4137 unaryOp = spv::OpTranspose;
4138 break;
4139
4140 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004141 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004142 break;
4143 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004144 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004145 break;
4146 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004147 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004148 break;
4149 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004150 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004151 break;
4152 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004153 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004154 break;
4155 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004156 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004157 break;
4158 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004159 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004160 break;
4161 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004162 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004163 break;
4164
4165 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004166 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004167 break;
4168 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004169 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004170 break;
4171 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004172 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004173 break;
4174 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004175 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
4177 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004178 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 break;
4180 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004181 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183
4184 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004185 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
4187 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004188 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004189 break;
4190
4191 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004192 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004193 break;
4194 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004195 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004196 break;
4197 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004198 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004199 break;
4200 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004201 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004202 break;
4203 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004204 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004205 break;
4206 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004207 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004208 break;
4209
4210 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004211 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004212 break;
4213 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004214 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004215 break;
4216 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004217 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004218 break;
4219 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004220 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004221 break;
4222 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004223 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004224 break;
4225 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004226 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004227 break;
4228
4229 case glslang::EOpIsNan:
4230 unaryOp = spv::OpIsNan;
4231 break;
4232 case glslang::EOpIsInf:
4233 unaryOp = spv::OpIsInf;
4234 break;
LoopDawg592860c2016-06-09 08:57:35 -06004235 case glslang::EOpIsFinite:
4236 unaryOp = spv::OpIsFinite;
4237 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004238
Rex Xucbc426e2015-12-15 16:03:10 +08004239 case glslang::EOpFloatBitsToInt:
4240 case glslang::EOpFloatBitsToUint:
4241 case glslang::EOpIntBitsToFloat:
4242 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004243 case glslang::EOpDoubleBitsToInt64:
4244 case glslang::EOpDoubleBitsToUint64:
4245 case glslang::EOpInt64BitsToDouble:
4246 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004247#ifdef AMD_EXTENSIONS
4248 case glslang::EOpFloat16BitsToInt16:
4249 case glslang::EOpFloat16BitsToUint16:
4250 case glslang::EOpInt16BitsToFloat16:
4251 case glslang::EOpUint16BitsToFloat16:
4252#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004253 unaryOp = spv::OpBitcast;
4254 break;
4255
John Kessenich140f3df2015-06-26 16:58:36 -06004256 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004257 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004258 break;
4259 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004260 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004261 break;
4262 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004263 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004264 break;
4265 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004266 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004267 break;
4268 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004269 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004270 break;
4271 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004272 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004273 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004274 case glslang::EOpPackSnorm4x8:
4275 libCall = spv::GLSLstd450PackSnorm4x8;
4276 break;
4277 case glslang::EOpUnpackSnorm4x8:
4278 libCall = spv::GLSLstd450UnpackSnorm4x8;
4279 break;
4280 case glslang::EOpPackUnorm4x8:
4281 libCall = spv::GLSLstd450PackUnorm4x8;
4282 break;
4283 case glslang::EOpUnpackUnorm4x8:
4284 libCall = spv::GLSLstd450UnpackUnorm4x8;
4285 break;
4286 case glslang::EOpPackDouble2x32:
4287 libCall = spv::GLSLstd450PackDouble2x32;
4288 break;
4289 case glslang::EOpUnpackDouble2x32:
4290 libCall = spv::GLSLstd450UnpackDouble2x32;
4291 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004292
Rex Xu8ff43de2016-04-22 16:51:45 +08004293 case glslang::EOpPackInt2x32:
4294 case glslang::EOpUnpackInt2x32:
4295 case glslang::EOpPackUint2x32:
4296 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004297 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004298 break;
4299
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004300#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004301 case glslang::EOpPackInt2x16:
4302 case glslang::EOpUnpackInt2x16:
4303 case glslang::EOpPackUint2x16:
4304 case glslang::EOpUnpackUint2x16:
4305 case glslang::EOpPackInt4x16:
4306 case glslang::EOpUnpackInt4x16:
4307 case glslang::EOpPackUint4x16:
4308 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004309 case glslang::EOpPackFloat2x16:
4310 case glslang::EOpUnpackFloat2x16:
4311 unaryOp = spv::OpBitcast;
4312 break;
4313#endif
4314
John Kessenich140f3df2015-06-26 16:58:36 -06004315 case glslang::EOpDPdx:
4316 unaryOp = spv::OpDPdx;
4317 break;
4318 case glslang::EOpDPdy:
4319 unaryOp = spv::OpDPdy;
4320 break;
4321 case glslang::EOpFwidth:
4322 unaryOp = spv::OpFwidth;
4323 break;
4324 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004325 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004326 unaryOp = spv::OpDPdxFine;
4327 break;
4328 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004329 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004330 unaryOp = spv::OpDPdyFine;
4331 break;
4332 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004333 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004334 unaryOp = spv::OpFwidthFine;
4335 break;
4336 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004337 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004338 unaryOp = spv::OpDPdxCoarse;
4339 break;
4340 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004341 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004342 unaryOp = spv::OpDPdyCoarse;
4343 break;
4344 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004345 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004346 unaryOp = spv::OpFwidthCoarse;
4347 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004348 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004349 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004350 libCall = spv::GLSLstd450InterpolateAtCentroid;
4351 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004352 case glslang::EOpAny:
4353 unaryOp = spv::OpAny;
4354 break;
4355 case glslang::EOpAll:
4356 unaryOp = spv::OpAll;
4357 break;
4358
4359 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004360 if (isFloat)
4361 libCall = spv::GLSLstd450FAbs;
4362 else
4363 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004364 break;
4365 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 if (isFloat)
4367 libCall = spv::GLSLstd450FSign;
4368 else
4369 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004370 break;
4371
John Kessenichfc51d282015-08-19 13:34:18 -06004372 case glslang::EOpAtomicCounterIncrement:
4373 case glslang::EOpAtomicCounterDecrement:
4374 case glslang::EOpAtomicCounter:
4375 {
4376 // Handle all of the atomics in one place, in createAtomicOperation()
4377 std::vector<spv::Id> operands;
4378 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004379 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004380 }
4381
John Kessenichfc51d282015-08-19 13:34:18 -06004382 case glslang::EOpBitFieldReverse:
4383 unaryOp = spv::OpBitReverse;
4384 break;
4385 case glslang::EOpBitCount:
4386 unaryOp = spv::OpBitCount;
4387 break;
4388 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004389 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004390 break;
4391 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004392 if (isUnsigned)
4393 libCall = spv::GLSLstd450FindUMsb;
4394 else
4395 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004396 break;
4397
Rex Xu574ab042016-04-14 16:53:07 +08004398 case glslang::EOpBallot:
4399 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004400 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004401 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004402 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004403#ifdef AMD_EXTENSIONS
4404 case glslang::EOpMinInvocations:
4405 case glslang::EOpMaxInvocations:
4406 case glslang::EOpAddInvocations:
4407 case glslang::EOpMinInvocationsNonUniform:
4408 case glslang::EOpMaxInvocationsNonUniform:
4409 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004410 case glslang::EOpMinInvocationsInclusiveScan:
4411 case glslang::EOpMaxInvocationsInclusiveScan:
4412 case glslang::EOpAddInvocationsInclusiveScan:
4413 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4414 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4415 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4416 case glslang::EOpMinInvocationsExclusiveScan:
4417 case glslang::EOpMaxInvocationsExclusiveScan:
4418 case glslang::EOpAddInvocationsExclusiveScan:
4419 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4420 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4421 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004422#endif
Rex Xu51596642016-09-21 18:56:12 +08004423 {
4424 std::vector<spv::Id> operands;
4425 operands.push_back(operand);
4426 return createInvocationsOperation(op, typeId, operands, typeProxy);
4427 }
Rex Xu9d93a232016-05-05 12:30:44 +08004428
4429#ifdef AMD_EXTENSIONS
4430 case glslang::EOpMbcnt:
4431 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4432 libCall = spv::MbcntAMD;
4433 break;
4434
4435 case glslang::EOpCubeFaceIndex:
4436 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4437 libCall = spv::CubeFaceIndexAMD;
4438 break;
4439
4440 case glslang::EOpCubeFaceCoord:
4441 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4442 libCall = spv::CubeFaceCoordAMD;
4443 break;
4444#endif
Rex Xu338b1852016-05-05 20:38:33 +08004445
John Kessenich140f3df2015-06-26 16:58:36 -06004446 default:
4447 return 0;
4448 }
4449
4450 spv::Id id;
4451 if (libCall >= 0) {
4452 std::vector<spv::Id> args;
4453 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004454 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004455 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004456 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004457 }
John Kessenich140f3df2015-06-26 16:58:36 -06004458
qining25262b32016-05-06 17:25:16 -04004459 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004460 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004461}
4462
John Kessenich7a53f762016-01-20 11:19:27 -07004463// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004464spv::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 -07004465{
4466 // Handle unary operations vector by vector.
4467 // The result type is the same type as the original type.
4468 // The algorithm is to:
4469 // - break the matrix into vectors
4470 // - apply the operation to each vector
4471 // - make a matrix out the vector results
4472
4473 // get the types sorted out
4474 int numCols = builder.getNumColumns(operand);
4475 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004476 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4477 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004478 std::vector<spv::Id> results;
4479
4480 // do each vector op
4481 for (int c = 0; c < numCols; ++c) {
4482 std::vector<unsigned int> indexes;
4483 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004484 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4485 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4486 addDecoration(destVec, noContraction);
4487 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004488 }
4489
4490 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004491 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004492}
4493
Rex Xu73e3ce72016-04-27 18:48:17 +08004494spv::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 -06004495{
4496 spv::Op convOp = spv::OpNop;
4497 spv::Id zero = 0;
4498 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004499 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004500
4501 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4502
4503 switch (op) {
4504 case glslang::EOpConvIntToBool:
4505 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004506 case glslang::EOpConvInt64ToBool:
4507 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004508#ifdef AMD_EXTENSIONS
4509 case glslang::EOpConvInt16ToBool:
4510 case glslang::EOpConvUint16ToBool:
4511#endif
4512 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4513 zero = builder.makeUint64Constant(0);
4514#ifdef AMD_EXTENSIONS
4515 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4516 zero = builder.makeUint16Constant(0);
4517#endif
4518 else
4519 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004520 zero = makeSmearedConstant(zero, vectorSize);
4521 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4522
4523 case glslang::EOpConvFloatToBool:
4524 zero = builder.makeFloatConstant(0.0F);
4525 zero = makeSmearedConstant(zero, vectorSize);
4526 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4527
4528 case glslang::EOpConvDoubleToBool:
4529 zero = builder.makeDoubleConstant(0.0);
4530 zero = makeSmearedConstant(zero, vectorSize);
4531 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4532
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004533#ifdef AMD_EXTENSIONS
4534 case glslang::EOpConvFloat16ToBool:
4535 zero = builder.makeFloat16Constant(0.0F);
4536 zero = makeSmearedConstant(zero, vectorSize);
4537 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4538#endif
4539
John Kessenich140f3df2015-06-26 16:58:36 -06004540 case glslang::EOpConvBoolToFloat:
4541 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004542 zero = builder.makeFloatConstant(0.0F);
4543 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004544 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004545
John Kessenich140f3df2015-06-26 16:58:36 -06004546 case glslang::EOpConvBoolToDouble:
4547 convOp = spv::OpSelect;
4548 zero = builder.makeDoubleConstant(0.0);
4549 one = builder.makeDoubleConstant(1.0);
4550 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004551
4552#ifdef AMD_EXTENSIONS
4553 case glslang::EOpConvBoolToFloat16:
4554 convOp = spv::OpSelect;
4555 zero = builder.makeFloat16Constant(0.0F);
4556 one = builder.makeFloat16Constant(1.0F);
4557 break;
4558#endif
4559
John Kessenich140f3df2015-06-26 16:58:36 -06004560 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004561 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004562#ifdef AMD_EXTENSIONS
4563 case glslang::EOpConvBoolToInt16:
4564#endif
4565 if (op == glslang::EOpConvBoolToInt64)
4566 zero = builder.makeInt64Constant(0);
4567#ifdef AMD_EXTENSIONS
4568 else if (op == glslang::EOpConvBoolToInt16)
4569 zero = builder.makeInt16Constant(0);
4570#endif
4571 else
4572 zero = builder.makeIntConstant(0);
4573
4574 if (op == glslang::EOpConvBoolToInt64)
4575 one = builder.makeInt64Constant(1);
4576#ifdef AMD_EXTENSIONS
4577 else if (op == glslang::EOpConvBoolToInt16)
4578 one = builder.makeInt16Constant(1);
4579#endif
4580 else
4581 one = builder.makeIntConstant(1);
4582
John Kessenich140f3df2015-06-26 16:58:36 -06004583 convOp = spv::OpSelect;
4584 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004585
John Kessenich140f3df2015-06-26 16:58:36 -06004586 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004587 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004588#ifdef AMD_EXTENSIONS
4589 case glslang::EOpConvBoolToUint16:
4590#endif
4591 if (op == glslang::EOpConvBoolToUint64)
4592 zero = builder.makeUint64Constant(0);
4593#ifdef AMD_EXTENSIONS
4594 else if (op == glslang::EOpConvBoolToUint16)
4595 zero = builder.makeUint16Constant(0);
4596#endif
4597 else
4598 zero = builder.makeUintConstant(0);
4599
4600 if (op == glslang::EOpConvBoolToUint64)
4601 one = builder.makeUint64Constant(1);
4602#ifdef AMD_EXTENSIONS
4603 else if (op == glslang::EOpConvBoolToUint16)
4604 one = builder.makeUint16Constant(1);
4605#endif
4606 else
4607 one = builder.makeUintConstant(1);
4608
John Kessenich140f3df2015-06-26 16:58:36 -06004609 convOp = spv::OpSelect;
4610 break;
4611
4612 case glslang::EOpConvIntToFloat:
4613 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004614 case glslang::EOpConvInt64ToFloat:
4615 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004616#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004617 case glslang::EOpConvInt16ToFloat:
4618 case glslang::EOpConvInt16ToDouble:
4619 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004620 case glslang::EOpConvIntToFloat16:
4621 case glslang::EOpConvInt64ToFloat16:
4622#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004623 convOp = spv::OpConvertSToF;
4624 break;
4625
4626 case glslang::EOpConvUintToFloat:
4627 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004628 case glslang::EOpConvUint64ToFloat:
4629 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004630#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004631 case glslang::EOpConvUint16ToFloat:
4632 case glslang::EOpConvUint16ToDouble:
4633 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004634 case glslang::EOpConvUintToFloat16:
4635 case glslang::EOpConvUint64ToFloat16:
4636#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004637 convOp = spv::OpConvertUToF;
4638 break;
4639
4640 case glslang::EOpConvDoubleToFloat:
4641 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004642#ifdef AMD_EXTENSIONS
4643 case glslang::EOpConvDoubleToFloat16:
4644 case glslang::EOpConvFloat16ToDouble:
4645 case glslang::EOpConvFloatToFloat16:
4646 case glslang::EOpConvFloat16ToFloat:
4647#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004648 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004649 if (builder.isMatrixType(destType))
4650 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004651 break;
4652
4653 case glslang::EOpConvFloatToInt:
4654 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004655 case glslang::EOpConvFloatToInt64:
4656 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004657#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004658 case glslang::EOpConvFloatToInt16:
4659 case glslang::EOpConvDoubleToInt16:
4660 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004661 case glslang::EOpConvFloat16ToInt:
4662 case glslang::EOpConvFloat16ToInt64:
4663#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004664 convOp = spv::OpConvertFToS;
4665 break;
4666
4667 case glslang::EOpConvUintToInt:
4668 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004669 case glslang::EOpConvUint64ToInt64:
4670 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004671#ifdef AMD_EXTENSIONS
4672 case glslang::EOpConvUint16ToInt16:
4673 case glslang::EOpConvInt16ToUint16:
4674#endif
qininge24aa5e2016-04-07 15:40:27 -04004675 if (builder.isInSpecConstCodeGenMode()) {
4676 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004677 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4678 zero = builder.makeUint64Constant(0);
4679#ifdef AMD_EXTENSIONS
4680 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4681 zero = builder.makeUint16Constant(0);
4682#endif
4683 else
4684 zero = builder.makeUintConstant(0);
4685
qining189b2032016-04-12 23:16:20 -04004686 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004687 // Use OpIAdd, instead of OpBitcast to do the conversion when
4688 // generating for OpSpecConstantOp instruction.
4689 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4690 }
4691 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004692 convOp = spv::OpBitcast;
4693 break;
4694
4695 case glslang::EOpConvFloatToUint:
4696 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004697 case glslang::EOpConvFloatToUint64:
4698 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004699#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004700 case glslang::EOpConvFloatToUint16:
4701 case glslang::EOpConvDoubleToUint16:
4702 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004703 case glslang::EOpConvFloat16ToUint:
4704 case glslang::EOpConvFloat16ToUint64:
4705#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004706 convOp = spv::OpConvertFToU;
4707 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004708
4709 case glslang::EOpConvIntToInt64:
4710 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004711#ifdef AMD_EXTENSIONS
4712 case glslang::EOpConvIntToInt16:
4713 case glslang::EOpConvInt16ToInt:
4714 case glslang::EOpConvInt64ToInt16:
4715 case glslang::EOpConvInt16ToInt64:
4716#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004717 convOp = spv::OpSConvert;
4718 break;
4719
4720 case glslang::EOpConvUintToUint64:
4721 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004722#ifdef AMD_EXTENSIONS
4723 case glslang::EOpConvUintToUint16:
4724 case glslang::EOpConvUint16ToUint:
4725 case glslang::EOpConvUint64ToUint16:
4726 case glslang::EOpConvUint16ToUint64:
4727#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004728 convOp = spv::OpUConvert;
4729 break;
4730
4731 case glslang::EOpConvIntToUint64:
4732 case glslang::EOpConvInt64ToUint:
4733 case glslang::EOpConvUint64ToInt:
4734 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004735#ifdef AMD_EXTENSIONS
4736 case glslang::EOpConvInt16ToUint:
4737 case glslang::EOpConvUintToInt16:
4738 case glslang::EOpConvInt16ToUint64:
4739 case glslang::EOpConvUint64ToInt16:
4740 case glslang::EOpConvUint16ToInt:
4741 case glslang::EOpConvIntToUint16:
4742 case glslang::EOpConvUint16ToInt64:
4743 case glslang::EOpConvInt64ToUint16:
4744#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004745 // OpSConvert/OpUConvert + OpBitCast
4746 switch (op) {
4747 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004748#ifdef AMD_EXTENSIONS
4749 case glslang::EOpConvInt16ToUint64:
4750#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004751 convOp = spv::OpSConvert;
4752 type = builder.makeIntType(64);
4753 break;
4754 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004755#ifdef AMD_EXTENSIONS
4756 case glslang::EOpConvInt16ToUint:
4757#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004758 convOp = spv::OpSConvert;
4759 type = builder.makeIntType(32);
4760 break;
4761 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004762#ifdef AMD_EXTENSIONS
4763 case glslang::EOpConvUint16ToInt:
4764#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004765 convOp = spv::OpUConvert;
4766 type = builder.makeUintType(32);
4767 break;
4768 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004769#ifdef AMD_EXTENSIONS
4770 case glslang::EOpConvUint16ToInt64:
4771#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004772 convOp = spv::OpUConvert;
4773 type = builder.makeUintType(64);
4774 break;
Rex Xucabbb782017-03-24 13:41:14 +08004775#ifdef AMD_EXTENSIONS
4776 case glslang::EOpConvUintToInt16:
4777 case glslang::EOpConvUint64ToInt16:
4778 convOp = spv::OpUConvert;
4779 type = builder.makeUintType(16);
4780 break;
4781 case glslang::EOpConvIntToUint16:
4782 case glslang::EOpConvInt64ToUint16:
4783 convOp = spv::OpSConvert;
4784 type = builder.makeIntType(16);
4785 break;
4786#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004787 default:
4788 assert(0);
4789 break;
4790 }
4791
4792 if (vectorSize > 0)
4793 type = builder.makeVectorType(type, vectorSize);
4794
4795 operand = builder.createUnaryOp(convOp, type, operand);
4796
4797 if (builder.isInSpecConstCodeGenMode()) {
4798 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004799#ifdef AMD_EXTENSIONS
4800 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4801 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4802 zero = builder.makeUint64Constant(0);
4803 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4804 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4805 zero = builder.makeUint16Constant(0);
4806 else
4807 zero = builder.makeUintConstant(0);
4808#else
4809 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4810 zero = builder.makeUint64Constant(0);
4811 else
4812 zero = builder.makeUintConstant(0);
4813#endif
4814
Rex Xu8ff43de2016-04-22 16:51:45 +08004815 zero = makeSmearedConstant(zero, vectorSize);
4816 // Use OpIAdd, instead of OpBitcast to do the conversion when
4817 // generating for OpSpecConstantOp instruction.
4818 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4819 }
4820 // For normal run-time conversion instruction, use OpBitcast.
4821 convOp = spv::OpBitcast;
4822 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004823 default:
4824 break;
4825 }
4826
4827 spv::Id result = 0;
4828 if (convOp == spv::OpNop)
4829 return result;
4830
4831 if (convOp == spv::OpSelect) {
4832 zero = makeSmearedConstant(zero, vectorSize);
4833 one = makeSmearedConstant(one, vectorSize);
4834 result = builder.createTriOp(convOp, destType, operand, one, zero);
4835 } else
4836 result = builder.createUnaryOp(convOp, destType, operand);
4837
John Kessenich32cfd492016-02-02 12:37:46 -07004838 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004839}
4840
4841spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4842{
4843 if (vectorSize == 0)
4844 return constant;
4845
4846 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4847 std::vector<spv::Id> components;
4848 for (int c = 0; c < vectorSize; ++c)
4849 components.push_back(constant);
4850 return builder.makeCompositeConstant(vectorTypeId, components);
4851}
4852
John Kessenich426394d2015-07-23 10:22:48 -06004853// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004854spv::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 -06004855{
4856 spv::Op opCode = spv::OpNop;
4857
4858 switch (op) {
4859 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004860 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004861 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004862 opCode = spv::OpAtomicIAdd;
4863 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004864 case glslang::EOpAtomicCounterSubtract:
4865 opCode = spv::OpAtomicISub;
4866 break;
John Kessenich426394d2015-07-23 10:22:48 -06004867 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004868 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004869 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004870 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004871 break;
4872 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004873 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004874 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004875 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004876 break;
4877 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004878 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004879 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004880 opCode = spv::OpAtomicAnd;
4881 break;
4882 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004883 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004884 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004885 opCode = spv::OpAtomicOr;
4886 break;
4887 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004888 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004889 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004890 opCode = spv::OpAtomicXor;
4891 break;
4892 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004893 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004894 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004895 opCode = spv::OpAtomicExchange;
4896 break;
4897 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004898 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004899 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004900 opCode = spv::OpAtomicCompareExchange;
4901 break;
4902 case glslang::EOpAtomicCounterIncrement:
4903 opCode = spv::OpAtomicIIncrement;
4904 break;
4905 case glslang::EOpAtomicCounterDecrement:
4906 opCode = spv::OpAtomicIDecrement;
4907 break;
4908 case glslang::EOpAtomicCounter:
4909 opCode = spv::OpAtomicLoad;
4910 break;
4911 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004912 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004913 break;
4914 }
4915
Rex Xue8fe8b02017-09-26 15:42:56 +08004916 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4917 builder.addCapability(spv::CapabilityInt64Atomics);
4918
John Kessenich426394d2015-07-23 10:22:48 -06004919 // Sort out the operands
4920 // - mapping from glslang -> SPV
4921 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004922 // - compare-exchange swaps the value and comparator
4923 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004924 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004925 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4926 auto opIt = operands.begin(); // walk the glslang operands
4927 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004928 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4929 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4930 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004931 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4932 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004933 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004934 spvAtomicOperands.push_back(*(opIt + 1));
4935 spvAtomicOperands.push_back(*opIt);
4936 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004937 }
John Kessenich426394d2015-07-23 10:22:48 -06004938
John Kessenich3e60a6f2015-09-14 22:45:16 -06004939 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004940 for (; opIt != operands.end(); ++opIt)
4941 spvAtomicOperands.push_back(*opIt);
4942
John Kessenich48d6e792017-10-06 21:21:48 -06004943 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4944
4945 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4946 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4947 if (op == glslang::EOpAtomicCounterDecrement)
4948 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4949
4950 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004951}
4952
John Kessenich91cef522016-05-05 16:45:40 -06004953// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004954spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004955{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004956#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004957 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004958 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004959#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004960
Rex Xu51596642016-09-21 18:56:12 +08004961 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004962 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004963 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4964
chaocf200da82016-12-20 12:44:35 -08004965 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4966 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004967 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4968 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004969 } else if (op == glslang::EOpAnyInvocation ||
4970 op == glslang::EOpAllInvocations ||
4971 op == glslang::EOpAllInvocationsEqual) {
4972 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4973 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004974 } else {
4975 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004976#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004977 if (op == glslang::EOpMinInvocationsNonUniform ||
4978 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004979 op == glslang::EOpAddInvocationsNonUniform ||
4980 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4981 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4982 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4983 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4984 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4985 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004986 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004987#endif
Rex Xu51596642016-09-21 18:56:12 +08004988
4989 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004990#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004991 switch (op) {
4992 case glslang::EOpMinInvocations:
4993 case glslang::EOpMaxInvocations:
4994 case glslang::EOpAddInvocations:
4995 case glslang::EOpMinInvocationsNonUniform:
4996 case glslang::EOpMaxInvocationsNonUniform:
4997 case glslang::EOpAddInvocationsNonUniform:
4998 groupOperation = spv::GroupOperationReduce;
4999 spvGroupOperands.push_back(groupOperation);
5000 break;
5001 case glslang::EOpMinInvocationsInclusiveScan:
5002 case glslang::EOpMaxInvocationsInclusiveScan:
5003 case glslang::EOpAddInvocationsInclusiveScan:
5004 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5005 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5006 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5007 groupOperation = spv::GroupOperationInclusiveScan;
5008 spvGroupOperands.push_back(groupOperation);
5009 break;
5010 case glslang::EOpMinInvocationsExclusiveScan:
5011 case glslang::EOpMaxInvocationsExclusiveScan:
5012 case glslang::EOpAddInvocationsExclusiveScan:
5013 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5014 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5015 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5016 groupOperation = spv::GroupOperationExclusiveScan;
5017 spvGroupOperands.push_back(groupOperation);
5018 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005019 default:
5020 break;
Rex Xu430ef402016-10-14 17:22:23 +08005021 }
Rex Xu9d93a232016-05-05 12:30:44 +08005022#endif
Rex Xu51596642016-09-21 18:56:12 +08005023 }
5024
5025 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5026 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005027
5028 switch (op) {
5029 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005030 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005031 break;
John Kessenich91cef522016-05-05 16:45:40 -06005032 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005033 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005034 break;
John Kessenich91cef522016-05-05 16:45:40 -06005035 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005036 opCode = spv::OpSubgroupAllEqualKHR;
5037 break;
Rex Xu51596642016-09-21 18:56:12 +08005038 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005039 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005040 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005041 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005042 break;
5043 case glslang::EOpReadFirstInvocation:
5044 opCode = spv::OpSubgroupFirstInvocationKHR;
5045 break;
5046 case glslang::EOpBallot:
5047 {
5048 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5049 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5050 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5051 //
5052 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5053 //
5054 spv::Id uintType = builder.makeUintType(32);
5055 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5056 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5057
5058 std::vector<spv::Id> components;
5059 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5060 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5061
5062 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5063 return builder.createUnaryOp(spv::OpBitcast, typeId,
5064 builder.createCompositeConstruct(uvec2Type, components));
5065 }
5066
Rex Xu9d93a232016-05-05 12:30:44 +08005067#ifdef AMD_EXTENSIONS
5068 case glslang::EOpMinInvocations:
5069 case glslang::EOpMaxInvocations:
5070 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005071 case glslang::EOpMinInvocationsInclusiveScan:
5072 case glslang::EOpMaxInvocationsInclusiveScan:
5073 case glslang::EOpAddInvocationsInclusiveScan:
5074 case glslang::EOpMinInvocationsExclusiveScan:
5075 case glslang::EOpMaxInvocationsExclusiveScan:
5076 case glslang::EOpAddInvocationsExclusiveScan:
5077 if (op == glslang::EOpMinInvocations ||
5078 op == glslang::EOpMinInvocationsInclusiveScan ||
5079 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005080 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005081 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005082 else {
5083 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005084 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005085 else
Rex Xu51596642016-09-21 18:56:12 +08005086 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005087 }
Rex Xu430ef402016-10-14 17:22:23 +08005088 } else if (op == glslang::EOpMaxInvocations ||
5089 op == glslang::EOpMaxInvocationsInclusiveScan ||
5090 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005091 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005092 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005093 else {
5094 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005095 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005096 else
Rex Xu51596642016-09-21 18:56:12 +08005097 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005098 }
5099 } else {
5100 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005101 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005102 else
Rex Xu51596642016-09-21 18:56:12 +08005103 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005104 }
5105
Rex Xu2bbbe062016-08-23 15:41:05 +08005106 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005107 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005108
5109 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005110 case glslang::EOpMinInvocationsNonUniform:
5111 case glslang::EOpMaxInvocationsNonUniform:
5112 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005113 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5114 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5115 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5116 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5117 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5118 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5119 if (op == glslang::EOpMinInvocationsNonUniform ||
5120 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5121 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005122 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005123 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005124 else {
5125 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005126 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005127 else
Rex Xu51596642016-09-21 18:56:12 +08005128 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005129 }
5130 }
Rex Xu430ef402016-10-14 17:22:23 +08005131 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5132 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5133 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005134 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005135 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005136 else {
5137 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005138 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005139 else
Rex Xu51596642016-09-21 18:56:12 +08005140 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005141 }
5142 }
5143 else {
5144 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005145 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005146 else
Rex Xu51596642016-09-21 18:56:12 +08005147 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005148 }
5149
Rex Xu2bbbe062016-08-23 15:41:05 +08005150 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005151 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005152
5153 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005154#endif
John Kessenich91cef522016-05-05 16:45:40 -06005155 default:
5156 logger->missingFunctionality("invocation operation");
5157 return spv::NoResult;
5158 }
Rex Xu51596642016-09-21 18:56:12 +08005159
5160 assert(opCode != spv::OpNop);
5161 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005162}
5163
Rex Xu2bbbe062016-08-23 15:41:05 +08005164// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005165spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005166{
Rex Xub7072052016-09-26 15:53:40 +08005167#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005168 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5169 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005170 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005171 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005172 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5173 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5174 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005175#else
5176 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5177 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005178 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5179 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005180#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005181
5182 // Handle group invocation operations scalar by scalar.
5183 // The result type is the same type as the original type.
5184 // The algorithm is to:
5185 // - break the vector into scalars
5186 // - apply the operation to each scalar
5187 // - make a vector out the scalar results
5188
5189 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005190 int numComponents = builder.getNumComponents(operands[0]);
5191 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005192 std::vector<spv::Id> results;
5193
5194 // do each scalar op
5195 for (int comp = 0; comp < numComponents; ++comp) {
5196 std::vector<unsigned int> indexes;
5197 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005198 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005199 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005200 if (op == spv::OpSubgroupReadInvocationKHR) {
5201 spvGroupOperands.push_back(scalar);
5202 spvGroupOperands.push_back(operands[1]);
5203 } else if (op == spv::OpGroupBroadcast) {
5204 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005205 spvGroupOperands.push_back(scalar);
5206 spvGroupOperands.push_back(operands[1]);
5207 } else {
chaocf200da82016-12-20 12:44:35 -08005208 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005209 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005210 spvGroupOperands.push_back(scalar);
5211 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005212
Rex Xub7072052016-09-26 15:53:40 +08005213 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005214 }
5215
5216 // put the pieces together
5217 return builder.createCompositeConstruct(typeId, results);
5218}
Rex Xu2bbbe062016-08-23 15:41:05 +08005219
John Kessenich5e4b1242015-08-06 22:53:06 -06005220spv::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 -06005221{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005222#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005223 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005224 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5225#else
Rex Xucabbb782017-03-24 13:41:14 +08005226 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005228#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005229
John Kessenich140f3df2015-06-26 16:58:36 -06005230 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005231 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005233 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005234 spv::Id typeId0 = 0;
5235 if (consumedOperands > 0)
5236 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005237 spv::Id typeId1 = 0;
5238 if (consumedOperands > 1)
5239 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005240 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005241
5242 switch (op) {
5243 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005244 if (isFloat)
5245 libCall = spv::GLSLstd450FMin;
5246 else if (isUnsigned)
5247 libCall = spv::GLSLstd450UMin;
5248 else
5249 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005250 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
5252 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005253 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005254 break;
5255 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 if (isFloat)
5257 libCall = spv::GLSLstd450FMax;
5258 else if (isUnsigned)
5259 libCall = spv::GLSLstd450UMax;
5260 else
5261 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005262 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005263 break;
5264 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005265 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005266 break;
5267 case glslang::EOpDot:
5268 opCode = spv::OpDot;
5269 break;
5270 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005271 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005272 break;
5273
5274 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005275 if (isFloat)
5276 libCall = spv::GLSLstd450FClamp;
5277 else if (isUnsigned)
5278 libCall = spv::GLSLstd450UClamp;
5279 else
5280 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005281 builder.promoteScalar(precision, operands.front(), operands[1]);
5282 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005285 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5286 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005287 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005288 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005289 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005290 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005291 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005292 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
5294 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005295 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005296 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005297 break;
5298 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005299 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005300 builder.promoteScalar(precision, operands[0], operands[2]);
5301 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005302 break;
5303
5304 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005305 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005306 break;
5307 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005308 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005309 break;
5310 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005311 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005312 break;
5313 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005314 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 break;
5316 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005317 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005318 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005319 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005320 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005321 libCall = spv::GLSLstd450InterpolateAtSample;
5322 break;
5323 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005324 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005325 libCall = spv::GLSLstd450InterpolateAtOffset;
5326 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005327 case glslang::EOpAddCarry:
5328 opCode = spv::OpIAddCarry;
5329 typeId = builder.makeStructResultType(typeId0, typeId0);
5330 consumedOperands = 2;
5331 break;
5332 case glslang::EOpSubBorrow:
5333 opCode = spv::OpISubBorrow;
5334 typeId = builder.makeStructResultType(typeId0, typeId0);
5335 consumedOperands = 2;
5336 break;
5337 case glslang::EOpUMulExtended:
5338 opCode = spv::OpUMulExtended;
5339 typeId = builder.makeStructResultType(typeId0, typeId0);
5340 consumedOperands = 2;
5341 break;
5342 case glslang::EOpIMulExtended:
5343 opCode = spv::OpSMulExtended;
5344 typeId = builder.makeStructResultType(typeId0, typeId0);
5345 consumedOperands = 2;
5346 break;
5347 case glslang::EOpBitfieldExtract:
5348 if (isUnsigned)
5349 opCode = spv::OpBitFieldUExtract;
5350 else
5351 opCode = spv::OpBitFieldSExtract;
5352 break;
5353 case glslang::EOpBitfieldInsert:
5354 opCode = spv::OpBitFieldInsert;
5355 break;
5356
5357 case glslang::EOpFma:
5358 libCall = spv::GLSLstd450Fma;
5359 break;
5360 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005361 {
5362 libCall = spv::GLSLstd450FrexpStruct;
5363 assert(builder.isPointerType(typeId1));
5364 typeId1 = builder.getContainedTypeId(typeId1);
5365#ifdef AMD_EXTENSIONS
5366 int width = builder.getScalarTypeWidth(typeId1);
5367#else
5368 int width = 32;
5369#endif
5370 if (builder.getNumComponents(operands[0]) == 1)
5371 frexpIntType = builder.makeIntegerType(width, true);
5372 else
5373 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5374 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5375 consumedOperands = 1;
5376 }
John Kessenich55e7d112015-11-15 21:33:39 -07005377 break;
5378 case glslang::EOpLdexp:
5379 libCall = spv::GLSLstd450Ldexp;
5380 break;
5381
Rex Xu574ab042016-04-14 16:53:07 +08005382 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005383 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005384
Rex Xu9d93a232016-05-05 12:30:44 +08005385#ifdef AMD_EXTENSIONS
5386 case glslang::EOpSwizzleInvocations:
5387 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5388 libCall = spv::SwizzleInvocationsAMD;
5389 break;
5390 case glslang::EOpSwizzleInvocationsMasked:
5391 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5392 libCall = spv::SwizzleInvocationsMaskedAMD;
5393 break;
5394 case glslang::EOpWriteInvocation:
5395 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5396 libCall = spv::WriteInvocationAMD;
5397 break;
5398
5399 case glslang::EOpMin3:
5400 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5401 if (isFloat)
5402 libCall = spv::FMin3AMD;
5403 else {
5404 if (isUnsigned)
5405 libCall = spv::UMin3AMD;
5406 else
5407 libCall = spv::SMin3AMD;
5408 }
5409 break;
5410 case glslang::EOpMax3:
5411 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5412 if (isFloat)
5413 libCall = spv::FMax3AMD;
5414 else {
5415 if (isUnsigned)
5416 libCall = spv::UMax3AMD;
5417 else
5418 libCall = spv::SMax3AMD;
5419 }
5420 break;
5421 case glslang::EOpMid3:
5422 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5423 if (isFloat)
5424 libCall = spv::FMid3AMD;
5425 else {
5426 if (isUnsigned)
5427 libCall = spv::UMid3AMD;
5428 else
5429 libCall = spv::SMid3AMD;
5430 }
5431 break;
5432
5433 case glslang::EOpInterpolateAtVertex:
5434 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5435 libCall = spv::InterpolateAtVertexAMD;
5436 break;
5437#endif
5438
John Kessenich140f3df2015-06-26 16:58:36 -06005439 default:
5440 return 0;
5441 }
5442
5443 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005444 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005445 // Use an extended instruction from the standard library.
5446 // Construct the call arguments, without modifying the original operands vector.
5447 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5448 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005449 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005450 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005451 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005452 case 0:
5453 // should all be handled by visitAggregate and createNoArgOperation
5454 assert(0);
5455 return 0;
5456 case 1:
5457 // should all be handled by createUnaryOperation
5458 assert(0);
5459 return 0;
5460 case 2:
5461 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5462 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005463 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005464 // anything 3 or over doesn't have l-value operands, so all should be consumed
5465 assert(consumedOperands == operands.size());
5466 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005467 break;
5468 }
5469 }
5470
John Kessenich55e7d112015-11-15 21:33:39 -07005471 // Decode the return types that were structures
5472 switch (op) {
5473 case glslang::EOpAddCarry:
5474 case glslang::EOpSubBorrow:
5475 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5476 id = builder.createCompositeExtract(id, typeId0, 0);
5477 break;
5478 case glslang::EOpUMulExtended:
5479 case glslang::EOpIMulExtended:
5480 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5481 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5482 break;
5483 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005484 {
5485 assert(operands.size() == 2);
5486 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5487 // "exp" is floating-point type (from HLSL intrinsic)
5488 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5489 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5490 builder.createStore(member1, operands[1]);
5491 } else
5492 // "exp" is integer type (from GLSL built-in function)
5493 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5494 id = builder.createCompositeExtract(id, typeId0, 0);
5495 }
John Kessenich55e7d112015-11-15 21:33:39 -07005496 break;
5497 default:
5498 break;
5499 }
5500
John Kessenich32cfd492016-02-02 12:37:46 -07005501 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005502}
5503
Rex Xu9d93a232016-05-05 12:30:44 +08005504// Intrinsics with no arguments (or no return value, and no precision).
5505spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005506{
5507 // TODO: get the barrier operands correct
5508
5509 switch (op) {
5510 case glslang::EOpEmitVertex:
5511 builder.createNoResultOp(spv::OpEmitVertex);
5512 return 0;
5513 case glslang::EOpEndPrimitive:
5514 builder.createNoResultOp(spv::OpEndPrimitive);
5515 return 0;
5516 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005517 if (glslangIntermediate->getStage() == EShLangTessControl) {
5518 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5519 // TODO: prefer the following, when available:
5520 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5521 // spv::MemorySemanticsPatchMask |
5522 // spv::MemorySemanticsAcquireReleaseMask);
5523 } else {
5524 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5525 spv::MemorySemanticsWorkgroupMemoryMask |
5526 spv::MemorySemanticsAcquireReleaseMask);
5527 }
John Kessenich140f3df2015-06-26 16:58:36 -06005528 return 0;
5529 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005530 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5531 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005532 return 0;
5533 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005534 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5535 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005536 return 0;
5537 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005538 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5539 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005540 return 0;
5541 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005542 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5543 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005544 return 0;
5545 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005546 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5547 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005548 return 0;
5549 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005550 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5551 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005552 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005553 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005554 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005555 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005556 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005557 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005558 case glslang::EOpDeviceMemoryBarrier:
5559 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5560 spv::MemorySemanticsImageMemoryMask |
5561 spv::MemorySemanticsAcquireReleaseMask);
5562 return 0;
5563 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5564 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5565 spv::MemorySemanticsImageMemoryMask |
5566 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005567 return 0;
5568 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005569 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5570 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005571 return 0;
5572 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005573 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5574 spv::MemorySemanticsWorkgroupMemoryMask |
5575 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005576 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005577#ifdef AMD_EXTENSIONS
5578 case glslang::EOpTime:
5579 {
5580 std::vector<spv::Id> args; // Dummy arguments
5581 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5582 return builder.setPrecision(id, precision);
5583 }
5584#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005585 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005586 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005587 return 0;
5588 }
5589}
5590
5591spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5592{
John Kessenich2f273362015-07-18 22:34:27 -06005593 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005594 spv::Id id;
5595 if (symbolValues.end() != iter) {
5596 id = iter->second;
5597 return id;
5598 }
5599
5600 // it was not found, create it
5601 id = createSpvVariable(symbol);
5602 symbolValues[symbol->getId()] = id;
5603
Rex Xuc884b4a2016-06-29 15:03:44 +08005604 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005605 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005606 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005607 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005608 if (symbol->getType().getQualifier().hasSpecConstantId())
5609 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005610 if (symbol->getQualifier().hasIndex())
5611 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5612 if (symbol->getQualifier().hasComponent())
5613 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005614 // atomic counters use this:
5615 if (symbol->getQualifier().hasOffset())
5616 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005617 }
5618
scygan2c864272016-05-18 18:09:17 +02005619 if (symbol->getQualifier().hasLocation())
5620 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005621 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005622 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005623 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005624 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005625 }
John Kessenich140f3df2015-06-26 16:58:36 -06005626 if (symbol->getQualifier().hasSet())
5627 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005628 else if (IsDescriptorResource(symbol->getType())) {
5629 // default to 0
5630 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5631 }
John Kessenich140f3df2015-06-26 16:58:36 -06005632 if (symbol->getQualifier().hasBinding())
5633 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005634 if (symbol->getQualifier().hasAttachment())
5635 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005636 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005637 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005638 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005639 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005640 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005641 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005642 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5643 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5644 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5645 }
5646 if (symbol->getQualifier().hasXfbOffset())
5647 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005648 }
5649
Rex Xu1da878f2016-02-21 20:59:01 +08005650 if (symbol->getType().isImage()) {
5651 std::vector<spv::Decoration> memory;
5652 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5653 for (unsigned int i = 0; i < memory.size(); ++i)
5654 addDecoration(id, memory[i]);
5655 }
5656
John Kessenich140f3df2015-06-26 16:58:36 -06005657 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005658 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005659 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005660 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005661
John Kessenichecba76f2017-01-06 00:34:48 -07005662#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005663 if (builtIn == spv::BuiltInSampleMask) {
5664 spv::Decoration decoration;
5665 // GL_NV_sample_mask_override_coverage extension
5666 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005667 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005668 else
5669 decoration = (spv::Decoration)spv::DecorationMax;
5670 addDecoration(id, decoration);
5671 if (decoration != spv::DecorationMax) {
5672 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5673 }
5674 }
chaoc771d89f2017-01-13 01:10:53 -08005675 else if (builtIn == spv::BuiltInLayer) {
5676 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005677 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005678 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5679 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5680 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5681 }
John Kessenichb41bff62017-08-11 13:07:17 -06005682 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005683 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5684 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5685 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5686 }
5687 }
5688
chaoc6e5acae2016-12-20 13:28:52 -08005689 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005690 addDecoration(id, spv::DecorationPassthroughNV);
5691 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005692 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5693 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005694#endif
5695
John Kessenich140f3df2015-06-26 16:58:36 -06005696 return id;
5697}
5698
John Kessenich55e7d112015-11-15 21:33:39 -07005699// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005700void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5701{
John Kessenich4016e382016-07-15 11:53:56 -06005702 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005703 builder.addDecoration(id, dec);
5704}
5705
John Kessenich55e7d112015-11-15 21:33:39 -07005706// If 'dec' is valid, add a one-operand decoration to an object
5707void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5708{
John Kessenich4016e382016-07-15 11:53:56 -06005709 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005710 builder.addDecoration(id, dec, value);
5711}
5712
5713// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005714void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5715{
John Kessenich4016e382016-07-15 11:53:56 -06005716 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005717 builder.addMemberDecoration(id, (unsigned)member, dec);
5718}
5719
John Kessenich92187592016-02-01 13:45:25 -07005720// If 'dec' is valid, add a one-operand decoration to a struct member
5721void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5722{
John Kessenich4016e382016-07-15 11:53:56 -06005723 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005724 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5725}
5726
John Kessenich55e7d112015-11-15 21:33:39 -07005727// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005728// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005729//
5730// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5731//
5732// Recursively walk the nodes. The nodes form a tree whose leaves are
5733// regular constants, which themselves are trees that createSpvConstant()
5734// recursively walks. So, this function walks the "top" of the tree:
5735// - emit specialization constant-building instructions for specConstant
5736// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005737spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005738{
John Kessenich7cc0e282016-03-20 00:46:02 -06005739 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005740
qining4f4bb812016-04-03 23:55:17 -04005741 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005742 if (! node.getQualifier().specConstant) {
5743 // hand off to the non-spec-constant path
5744 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5745 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005746 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005747 nextConst, false);
5748 }
5749
5750 // We now know we have a specialization constant to build
5751
John Kessenichd94c0032016-05-30 19:29:40 -06005752 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005753 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5754 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5755 std::vector<spv::Id> dimConstId;
5756 for (int dim = 0; dim < 3; ++dim) {
5757 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5758 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5759 if (specConst)
5760 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5761 }
5762 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5763 }
5764
5765 // An AST node labelled as specialization constant should be a symbol node.
5766 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5767 if (auto* sn = node.getAsSymbolNode()) {
5768 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005769 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5770 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5771 // will set the builder into spec constant op instruction generating mode.
5772 sub_tree->traverse(this);
5773 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005774 } else if (auto* const_union_array = &sn->getConstArray()){
5775 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005776 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5777 builder.addName(id, sn->getName().c_str());
5778 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005779 }
5780 }
qining4f4bb812016-04-03 23:55:17 -04005781
5782 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5783 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005784 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005785 exit(1);
5786 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005787}
5788
John Kessenich140f3df2015-06-26 16:58:36 -06005789// Use 'consts' as the flattened glslang source of scalar constants to recursively
5790// build the aggregate SPIR-V constant.
5791//
5792// If there are not enough elements present in 'consts', 0 will be substituted;
5793// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5794//
qining08408382016-03-21 09:51:37 -04005795spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005796{
5797 // vector of constants for SPIR-V
5798 std::vector<spv::Id> spvConsts;
5799
5800 // Type is used for struct and array constants
5801 spv::Id typeId = convertGlslangToSpvType(glslangType);
5802
5803 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005804 glslang::TType elementType(glslangType, 0);
5805 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005806 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005807 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005808 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005809 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005810 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005811 } else if (glslangType.getStruct()) {
5812 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5813 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005814 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005815 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005816 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5817 bool zero = nextConst >= consts.size();
5818 switch (glslangType.getBasicType()) {
5819 case glslang::EbtInt:
5820 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5821 break;
5822 case glslang::EbtUint:
5823 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5824 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005825 case glslang::EbtInt64:
5826 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5827 break;
5828 case glslang::EbtUint64:
5829 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5830 break;
Rex Xucabbb782017-03-24 13:41:14 +08005831#ifdef AMD_EXTENSIONS
5832 case glslang::EbtInt16:
5833 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5834 break;
5835 case glslang::EbtUint16:
5836 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5837 break;
5838#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005839 case glslang::EbtFloat:
5840 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5841 break;
5842 case glslang::EbtDouble:
5843 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5844 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005845#ifdef AMD_EXTENSIONS
5846 case glslang::EbtFloat16:
5847 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5848 break;
5849#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005850 case glslang::EbtBool:
5851 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5852 break;
5853 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005854 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005855 break;
5856 }
5857 ++nextConst;
5858 }
5859 } else {
5860 // we have a non-aggregate (scalar) constant
5861 bool zero = nextConst >= consts.size();
5862 spv::Id scalar = 0;
5863 switch (glslangType.getBasicType()) {
5864 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005865 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005866 break;
5867 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005868 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005869 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005870 case glslang::EbtInt64:
5871 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5872 break;
5873 case glslang::EbtUint64:
5874 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5875 break;
Rex Xucabbb782017-03-24 13:41:14 +08005876#ifdef AMD_EXTENSIONS
5877 case glslang::EbtInt16:
5878 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5879 break;
5880 case glslang::EbtUint16:
5881 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5882 break;
5883#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005884 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005885 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005886 break;
5887 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005888 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005890#ifdef AMD_EXTENSIONS
5891 case glslang::EbtFloat16:
5892 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5893 break;
5894#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005895 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005896 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
5898 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005899 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005900 break;
5901 }
5902 ++nextConst;
5903 return scalar;
5904 }
5905
5906 return builder.makeCompositeConstant(typeId, spvConsts);
5907}
5908
John Kessenich7c1aa102015-10-15 13:29:11 -06005909// Return true if the node is a constant or symbol whose reading has no
5910// non-trivial observable cost or effect.
5911bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5912{
5913 // don't know what this is
5914 if (node == nullptr)
5915 return false;
5916
5917 // a constant is safe
5918 if (node->getAsConstantUnion() != nullptr)
5919 return true;
5920
5921 // not a symbol means non-trivial
5922 if (node->getAsSymbolNode() == nullptr)
5923 return false;
5924
5925 // a symbol, depends on what's being read
5926 switch (node->getType().getQualifier().storage) {
5927 case glslang::EvqTemporary:
5928 case glslang::EvqGlobal:
5929 case glslang::EvqIn:
5930 case glslang::EvqInOut:
5931 case glslang::EvqConst:
5932 case glslang::EvqConstReadOnly:
5933 case glslang::EvqUniform:
5934 return true;
5935 default:
5936 return false;
5937 }
qining25262b32016-05-06 17:25:16 -04005938}
John Kessenich7c1aa102015-10-15 13:29:11 -06005939
5940// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005941// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005942// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005943// Return true if trivial.
5944bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5945{
5946 if (node == nullptr)
5947 return false;
5948
John Kessenich84cc15f2017-05-24 16:44:47 -06005949 // count non scalars as trivial, as well as anything coming from HLSL
5950 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005951 return true;
5952
John Kessenich7c1aa102015-10-15 13:29:11 -06005953 // symbols and constants are trivial
5954 if (isTrivialLeaf(node))
5955 return true;
5956
5957 // otherwise, it needs to be a simple operation or one or two leaf nodes
5958
5959 // not a simple operation
5960 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5961 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5962 if (binaryNode == nullptr && unaryNode == nullptr)
5963 return false;
5964
5965 // not on leaf nodes
5966 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5967 return false;
5968
5969 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5970 return false;
5971 }
5972
5973 switch (node->getAsOperator()->getOp()) {
5974 case glslang::EOpLogicalNot:
5975 case glslang::EOpConvIntToBool:
5976 case glslang::EOpConvUintToBool:
5977 case glslang::EOpConvFloatToBool:
5978 case glslang::EOpConvDoubleToBool:
5979 case glslang::EOpEqual:
5980 case glslang::EOpNotEqual:
5981 case glslang::EOpLessThan:
5982 case glslang::EOpGreaterThan:
5983 case glslang::EOpLessThanEqual:
5984 case glslang::EOpGreaterThanEqual:
5985 case glslang::EOpIndexDirect:
5986 case glslang::EOpIndexDirectStruct:
5987 case glslang::EOpLogicalXor:
5988 case glslang::EOpAny:
5989 case glslang::EOpAll:
5990 return true;
5991 default:
5992 return false;
5993 }
5994}
5995
5996// Emit short-circuiting code, where 'right' is never evaluated unless
5997// the left side is true (for &&) or false (for ||).
5998spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5999{
6000 spv::Id boolTypeId = builder.makeBoolType();
6001
6002 // emit left operand
6003 builder.clearAccessChain();
6004 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006005 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006006
6007 // Operands to accumulate OpPhi operands
6008 std::vector<spv::Id> phiOperands;
6009 // accumulate left operand's phi information
6010 phiOperands.push_back(leftId);
6011 phiOperands.push_back(builder.getBuildPoint()->getId());
6012
6013 // Make the two kinds of operation symmetric with a "!"
6014 // || => emit "if (! left) result = right"
6015 // && => emit "if ( left) result = right"
6016 //
6017 // TODO: this runtime "not" for || could be avoided by adding functionality
6018 // to 'builder' to have an "else" without an "then"
6019 if (op == glslang::EOpLogicalOr)
6020 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6021
6022 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006023 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006024
6025 // emit right operand as the "then" part of the "if"
6026 builder.clearAccessChain();
6027 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006028 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006029
6030 // accumulate left operand's phi information
6031 phiOperands.push_back(rightId);
6032 phiOperands.push_back(builder.getBuildPoint()->getId());
6033
6034 // finish the "if"
6035 ifBuilder.makeEndIf();
6036
6037 // phi together the two results
6038 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6039}
6040
Frank Henigman541f7bb2018-01-16 00:18:26 -05006041#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006042// Return type Id of the imported set of extended instructions corresponds to the name.
6043// Import this set if it has not been imported yet.
6044spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6045{
6046 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6047 return extBuiltinMap[name];
6048 else {
Rex Xu51596642016-09-21 18:56:12 +08006049 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006050 spv::Id extBuiltins = builder.import(name);
6051 extBuiltinMap[name] = extBuiltins;
6052 return extBuiltins;
6053 }
6054}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006055#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006056
John Kessenich140f3df2015-06-26 16:58:36 -06006057}; // end anonymous namespace
6058
6059namespace glslang {
6060
John Kessenich68d78fd2015-07-12 19:28:10 -06006061void GetSpirvVersion(std::string& version)
6062{
John Kessenich9e55f632015-07-15 10:03:39 -06006063 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006064 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006065 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006066 version = buf;
6067}
6068
John Kessenicha372a3e2017-11-02 22:32:14 -06006069// For low-order part of the generator's magic number. Bump up
6070// when there is a change in the style (e.g., if SSA form changes,
6071// or a different instruction sequence to do something gets used).
6072int GetSpirvGeneratorVersion()
6073{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006074 // return 1; // start
6075 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006076 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
6077 return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenicha372a3e2017-11-02 22:32:14 -06006078}
6079
John Kessenich140f3df2015-06-26 16:58:36 -06006080// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006081void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006082{
6083 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006084 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006085 if (out.fail())
6086 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006087 for (int i = 0; i < (int)spirv.size(); ++i) {
6088 unsigned int word = spirv[i];
6089 out.write((const char*)&word, 4);
6090 }
6091 out.close();
6092}
6093
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006094// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006095void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006096{
6097 std::ofstream out;
6098 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006099 if (out.fail())
6100 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006101 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006102 if (varName != nullptr) {
6103 out << "\t #pragma once" << std::endl;
6104 out << "const uint32_t " << varName << "[] = {" << std::endl;
6105 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006106 const int WORDS_PER_LINE = 8;
6107 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6108 out << "\t";
6109 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6110 const unsigned int word = spirv[i + j];
6111 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6112 if (i + j + 1 < (int)spirv.size()) {
6113 out << ",";
6114 }
6115 }
6116 out << std::endl;
6117 }
Flavio15017db2017-02-15 14:29:33 -08006118 if (varName != nullptr) {
6119 out << "};";
6120 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006121 out.close();
6122}
6123
GregFcd1f1692017-09-21 18:40:22 -06006124#ifdef ENABLE_OPT
6125void errHandler(const std::string& str) {
6126 std::cerr << str << std::endl;
6127}
6128#endif
6129
John Kessenich140f3df2015-06-26 16:58:36 -06006130//
6131// Set up the glslang traversal
6132//
John Kessenich121853f2017-05-31 17:11:16 -06006133void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006134{
Lei Zhang17535f72016-05-04 15:55:59 -04006135 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006136 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006137}
6138
John Kessenich121853f2017-05-31 17:11:16 -06006139void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6140 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006141{
John Kessenich140f3df2015-06-26 16:58:36 -06006142 TIntermNode* root = intermediate.getTreeRoot();
6143
6144 if (root == 0)
6145 return;
6146
John Kessenich121853f2017-05-31 17:11:16 -06006147 glslang::SpvOptions defaultOptions;
6148 if (options == nullptr)
6149 options = &defaultOptions;
6150
John Kessenich140f3df2015-06-26 16:58:36 -06006151 glslang::GetThreadPoolAllocator().push();
6152
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006153 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006154 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006155 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006156 it.dumpSpv(spirv);
6157
GregFcd1f1692017-09-21 18:40:22 -06006158#ifdef ENABLE_OPT
6159 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6160 // eg. forward and remove memory writes of opaque types.
6161 if ((intermediate.getSource() == EShSourceHlsl ||
6162 options->optimizeSize) &&
6163 !options->disableOptimizer) {
6164 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6165
6166 spvtools::Optimizer optimizer(target_env);
6167 optimizer.SetMessageConsumer([](spv_message_level_t level,
6168 const char* source,
6169 const spv_position_t& position,
6170 const char* message) {
6171 std::cerr << StringifyMessage(level, source, position, message)
6172 << std::endl;
6173 });
6174
6175 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006176 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6177 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006178 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6179 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6180 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6181 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006182 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006183 optimizer.RegisterPass(CreateAggressiveDCEPass());
6184 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006185 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006186 optimizer.RegisterPass(CreateBlockMergePass());
6187 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6188 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006189 optimizer.RegisterPass(CreateDeadInsertElimPass());
6190 if (options->optimizeSize) {
6191 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6192 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6193 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6194 }
GregFcd1f1692017-09-21 18:40:22 -06006195 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006196
6197 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6198 return;
6199
6200 // Remove dead module-level objects: functions, types, vars
6201 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6202 spv::spirvbin_t Remapper(0);
6203 Remapper.registerErrorHandler(errHandler);
6204 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6205 }
6206#endif
6207
John Kessenich140f3df2015-06-26 16:58:36 -06006208 glslang::GetThreadPoolAllocator().pop();
6209}
6210
6211}; // end namespace glslang