blob: 420c38ecff1b071ba09837bc297c6d1eb5b971e8 [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
John Kessenichc5215792018-02-27 13:23:08 -07002671 locationOffset += glslangIntermediate->computeTypeLocationSize(
2672 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002673
John Kessenich6090df02016-06-30 21:18:02 -06002674 // component, XFB, others
2675 if (glslangMember.getQualifier().hasComponent())
2676 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2677 if (glslangMember.getQualifier().hasXfbOffset())
2678 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2679 else if (explicitLayout != glslang::ElpNone) {
2680 // figure out what to do with offset, which is accumulating
2681 int nextOffset;
2682 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2683 if (offset >= 0)
2684 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2685 offset = nextOffset;
2686 }
2687
2688 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2689 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2690
2691 // built-in variable decorations
2692 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002693 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002694 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002695
2696#ifdef NV_EXTENSIONS
2697 if (builtIn == spv::BuiltInLayer) {
2698 // SPV_NV_viewport_array2 extension
2699 if (glslangMember.getQualifier().layoutViewportRelative){
2700 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2701 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2702 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2703 }
2704 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2705 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2706 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2707 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2708 }
2709 }
chaocdf3956c2017-02-14 14:52:34 -08002710 if (glslangMember.getQualifier().layoutPassthrough) {
2711 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2712 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2713 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2714 }
chaoc771d89f2017-01-13 01:10:53 -08002715#endif
John Kessenich6090df02016-06-30 21:18:02 -06002716 }
2717 }
2718
2719 // Decorate the structure
2720 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002721 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002722 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2723 builder.addCapability(spv::CapabilityGeometryStreams);
2724 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2725 }
John Kessenich6090df02016-06-30 21:18:02 -06002726}
2727
John Kessenich6c292d32016-02-15 20:58:50 -07002728// Turn the expression forming the array size into an id.
2729// This is not quite trivial, because of specialization constants.
2730// Sometimes, a raw constant is turned into an Id, and sometimes
2731// a specialization constant expression is.
2732spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2733{
2734 // First, see if this is sized with a node, meaning a specialization constant:
2735 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2736 if (specNode != nullptr) {
2737 builder.clearAccessChain();
2738 specNode->traverse(this);
2739 return accessChainLoad(specNode->getAsTyped()->getType());
2740 }
qining25262b32016-05-06 17:25:16 -04002741
John Kessenich6c292d32016-02-15 20:58:50 -07002742 // Otherwise, need a compile-time (front end) size, get it:
2743 int size = arraySizes.getDimSize(dim);
2744 assert(size > 0);
2745 return builder.makeUintConstant(size);
2746}
2747
John Kessenich103bef92016-02-08 21:38:15 -07002748// Wrap the builder's accessChainLoad to:
2749// - localize handling of RelaxedPrecision
2750// - use the SPIR-V inferred type instead of another conversion of the glslang type
2751// (avoids unnecessary work and possible type punning for structures)
2752// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002753spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2754{
John Kessenich103bef92016-02-08 21:38:15 -07002755 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2756 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2757
2758 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002759 if (type.getBasicType() == glslang::EbtBool) {
2760 if (builder.isScalarType(nominalTypeId)) {
2761 // Conversion for bool
2762 spv::Id boolType = builder.makeBoolType();
2763 if (nominalTypeId != boolType)
2764 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2765 } else if (builder.isVectorType(nominalTypeId)) {
2766 // Conversion for bvec
2767 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2768 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2769 if (nominalTypeId != bvecType)
2770 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2771 }
2772 }
John Kessenich103bef92016-02-08 21:38:15 -07002773
2774 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002775}
2776
Rex Xu27253232016-02-23 17:51:09 +08002777// Wrap the builder's accessChainStore to:
2778// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002779//
2780// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002781void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2782{
2783 // Need to convert to abstract types when necessary
2784 if (type.getBasicType() == glslang::EbtBool) {
2785 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2786
2787 if (builder.isScalarType(nominalTypeId)) {
2788 // Conversion for bool
2789 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002790 if (nominalTypeId != boolType) {
2791 // keep these outside arguments, for determinant order-of-evaluation
2792 spv::Id one = builder.makeUintConstant(1);
2793 spv::Id zero = builder.makeUintConstant(0);
2794 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2795 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002796 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002797 } else if (builder.isVectorType(nominalTypeId)) {
2798 // Conversion for bvec
2799 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2800 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002801 if (nominalTypeId != bvecType) {
2802 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002803 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2804 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2805 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002806 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002807 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2808 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002809 }
2810 }
2811
2812 builder.accessChainStore(rvalue);
2813}
2814
John Kessenich4bf71552016-09-02 11:20:21 -06002815// For storing when types match at the glslang level, but not might match at the
2816// SPIR-V level.
2817//
2818// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002819// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002820// as in a member-decorated way.
2821//
2822// NOTE: This function can handle any store request; if it's not special it
2823// simplifies to a simple OpStore.
2824//
2825// Implicitly uses the existing builder.accessChain as the storage target.
2826void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2827{
John Kessenichb3e24e42016-09-11 12:33:43 -06002828 // we only do the complex path here if it's an aggregate
2829 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002830 accessChainStore(type, rValue);
2831 return;
2832 }
2833
John Kessenichb3e24e42016-09-11 12:33:43 -06002834 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002835 spv::Id rType = builder.getTypeId(rValue);
2836 spv::Id lValue = builder.accessChainGetLValue();
2837 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2838 if (lType == rType) {
2839 accessChainStore(type, rValue);
2840 return;
2841 }
2842
John Kessenichb3e24e42016-09-11 12:33:43 -06002843 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002844 // where the two types were the same type in GLSL. This requires member
2845 // by member copy, recursively.
2846
John Kessenichb3e24e42016-09-11 12:33:43 -06002847 // If an array, copy element by element.
2848 if (type.isArray()) {
2849 glslang::TType glslangElementType(type, 0);
2850 spv::Id elementRType = builder.getContainedTypeId(rType);
2851 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2852 // get the source member
2853 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002854
John Kessenichb3e24e42016-09-11 12:33:43 -06002855 // set up the target storage
2856 builder.clearAccessChain();
2857 builder.setAccessChainLValue(lValue);
2858 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002859
John Kessenichb3e24e42016-09-11 12:33:43 -06002860 // store the member
2861 multiTypeStore(glslangElementType, elementRValue);
2862 }
2863 } else {
2864 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002865
John Kessenichb3e24e42016-09-11 12:33:43 -06002866 // loop over structure members
2867 const glslang::TTypeList& members = *type.getStruct();
2868 for (int m = 0; m < (int)members.size(); ++m) {
2869 const glslang::TType& glslangMemberType = *members[m].type;
2870
2871 // get the source member
2872 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2873 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2874
2875 // set up the target storage
2876 builder.clearAccessChain();
2877 builder.setAccessChainLValue(lValue);
2878 builder.accessChainPush(builder.makeIntConstant(m));
2879
2880 // store the member
2881 multiTypeStore(glslangMemberType, memberRValue);
2882 }
John Kessenich4bf71552016-09-02 11:20:21 -06002883 }
2884}
2885
John Kessenichf85e8062015-12-19 13:57:10 -07002886// Decide whether or not this type should be
2887// decorated with offsets and strides, and if so
2888// whether std140 or std430 rules should be applied.
2889glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002890{
John Kessenichf85e8062015-12-19 13:57:10 -07002891 // has to be a block
2892 if (type.getBasicType() != glslang::EbtBlock)
2893 return glslang::ElpNone;
2894
2895 // has to be a uniform or buffer block
2896 if (type.getQualifier().storage != glslang::EvqUniform &&
2897 type.getQualifier().storage != glslang::EvqBuffer)
2898 return glslang::ElpNone;
2899
2900 // return the layout to use
2901 switch (type.getQualifier().layoutPacking) {
2902 case glslang::ElpStd140:
2903 case glslang::ElpStd430:
2904 return type.getQualifier().layoutPacking;
2905 default:
2906 return glslang::ElpNone;
2907 }
John Kessenich31ed4832015-09-09 17:51:38 -06002908}
2909
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002910// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002911int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002912{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002913 int size;
John Kessenich49987892015-12-29 17:11:44 -07002914 int stride;
2915 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002916
2917 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002918}
2919
John Kessenich49987892015-12-29 17:11:44 -07002920// 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 -07002921// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002922int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002923{
John Kessenich49987892015-12-29 17:11:44 -07002924 glslang::TType elementType;
2925 elementType.shallowCopy(matrixType);
2926 elementType.clearArraySizes();
2927
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002928 int size;
John Kessenich49987892015-12-29 17:11:44 -07002929 int stride;
2930 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2931
2932 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002933}
2934
John Kessenich5e4b1242015-08-06 22:53:06 -06002935// Given a member type of a struct, realign the current offset for it, and compute
2936// the next (not yet aligned) offset for the next member, which will get aligned
2937// on the next call.
2938// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2939// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2940// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002941void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002942 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002943{
2944 // this will get a positive value when deemed necessary
2945 nextOffset = -1;
2946
John Kessenich5e4b1242015-08-06 22:53:06 -06002947 // override anything in currentOffset with user-set offset
2948 if (memberType.getQualifier().hasOffset())
2949 currentOffset = memberType.getQualifier().layoutOffset;
2950
2951 // It could be that current linker usage in glslang updated all the layoutOffset,
2952 // in which case the following code does not matter. But, that's not quite right
2953 // once cross-compilation unit GLSL validation is done, as the original user
2954 // settings are needed in layoutOffset, and then the following will come into play.
2955
John Kessenichf85e8062015-12-19 13:57:10 -07002956 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002957 if (! memberType.getQualifier().hasOffset())
2958 currentOffset = -1;
2959
2960 return;
2961 }
2962
John Kessenichf85e8062015-12-19 13:57:10 -07002963 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002964 if (currentOffset < 0)
2965 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002966
John Kessenich5e4b1242015-08-06 22:53:06 -06002967 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2968 // but possibly not yet correctly aligned.
2969
2970 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002971 int dummyStride;
2972 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002973
2974 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002975 // TODO: make this consistent in early phases of code:
2976 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2977 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2978 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002979 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002980 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002981 int dummySize;
2982 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2983 if (componentAlignment <= 4)
2984 memberAlignment = componentAlignment;
2985 }
2986
2987 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002989
2990 // Bump up to vec4 if there is a bad straddle
2991 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2992 glslang::RoundToPow2(currentOffset, 16);
2993
John Kessenich5e4b1242015-08-06 22:53:06 -06002994 nextOffset = currentOffset + memberSize;
2995}
2996
David Netoa901ffe2016-06-08 14:11:40 +01002997void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002998{
David Netoa901ffe2016-06-08 14:11:40 +01002999 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3000 switch (glslangBuiltIn)
3001 {
3002 case glslang::EbvClipDistance:
3003 case glslang::EbvCullDistance:
3004 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003005#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003006 case glslang::EbvViewportMaskNV:
3007 case glslang::EbvSecondaryPositionNV:
3008 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003009 case glslang::EbvPositionPerViewNV:
3010 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003011#endif
David Netoa901ffe2016-06-08 14:11:40 +01003012 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3013 // Alternately, we could just call this for any glslang built-in, since the
3014 // capability already guards against duplicates.
3015 TranslateBuiltInDecoration(glslangBuiltIn, false);
3016 break;
3017 default:
3018 // Capabilities were already generated when the struct was declared.
3019 break;
3020 }
John Kessenichebb50532016-05-16 19:22:05 -06003021}
3022
John Kessenich6fccb3c2016-09-19 16:01:41 -06003023bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003024{
John Kessenicheee9d532016-09-19 18:09:30 -06003025 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003026}
3027
John Kessenichd41993d2017-09-10 15:21:05 -06003028// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003029// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3030// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003031bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3032{
John Kessenich6a14f782017-12-04 02:48:10 -07003033 assert(qualifier == glslang::EvqIn ||
3034 qualifier == glslang::EvqOut ||
3035 qualifier == glslang::EvqInOut ||
3036 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003037 return qualifier != glslang::EvqConstReadOnly;
3038}
3039
3040// Is parameter pass-by-original?
3041bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3042 bool implicitThisParam)
3043{
3044 if (implicitThisParam) // implicit this
3045 return true;
3046 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003047 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003048 return paramType.containsOpaque() || // sampler, etc.
3049 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3050}
3051
John Kessenich140f3df2015-06-26 16:58:36 -06003052// Make all the functions, skeletally, without actually visiting their bodies.
3053void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3054{
John Kessenichfad62972017-07-18 02:35:46 -06003055 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3056 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3057 if (paramPrecision != spv::NoPrecision)
3058 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003059 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003060 };
3061
John Kessenich140f3df2015-06-26 16:58:36 -06003062 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3063 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003064 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003065 continue;
3066
3067 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003068 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003069 //
qining25262b32016-05-06 17:25:16 -04003070 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003071 // function. What it is an address of varies:
3072 //
John Kessenich4bf71552016-09-02 11:20:21 -06003073 // - "in" parameters not marked as "const" can be written to without modifying the calling
3074 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003075 //
3076 // - "const in" parameters can just be the r-value, as no writes need occur.
3077 //
John Kessenich4bf71552016-09-02 11:20:21 -06003078 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3079 // 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 -06003080
3081 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003082 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003083 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3084
John Kessenichfad62972017-07-18 02:35:46 -06003085 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3086 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003087
John Kessenichfad62972017-07-18 02:35:46 -06003088 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003089 for (int p = 0; p < (int)parameters.size(); ++p) {
3090 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3091 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003092 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003093 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003094 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003095 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3096 else
John Kessenich4bf71552016-09-02 11:20:21 -06003097 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003098 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003099 paramTypes.push_back(typeId);
3100 }
3101
3102 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003103 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3104 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003105 glslFunction->getName().c_str(), paramTypes,
3106 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003107 if (implicitThis)
3108 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003109
3110 // Track function to emit/call later
3111 functionMap[glslFunction->getName().c_str()] = function;
3112
3113 // Set the parameter id's
3114 for (int p = 0; p < (int)parameters.size(); ++p) {
3115 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3116 // give a name too
3117 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3118 }
3119 }
3120}
3121
3122// Process all the initializers, while skipping the functions and link objects
3123void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3124{
3125 builder.setBuildPoint(shaderEntry->getLastBlock());
3126 for (int i = 0; i < (int)initializers.size(); ++i) {
3127 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3128 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3129
3130 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003131 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003132 initializer->traverse(this);
3133 }
3134 }
3135}
3136
3137// Process all the functions, while skipping initializers.
3138void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3139{
3140 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3141 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003142 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003143 node->traverse(this);
3144 }
3145}
3146
3147void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3148{
qining25262b32016-05-06 17:25:16 -04003149 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003150 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003151 currentFunction = functionMap[node->getName().c_str()];
3152 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003153 builder.setBuildPoint(functionBlock);
3154}
3155
Rex Xu04db3f52015-09-16 11:44:02 +08003156void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003157{
Rex Xufc618912015-09-09 16:42:49 +08003158 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003159
3160 glslang::TSampler sampler = {};
3161 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003162 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003163 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3164 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3165 }
3166
John Kessenich140f3df2015-06-26 16:58:36 -06003167 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3168 builder.clearAccessChain();
3169 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003170
3171 // Special case l-value operands
3172 bool lvalue = false;
3173 switch (node.getOp()) {
3174 case glslang::EOpImageAtomicAdd:
3175 case glslang::EOpImageAtomicMin:
3176 case glslang::EOpImageAtomicMax:
3177 case glslang::EOpImageAtomicAnd:
3178 case glslang::EOpImageAtomicOr:
3179 case glslang::EOpImageAtomicXor:
3180 case glslang::EOpImageAtomicExchange:
3181 case glslang::EOpImageAtomicCompSwap:
3182 if (i == 0)
3183 lvalue = true;
3184 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003185 case glslang::EOpSparseImageLoad:
3186 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3187 lvalue = true;
3188 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003189 case glslang::EOpSparseTexture:
3190 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3191 lvalue = true;
3192 break;
3193 case glslang::EOpSparseTextureClamp:
3194 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3195 lvalue = true;
3196 break;
3197 case glslang::EOpSparseTextureLod:
3198 case glslang::EOpSparseTextureOffset:
3199 if (i == 3)
3200 lvalue = true;
3201 break;
3202 case glslang::EOpSparseTextureFetch:
3203 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3204 lvalue = true;
3205 break;
3206 case glslang::EOpSparseTextureFetchOffset:
3207 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3208 lvalue = true;
3209 break;
3210 case glslang::EOpSparseTextureLodOffset:
3211 case glslang::EOpSparseTextureGrad:
3212 case glslang::EOpSparseTextureOffsetClamp:
3213 if (i == 4)
3214 lvalue = true;
3215 break;
3216 case glslang::EOpSparseTextureGradOffset:
3217 case glslang::EOpSparseTextureGradClamp:
3218 if (i == 5)
3219 lvalue = true;
3220 break;
3221 case glslang::EOpSparseTextureGradOffsetClamp:
3222 if (i == 6)
3223 lvalue = true;
3224 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003225 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003226 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3227 lvalue = true;
3228 break;
3229 case glslang::EOpSparseTextureGatherOffset:
3230 case glslang::EOpSparseTextureGatherOffsets:
3231 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3232 lvalue = true;
3233 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003234#ifdef AMD_EXTENSIONS
3235 case glslang::EOpSparseTextureGatherLod:
3236 if (i == 3)
3237 lvalue = true;
3238 break;
3239 case glslang::EOpSparseTextureGatherLodOffset:
3240 case glslang::EOpSparseTextureGatherLodOffsets:
3241 if (i == 4)
3242 lvalue = true;
3243 break;
Rex Xu129799a2017-07-05 17:23:28 +08003244 case glslang::EOpSparseImageLoadLod:
3245 if (i == 3)
3246 lvalue = true;
3247 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003248#endif
Rex Xufc618912015-09-09 16:42:49 +08003249 default:
3250 break;
3251 }
3252
Rex Xu6b86d492015-09-16 17:48:22 +08003253 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003254 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003255 else
John Kessenich32cfd492016-02-02 12:37:46 -07003256 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003257 }
3258}
3259
John Kessenichfc51d282015-08-19 13:34:18 -06003260void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003261{
John Kessenichfc51d282015-08-19 13:34:18 -06003262 builder.clearAccessChain();
3263 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003264 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003265}
John Kessenich140f3df2015-06-26 16:58:36 -06003266
John Kessenichfc51d282015-08-19 13:34:18 -06003267spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3268{
John Kesseniche485c7a2017-05-31 18:50:53 -06003269 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003270 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003271
3272 builder.setLine(node->getLoc().line);
3273
John Kessenichfc51d282015-08-19 13:34:18 -06003274 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003275 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3276 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3277 std::vector<spv::Id> arguments;
3278 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003279 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003280 else
3281 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003282 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003283
3284 spv::Builder::TextureParameters params = { };
3285 params.sampler = arguments[0];
3286
Rex Xu04db3f52015-09-16 11:44:02 +08003287 glslang::TCrackedTextureOp cracked;
3288 node->crackTexture(sampler, cracked);
3289
amhagan05506bb2017-06-13 16:53:02 -04003290 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003291
John Kessenichfc51d282015-08-19 13:34:18 -06003292 // Check for queries
3293 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003294 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3295 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003296 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003297
John Kessenichfc51d282015-08-19 13:34:18 -06003298 switch (node->getOp()) {
3299 case glslang::EOpImageQuerySize:
3300 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003301 if (arguments.size() > 1) {
3302 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003303 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003304 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003305 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003306 case glslang::EOpImageQuerySamples:
3307 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003308 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003309 case glslang::EOpTextureQueryLod:
3310 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003311 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003312 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003313 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003314 case glslang::EOpSparseTexelsResident:
3315 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003316 default:
3317 assert(0);
3318 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003319 }
John Kessenich140f3df2015-06-26 16:58:36 -06003320 }
3321
LoopDawg4425f242018-02-18 11:40:01 -07003322 int components = node->getType().getVectorSize();
3323
3324 if (node->getOp() == glslang::EOpTextureFetch) {
3325 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3326 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3327 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3328 // here around e.g. which ones return scalars or other types.
3329 components = 4;
3330 }
3331
3332 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3333
3334 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3335
Rex Xufc618912015-09-09 16:42:49 +08003336 // Check for image functions other than queries
3337 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003338 std::vector<spv::Id> operands;
3339 auto opIt = arguments.begin();
3340 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003341
3342 // Handle subpass operations
3343 // TODO: GLSL should change to have the "MS" only on the type rather than the
3344 // built-in function.
3345 if (cracked.subpass) {
3346 // add on the (0,0) coordinate
3347 spv::Id zero = builder.makeIntConstant(0);
3348 std::vector<spv::Id> comps;
3349 comps.push_back(zero);
3350 comps.push_back(zero);
3351 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3352 if (sampler.ms) {
3353 operands.push_back(spv::ImageOperandsSampleMask);
3354 operands.push_back(*(opIt++));
3355 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003356 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3357 builder.setPrecision(result, precision);
3358 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003359 }
3360
John Kessenich56bab042015-09-16 10:54:31 -06003361 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003362#ifdef AMD_EXTENSIONS
3363 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3364#else
John Kessenich56bab042015-09-16 10:54:31 -06003365 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003366#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003367 if (sampler.ms) {
3368 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003369 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003370#ifdef AMD_EXTENSIONS
3371 } else if (cracked.lod) {
3372 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3373 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3374
3375 operands.push_back(spv::ImageOperandsLodMask);
3376 operands.push_back(*opIt);
3377#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003378 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003379 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3380 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003381
LoopDawg4425f242018-02-18 11:40:01 -07003382 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3383 builder.setPrecision(result[0], precision);
3384
3385 // If needed, add a conversion constructor to the proper size.
3386 if (components != node->getType().getVectorSize())
3387 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3388
3389 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003390#ifdef AMD_EXTENSIONS
3391 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3392#else
John Kessenich56bab042015-09-16 10:54:31 -06003393 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003394#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003395 if (sampler.ms) {
3396 operands.push_back(*(opIt + 1));
3397 operands.push_back(spv::ImageOperandsSampleMask);
3398 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003399#ifdef AMD_EXTENSIONS
3400 } else if (cracked.lod) {
3401 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3402 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3403
3404 operands.push_back(*(opIt + 1));
3405 operands.push_back(spv::ImageOperandsLodMask);
3406 operands.push_back(*opIt);
3407#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003408 } else
3409 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003410 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003411 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3412 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003413 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003414#ifdef AMD_EXTENSIONS
3415 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3416#else
Rex Xu5eafa472016-02-19 22:24:03 +08003417 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003418#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003419 builder.addCapability(spv::CapabilitySparseResidency);
3420 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3421 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3422
3423 if (sampler.ms) {
3424 operands.push_back(spv::ImageOperandsSampleMask);
3425 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003426#ifdef AMD_EXTENSIONS
3427 } else if (cracked.lod) {
3428 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3429 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3430
3431 operands.push_back(spv::ImageOperandsLodMask);
3432 operands.push_back(*opIt++);
3433#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003434 }
3435
3436 // Create the return type that was a special structure
3437 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003438 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003439 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3440 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3441
3442 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3443
3444 // Decode the return type
3445 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3446 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003447 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003448 // Process image atomic operations
3449
3450 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3451 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003452 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003453
John Kessenich8c8505c2016-07-26 12:50:38 -06003454 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003455 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003456
3457 std::vector<spv::Id> operands;
3458 operands.push_back(pointer);
3459 for (; opIt != arguments.end(); ++opIt)
3460 operands.push_back(*opIt);
3461
John Kessenich8c8505c2016-07-26 12:50:38 -06003462 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003463 }
3464 }
3465
amhagan05506bb2017-06-13 16:53:02 -04003466#ifdef AMD_EXTENSIONS
3467 // Check for fragment mask functions other than queries
3468 if (cracked.fragMask) {
3469 assert(sampler.ms);
3470
3471 auto opIt = arguments.begin();
3472 std::vector<spv::Id> operands;
3473
3474 // Extract the image if necessary
3475 if (builder.isSampledImage(params.sampler))
3476 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3477
3478 operands.push_back(params.sampler);
3479 ++opIt;
3480
3481 if (sampler.isSubpass()) {
3482 // add on the (0,0) coordinate
3483 spv::Id zero = builder.makeIntConstant(0);
3484 std::vector<spv::Id> comps;
3485 comps.push_back(zero);
3486 comps.push_back(zero);
3487 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3488 }
3489
3490 for (; opIt != arguments.end(); ++opIt)
3491 operands.push_back(*opIt);
3492
3493 spv::Op fragMaskOp = spv::OpNop;
3494 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3495 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3496 else if (node->getOp() == glslang::EOpFragmentFetch)
3497 fragMaskOp = spv::OpFragmentFetchAMD;
3498
3499 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3500 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3501 return builder.createOp(fragMaskOp, resultType(), operands);
3502 }
3503#endif
3504
Rex Xufc618912015-09-09 16:42:49 +08003505 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003506 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003507 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3508
John Kessenichfc51d282015-08-19 13:34:18 -06003509 // check for bias argument
3510 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003511#ifdef AMD_EXTENSIONS
3512 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3513#else
Rex Xu71519fe2015-11-11 15:35:47 +08003514 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003515#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003516 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003517#ifdef AMD_EXTENSIONS
3518 if (cracked.gather)
3519 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3520#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003521 if (cracked.offset)
3522 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003523#ifdef AMD_EXTENSIONS
3524 else if (cracked.offsets)
3525 ++nonBiasArgCount;
3526#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003527 if (cracked.grad)
3528 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003529 if (cracked.lodClamp)
3530 ++nonBiasArgCount;
3531 if (sparse)
3532 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003533
3534 if ((int)arguments.size() > nonBiasArgCount)
3535 bias = true;
3536 }
3537
John Kessenicha5c33d62016-06-02 23:45:21 -06003538 // See if the sampler param should really be just the SPV image part
3539 if (cracked.fetch) {
3540 // a fetch needs to have the image extracted first
3541 if (builder.isSampledImage(params.sampler))
3542 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3543 }
3544
Rex Xu225e0fc2016-11-17 17:47:59 +08003545#ifdef AMD_EXTENSIONS
3546 if (cracked.gather) {
3547 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3548 if (bias || cracked.lod ||
3549 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3550 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003551 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003552 }
3553 }
3554#endif
3555
John Kessenichfc51d282015-08-19 13:34:18 -06003556 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003557
John Kessenichfc51d282015-08-19 13:34:18 -06003558 params.coords = arguments[1];
3559 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003560 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003561
3562 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003563 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003564 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003565 ++extraArgs;
3566 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003567 params.Dref = arguments[2];
3568 ++extraArgs;
3569 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003570 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003571 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003572 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003573 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003574 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003575 dRefComp = builder.getNumComponents(params.coords) - 1;
3576 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003577 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3578 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003579
3580 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003581 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003582 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003583 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003584 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3585 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3586 noImplicitLod = true;
3587 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003588
3589 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003590 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003591 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003592 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003593 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003594
3595 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003596 if (cracked.grad) {
3597 params.gradX = arguments[2 + extraArgs];
3598 params.gradY = arguments[3 + extraArgs];
3599 extraArgs += 2;
3600 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003601
3602 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003603 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003604 params.offset = arguments[2 + extraArgs];
3605 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003606 } else if (cracked.offsets) {
3607 params.offsets = arguments[2 + extraArgs];
3608 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003609 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003610
3611 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003612 if (cracked.lodClamp) {
3613 params.lodClamp = arguments[2 + extraArgs];
3614 ++extraArgs;
3615 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003616
3617 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003618 if (sparse) {
3619 params.texelOut = arguments[2 + extraArgs];
3620 ++extraArgs;
3621 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003622
John Kessenich76d4dfc2016-06-16 12:43:23 -06003623 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003624 if (cracked.gather && ! sampler.shadow) {
3625 // default component is 0, if missing, otherwise an argument
3626 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003627 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003628 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003629 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003630 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003631 }
3632
3633 // bias
3634 if (bias) {
3635 params.bias = arguments[2 + extraArgs];
3636 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003637 }
John Kessenichfc51d282015-08-19 13:34:18 -06003638
John Kessenich65336482016-06-16 14:06:26 -06003639 // projective component (might not to move)
3640 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3641 // are divided by the last component of P."
3642 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3643 // unused components will appear after all used components."
3644 if (cracked.proj) {
3645 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3646 int projTargetComp;
3647 switch (sampler.dim) {
3648 case glslang::Esd1D: projTargetComp = 1; break;
3649 case glslang::Esd2D: projTargetComp = 2; break;
3650 case glslang::EsdRect: projTargetComp = 2; break;
3651 default: projTargetComp = projSourceComp; break;
3652 }
3653 // copy the projective coordinate if we have to
3654 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003655 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003656 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3657 projSourceComp);
3658 params.coords = builder.createCompositeInsert(projComp, params.coords,
3659 builder.getTypeId(params.coords), projTargetComp);
3660 }
3661 }
3662
LoopDawg4425f242018-02-18 11:40:01 -07003663 std::vector<spv::Id> result = {
3664 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3665 };
3666
3667 if (components != node->getType().getVectorSize())
3668 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3669
3670 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003671}
3672
3673spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3674{
3675 // Grab the function's pointer from the previously created function
3676 spv::Function* function = functionMap[node->getName().c_str()];
3677 if (! function)
3678 return 0;
3679
3680 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3681 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3682
3683 // See comments in makeFunctions() for details about the semantics for parameter passing.
3684 //
3685 // These imply we need a four step process:
3686 // 1. Evaluate the arguments
3687 // 2. Allocate and make copies of in, out, and inout arguments
3688 // 3. Make the call
3689 // 4. Copy back the results
3690
3691 // 1. Evaluate the arguments
3692 std::vector<spv::Builder::AccessChain> lValues;
3693 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003694 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003696 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003697 // build l-value
3698 builder.clearAccessChain();
3699 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003700 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003701 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003702 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3703 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003704 // save l-value
3705 lValues.push_back(builder.getAccessChain());
3706 } else {
3707 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003708 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003709 }
3710 }
3711
3712 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3713 // copy the original into that space.
3714 //
3715 // Also, build up the list of actual arguments to pass in for the call
3716 int lValueCount = 0;
3717 int rValueCount = 0;
3718 std::vector<spv::Id> spvArgs;
3719 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003720 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003721 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003722 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003723 builder.setAccessChain(lValues[lValueCount]);
3724 arg = builder.accessChainGetLValue();
3725 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003726 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003727 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003728 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3729 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3730 // need to copy the input into output space
3731 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003732 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003733 builder.clearAccessChain();
3734 builder.setAccessChainLValue(arg);
3735 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003736 }
3737 ++lValueCount;
3738 } else {
3739 arg = rValues[rValueCount];
3740 ++rValueCount;
3741 }
3742 spvArgs.push_back(arg);
3743 }
3744
3745 // 3. Make the call.
3746 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003747 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003748
3749 // 4. Copy back out an "out" arguments.
3750 lValueCount = 0;
3751 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003752 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003753 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3754 ++lValueCount;
3755 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003756 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3757 spv::Id copy = builder.createLoad(spvArgs[a]);
3758 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003759 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003760 }
3761 ++lValueCount;
3762 }
3763 }
3764
3765 return result;
3766}
3767
3768// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003769spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3770 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003771 spv::Id typeId, spv::Id left, spv::Id right,
3772 glslang::TBasicType typeProxy, bool reduceComparison)
3773{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003774#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003775 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003776 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3777#else
Rex Xucabbb782017-03-24 13:41:14 +08003778 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003779 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003780#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003781 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003782
3783 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003784 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003785 bool comparison = false;
3786
3787 switch (op) {
3788 case glslang::EOpAdd:
3789 case glslang::EOpAddAssign:
3790 if (isFloat)
3791 binOp = spv::OpFAdd;
3792 else
3793 binOp = spv::OpIAdd;
3794 break;
3795 case glslang::EOpSub:
3796 case glslang::EOpSubAssign:
3797 if (isFloat)
3798 binOp = spv::OpFSub;
3799 else
3800 binOp = spv::OpISub;
3801 break;
3802 case glslang::EOpMul:
3803 case glslang::EOpMulAssign:
3804 if (isFloat)
3805 binOp = spv::OpFMul;
3806 else
3807 binOp = spv::OpIMul;
3808 break;
3809 case glslang::EOpVectorTimesScalar:
3810 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003811 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003812 if (builder.isVector(right))
3813 std::swap(left, right);
3814 assert(builder.isScalar(right));
3815 needMatchingVectors = false;
3816 binOp = spv::OpVectorTimesScalar;
3817 } else
3818 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 case glslang::EOpVectorTimesMatrix:
3821 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003822 binOp = spv::OpVectorTimesMatrix;
3823 break;
3824 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003825 binOp = spv::OpMatrixTimesVector;
3826 break;
3827 case glslang::EOpMatrixTimesScalar:
3828 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003829 binOp = spv::OpMatrixTimesScalar;
3830 break;
3831 case glslang::EOpMatrixTimesMatrix:
3832 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003833 binOp = spv::OpMatrixTimesMatrix;
3834 break;
3835 case glslang::EOpOuterProduct:
3836 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003837 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839
3840 case glslang::EOpDiv:
3841 case glslang::EOpDivAssign:
3842 if (isFloat)
3843 binOp = spv::OpFDiv;
3844 else if (isUnsigned)
3845 binOp = spv::OpUDiv;
3846 else
3847 binOp = spv::OpSDiv;
3848 break;
3849 case glslang::EOpMod:
3850 case glslang::EOpModAssign:
3851 if (isFloat)
3852 binOp = spv::OpFMod;
3853 else if (isUnsigned)
3854 binOp = spv::OpUMod;
3855 else
3856 binOp = spv::OpSMod;
3857 break;
3858 case glslang::EOpRightShift:
3859 case glslang::EOpRightShiftAssign:
3860 if (isUnsigned)
3861 binOp = spv::OpShiftRightLogical;
3862 else
3863 binOp = spv::OpShiftRightArithmetic;
3864 break;
3865 case glslang::EOpLeftShift:
3866 case glslang::EOpLeftShiftAssign:
3867 binOp = spv::OpShiftLeftLogical;
3868 break;
3869 case glslang::EOpAnd:
3870 case glslang::EOpAndAssign:
3871 binOp = spv::OpBitwiseAnd;
3872 break;
3873 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003874 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003875 binOp = spv::OpLogicalAnd;
3876 break;
3877 case glslang::EOpInclusiveOr:
3878 case glslang::EOpInclusiveOrAssign:
3879 binOp = spv::OpBitwiseOr;
3880 break;
3881 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003882 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003883 binOp = spv::OpLogicalOr;
3884 break;
3885 case glslang::EOpExclusiveOr:
3886 case glslang::EOpExclusiveOrAssign:
3887 binOp = spv::OpBitwiseXor;
3888 break;
3889 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003890 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003891 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003892 break;
3893
3894 case glslang::EOpLessThan:
3895 case glslang::EOpGreaterThan:
3896 case glslang::EOpLessThanEqual:
3897 case glslang::EOpGreaterThanEqual:
3898 case glslang::EOpEqual:
3899 case glslang::EOpNotEqual:
3900 case glslang::EOpVectorEqual:
3901 case glslang::EOpVectorNotEqual:
3902 comparison = true;
3903 break;
3904 default:
3905 break;
3906 }
3907
John Kessenich7c1aa102015-10-15 13:29:11 -06003908 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003909 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003910 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003911 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003912 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003913
3914 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003915 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003916 builder.promoteScalar(precision, left, right);
3917
qining25262b32016-05-06 17:25:16 -04003918 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3919 addDecoration(result, noContraction);
3920 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003921 }
3922
3923 if (! comparison)
3924 return 0;
3925
John Kessenich7c1aa102015-10-15 13:29:11 -06003926 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003927
John Kessenich4583b612016-08-07 19:14:22 -06003928 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3929 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003930 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003931
3932 switch (op) {
3933 case glslang::EOpLessThan:
3934 if (isFloat)
3935 binOp = spv::OpFOrdLessThan;
3936 else if (isUnsigned)
3937 binOp = spv::OpULessThan;
3938 else
3939 binOp = spv::OpSLessThan;
3940 break;
3941 case glslang::EOpGreaterThan:
3942 if (isFloat)
3943 binOp = spv::OpFOrdGreaterThan;
3944 else if (isUnsigned)
3945 binOp = spv::OpUGreaterThan;
3946 else
3947 binOp = spv::OpSGreaterThan;
3948 break;
3949 case glslang::EOpLessThanEqual:
3950 if (isFloat)
3951 binOp = spv::OpFOrdLessThanEqual;
3952 else if (isUnsigned)
3953 binOp = spv::OpULessThanEqual;
3954 else
3955 binOp = spv::OpSLessThanEqual;
3956 break;
3957 case glslang::EOpGreaterThanEqual:
3958 if (isFloat)
3959 binOp = spv::OpFOrdGreaterThanEqual;
3960 else if (isUnsigned)
3961 binOp = spv::OpUGreaterThanEqual;
3962 else
3963 binOp = spv::OpSGreaterThanEqual;
3964 break;
3965 case glslang::EOpEqual:
3966 case glslang::EOpVectorEqual:
3967 if (isFloat)
3968 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003969 else if (isBool)
3970 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003971 else
3972 binOp = spv::OpIEqual;
3973 break;
3974 case glslang::EOpNotEqual:
3975 case glslang::EOpVectorNotEqual:
3976 if (isFloat)
3977 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003978 else if (isBool)
3979 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003980 else
3981 binOp = spv::OpINotEqual;
3982 break;
3983 default:
3984 break;
3985 }
3986
qining25262b32016-05-06 17:25:16 -04003987 if (binOp != spv::OpNop) {
3988 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3989 addDecoration(result, noContraction);
3990 return builder.setPrecision(result, precision);
3991 }
John Kessenich140f3df2015-06-26 16:58:36 -06003992
3993 return 0;
3994}
3995
John Kessenich04bb8a02015-12-12 12:28:14 -07003996//
3997// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3998// These can be any of:
3999//
4000// matrix * scalar
4001// scalar * matrix
4002// matrix * matrix linear algebraic
4003// matrix * vector
4004// vector * matrix
4005// matrix * matrix componentwise
4006// matrix op matrix op in {+, -, /}
4007// matrix op scalar op in {+, -, /}
4008// scalar op matrix op in {+, -, /}
4009//
qining25262b32016-05-06 17:25:16 -04004010spv::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 -07004011{
4012 bool firstClass = true;
4013
4014 // First, handle first-class matrix operations (* and matrix/scalar)
4015 switch (op) {
4016 case spv::OpFDiv:
4017 if (builder.isMatrix(left) && builder.isScalar(right)) {
4018 // turn matrix / scalar into a multiply...
4019 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
4020 op = spv::OpMatrixTimesScalar;
4021 } else
4022 firstClass = false;
4023 break;
4024 case spv::OpMatrixTimesScalar:
4025 if (builder.isMatrix(right))
4026 std::swap(left, right);
4027 assert(builder.isScalar(right));
4028 break;
4029 case spv::OpVectorTimesMatrix:
4030 assert(builder.isVector(left));
4031 assert(builder.isMatrix(right));
4032 break;
4033 case spv::OpMatrixTimesVector:
4034 assert(builder.isMatrix(left));
4035 assert(builder.isVector(right));
4036 break;
4037 case spv::OpMatrixTimesMatrix:
4038 assert(builder.isMatrix(left));
4039 assert(builder.isMatrix(right));
4040 break;
4041 default:
4042 firstClass = false;
4043 break;
4044 }
4045
qining25262b32016-05-06 17:25:16 -04004046 if (firstClass) {
4047 spv::Id result = builder.createBinOp(op, typeId, left, right);
4048 addDecoration(result, noContraction);
4049 return builder.setPrecision(result, precision);
4050 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004051
LoopDawg592860c2016-06-09 08:57:35 -06004052 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004053 // The result type of all of them is the same type as the (a) matrix operand.
4054 // The algorithm is to:
4055 // - break the matrix(es) into vectors
4056 // - smear any scalar to a vector
4057 // - do vector operations
4058 // - make a matrix out the vector results
4059 switch (op) {
4060 case spv::OpFAdd:
4061 case spv::OpFSub:
4062 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004063 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004064 case spv::OpFMul:
4065 {
4066 // one time set up...
4067 bool leftMat = builder.isMatrix(left);
4068 bool rightMat = builder.isMatrix(right);
4069 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4070 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4071 spv::Id scalarType = builder.getScalarTypeId(typeId);
4072 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4073 std::vector<spv::Id> results;
4074 spv::Id smearVec = spv::NoResult;
4075 if (builder.isScalar(left))
4076 smearVec = builder.smearScalar(precision, left, vecType);
4077 else if (builder.isScalar(right))
4078 smearVec = builder.smearScalar(precision, right, vecType);
4079
4080 // do each vector op
4081 for (unsigned int c = 0; c < numCols; ++c) {
4082 std::vector<unsigned int> indexes;
4083 indexes.push_back(c);
4084 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4085 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004086 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4087 addDecoration(result, noContraction);
4088 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004089 }
4090
4091 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004092 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004093 }
4094 default:
4095 assert(0);
4096 return spv::NoResult;
4097 }
4098}
4099
qining25262b32016-05-06 17:25:16 -04004100spv::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 -06004101{
4102 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004103 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004105#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004106 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004107 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4108#else
Rex Xucabbb782017-03-24 13:41:14 +08004109 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004110 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004111#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004112
4113 switch (op) {
4114 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004115 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004116 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004117 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004118 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004119 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004120 unaryOp = spv::OpSNegate;
4121 break;
4122
4123 case glslang::EOpLogicalNot:
4124 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004125 unaryOp = spv::OpLogicalNot;
4126 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 case glslang::EOpBitwiseNot:
4128 unaryOp = spv::OpNot;
4129 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004130
John Kessenich140f3df2015-06-26 16:58:36 -06004131 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137 case glslang::EOpTranspose:
4138 unaryOp = spv::OpTranspose;
4139 break;
4140
4141 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004142 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004145 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004146 break;
4147 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004148 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004154 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004155 break;
4156 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004157 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004158 break;
4159 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004160 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004161 break;
4162 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004163 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004164 break;
4165
4166 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004167 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004168 break;
4169 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004170 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004171 break;
4172 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004173 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004174 break;
4175 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004176 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004177 break;
4178 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004179 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004180 break;
4181 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004182 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 break;
4184
4185 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004186 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004187 break;
4188 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004189 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004190 break;
4191
4192 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004193 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004194 break;
4195 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004196 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004197 break;
4198 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004199 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004200 break;
4201 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004202 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004203 break;
4204 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004205 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004206 break;
4207 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004208 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004209 break;
4210
4211 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004212 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004213 break;
4214 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004215 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004216 break;
4217 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004218 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004219 break;
4220 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004221 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004222 break;
4223 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004224 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004225 break;
4226 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004227 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004228 break;
4229
4230 case glslang::EOpIsNan:
4231 unaryOp = spv::OpIsNan;
4232 break;
4233 case glslang::EOpIsInf:
4234 unaryOp = spv::OpIsInf;
4235 break;
LoopDawg592860c2016-06-09 08:57:35 -06004236 case glslang::EOpIsFinite:
4237 unaryOp = spv::OpIsFinite;
4238 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004239
Rex Xucbc426e2015-12-15 16:03:10 +08004240 case glslang::EOpFloatBitsToInt:
4241 case glslang::EOpFloatBitsToUint:
4242 case glslang::EOpIntBitsToFloat:
4243 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004244 case glslang::EOpDoubleBitsToInt64:
4245 case glslang::EOpDoubleBitsToUint64:
4246 case glslang::EOpInt64BitsToDouble:
4247 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004248#ifdef AMD_EXTENSIONS
4249 case glslang::EOpFloat16BitsToInt16:
4250 case glslang::EOpFloat16BitsToUint16:
4251 case glslang::EOpInt16BitsToFloat16:
4252 case glslang::EOpUint16BitsToFloat16:
4253#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004254 unaryOp = spv::OpBitcast;
4255 break;
4256
John Kessenich140f3df2015-06-26 16:58:36 -06004257 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004258 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004259 break;
4260 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004261 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004262 break;
4263 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004264 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004265 break;
4266 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004267 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004268 break;
4269 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004270 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004271 break;
4272 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004273 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004274 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004275 case glslang::EOpPackSnorm4x8:
4276 libCall = spv::GLSLstd450PackSnorm4x8;
4277 break;
4278 case glslang::EOpUnpackSnorm4x8:
4279 libCall = spv::GLSLstd450UnpackSnorm4x8;
4280 break;
4281 case glslang::EOpPackUnorm4x8:
4282 libCall = spv::GLSLstd450PackUnorm4x8;
4283 break;
4284 case glslang::EOpUnpackUnorm4x8:
4285 libCall = spv::GLSLstd450UnpackUnorm4x8;
4286 break;
4287 case glslang::EOpPackDouble2x32:
4288 libCall = spv::GLSLstd450PackDouble2x32;
4289 break;
4290 case glslang::EOpUnpackDouble2x32:
4291 libCall = spv::GLSLstd450UnpackDouble2x32;
4292 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004293
Rex Xu8ff43de2016-04-22 16:51:45 +08004294 case glslang::EOpPackInt2x32:
4295 case glslang::EOpUnpackInt2x32:
4296 case glslang::EOpPackUint2x32:
4297 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004298 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004299 break;
4300
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004301#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004302 case glslang::EOpPackInt2x16:
4303 case glslang::EOpUnpackInt2x16:
4304 case glslang::EOpPackUint2x16:
4305 case glslang::EOpUnpackUint2x16:
4306 case glslang::EOpPackInt4x16:
4307 case glslang::EOpUnpackInt4x16:
4308 case glslang::EOpPackUint4x16:
4309 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004310 case glslang::EOpPackFloat2x16:
4311 case glslang::EOpUnpackFloat2x16:
4312 unaryOp = spv::OpBitcast;
4313 break;
4314#endif
4315
John Kessenich140f3df2015-06-26 16:58:36 -06004316 case glslang::EOpDPdx:
4317 unaryOp = spv::OpDPdx;
4318 break;
4319 case glslang::EOpDPdy:
4320 unaryOp = spv::OpDPdy;
4321 break;
4322 case glslang::EOpFwidth:
4323 unaryOp = spv::OpFwidth;
4324 break;
4325 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004326 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004327 unaryOp = spv::OpDPdxFine;
4328 break;
4329 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004330 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004331 unaryOp = spv::OpDPdyFine;
4332 break;
4333 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004334 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004335 unaryOp = spv::OpFwidthFine;
4336 break;
4337 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004338 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004339 unaryOp = spv::OpDPdxCoarse;
4340 break;
4341 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004342 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004343 unaryOp = spv::OpDPdyCoarse;
4344 break;
4345 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004346 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004347 unaryOp = spv::OpFwidthCoarse;
4348 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004349 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004350 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004351 libCall = spv::GLSLstd450InterpolateAtCentroid;
4352 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004353 case glslang::EOpAny:
4354 unaryOp = spv::OpAny;
4355 break;
4356 case glslang::EOpAll:
4357 unaryOp = spv::OpAll;
4358 break;
4359
4360 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004361 if (isFloat)
4362 libCall = spv::GLSLstd450FAbs;
4363 else
4364 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004365 break;
4366 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004367 if (isFloat)
4368 libCall = spv::GLSLstd450FSign;
4369 else
4370 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004371 break;
4372
John Kessenichfc51d282015-08-19 13:34:18 -06004373 case glslang::EOpAtomicCounterIncrement:
4374 case glslang::EOpAtomicCounterDecrement:
4375 case glslang::EOpAtomicCounter:
4376 {
4377 // Handle all of the atomics in one place, in createAtomicOperation()
4378 std::vector<spv::Id> operands;
4379 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004380 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004381 }
4382
John Kessenichfc51d282015-08-19 13:34:18 -06004383 case glslang::EOpBitFieldReverse:
4384 unaryOp = spv::OpBitReverse;
4385 break;
4386 case glslang::EOpBitCount:
4387 unaryOp = spv::OpBitCount;
4388 break;
4389 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004390 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004391 break;
4392 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004393 if (isUnsigned)
4394 libCall = spv::GLSLstd450FindUMsb;
4395 else
4396 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004397 break;
4398
Rex Xu574ab042016-04-14 16:53:07 +08004399 case glslang::EOpBallot:
4400 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004401 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004402 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004403 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004404#ifdef AMD_EXTENSIONS
4405 case glslang::EOpMinInvocations:
4406 case glslang::EOpMaxInvocations:
4407 case glslang::EOpAddInvocations:
4408 case glslang::EOpMinInvocationsNonUniform:
4409 case glslang::EOpMaxInvocationsNonUniform:
4410 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004411 case glslang::EOpMinInvocationsInclusiveScan:
4412 case glslang::EOpMaxInvocationsInclusiveScan:
4413 case glslang::EOpAddInvocationsInclusiveScan:
4414 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4415 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4416 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4417 case glslang::EOpMinInvocationsExclusiveScan:
4418 case glslang::EOpMaxInvocationsExclusiveScan:
4419 case glslang::EOpAddInvocationsExclusiveScan:
4420 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4421 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4422 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004423#endif
Rex Xu51596642016-09-21 18:56:12 +08004424 {
4425 std::vector<spv::Id> operands;
4426 operands.push_back(operand);
4427 return createInvocationsOperation(op, typeId, operands, typeProxy);
4428 }
Rex Xu9d93a232016-05-05 12:30:44 +08004429
4430#ifdef AMD_EXTENSIONS
4431 case glslang::EOpMbcnt:
4432 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4433 libCall = spv::MbcntAMD;
4434 break;
4435
4436 case glslang::EOpCubeFaceIndex:
4437 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4438 libCall = spv::CubeFaceIndexAMD;
4439 break;
4440
4441 case glslang::EOpCubeFaceCoord:
4442 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4443 libCall = spv::CubeFaceCoordAMD;
4444 break;
4445#endif
Rex Xu338b1852016-05-05 20:38:33 +08004446
John Kessenich140f3df2015-06-26 16:58:36 -06004447 default:
4448 return 0;
4449 }
4450
4451 spv::Id id;
4452 if (libCall >= 0) {
4453 std::vector<spv::Id> args;
4454 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004455 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004456 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004457 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004458 }
John Kessenich140f3df2015-06-26 16:58:36 -06004459
qining25262b32016-05-06 17:25:16 -04004460 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004461 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004462}
4463
John Kessenich7a53f762016-01-20 11:19:27 -07004464// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004465spv::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 -07004466{
4467 // Handle unary operations vector by vector.
4468 // The result type is the same type as the original type.
4469 // The algorithm is to:
4470 // - break the matrix into vectors
4471 // - apply the operation to each vector
4472 // - make a matrix out the vector results
4473
4474 // get the types sorted out
4475 int numCols = builder.getNumColumns(operand);
4476 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004477 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4478 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004479 std::vector<spv::Id> results;
4480
4481 // do each vector op
4482 for (int c = 0; c < numCols; ++c) {
4483 std::vector<unsigned int> indexes;
4484 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004485 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4486 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4487 addDecoration(destVec, noContraction);
4488 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004489 }
4490
4491 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004492 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004493}
4494
Rex Xu73e3ce72016-04-27 18:48:17 +08004495spv::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 -06004496{
4497 spv::Op convOp = spv::OpNop;
4498 spv::Id zero = 0;
4499 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004500 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004501
4502 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4503
4504 switch (op) {
4505 case glslang::EOpConvIntToBool:
4506 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004507 case glslang::EOpConvInt64ToBool:
4508 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004509#ifdef AMD_EXTENSIONS
4510 case glslang::EOpConvInt16ToBool:
4511 case glslang::EOpConvUint16ToBool:
4512#endif
4513 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4514 zero = builder.makeUint64Constant(0);
4515#ifdef AMD_EXTENSIONS
4516 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4517 zero = builder.makeUint16Constant(0);
4518#endif
4519 else
4520 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004521 zero = makeSmearedConstant(zero, vectorSize);
4522 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4523
4524 case glslang::EOpConvFloatToBool:
4525 zero = builder.makeFloatConstant(0.0F);
4526 zero = makeSmearedConstant(zero, vectorSize);
4527 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4528
4529 case glslang::EOpConvDoubleToBool:
4530 zero = builder.makeDoubleConstant(0.0);
4531 zero = makeSmearedConstant(zero, vectorSize);
4532 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4533
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004534#ifdef AMD_EXTENSIONS
4535 case glslang::EOpConvFloat16ToBool:
4536 zero = builder.makeFloat16Constant(0.0F);
4537 zero = makeSmearedConstant(zero, vectorSize);
4538 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4539#endif
4540
John Kessenich140f3df2015-06-26 16:58:36 -06004541 case glslang::EOpConvBoolToFloat:
4542 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004543 zero = builder.makeFloatConstant(0.0F);
4544 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004545 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004546
John Kessenich140f3df2015-06-26 16:58:36 -06004547 case glslang::EOpConvBoolToDouble:
4548 convOp = spv::OpSelect;
4549 zero = builder.makeDoubleConstant(0.0);
4550 one = builder.makeDoubleConstant(1.0);
4551 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004552
4553#ifdef AMD_EXTENSIONS
4554 case glslang::EOpConvBoolToFloat16:
4555 convOp = spv::OpSelect;
4556 zero = builder.makeFloat16Constant(0.0F);
4557 one = builder.makeFloat16Constant(1.0F);
4558 break;
4559#endif
4560
John Kessenich140f3df2015-06-26 16:58:36 -06004561 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004562 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004563#ifdef AMD_EXTENSIONS
4564 case glslang::EOpConvBoolToInt16:
4565#endif
4566 if (op == glslang::EOpConvBoolToInt64)
4567 zero = builder.makeInt64Constant(0);
4568#ifdef AMD_EXTENSIONS
4569 else if (op == glslang::EOpConvBoolToInt16)
4570 zero = builder.makeInt16Constant(0);
4571#endif
4572 else
4573 zero = builder.makeIntConstant(0);
4574
4575 if (op == glslang::EOpConvBoolToInt64)
4576 one = builder.makeInt64Constant(1);
4577#ifdef AMD_EXTENSIONS
4578 else if (op == glslang::EOpConvBoolToInt16)
4579 one = builder.makeInt16Constant(1);
4580#endif
4581 else
4582 one = builder.makeIntConstant(1);
4583
John Kessenich140f3df2015-06-26 16:58:36 -06004584 convOp = spv::OpSelect;
4585 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004586
John Kessenich140f3df2015-06-26 16:58:36 -06004587 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004588 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004589#ifdef AMD_EXTENSIONS
4590 case glslang::EOpConvBoolToUint16:
4591#endif
4592 if (op == glslang::EOpConvBoolToUint64)
4593 zero = builder.makeUint64Constant(0);
4594#ifdef AMD_EXTENSIONS
4595 else if (op == glslang::EOpConvBoolToUint16)
4596 zero = builder.makeUint16Constant(0);
4597#endif
4598 else
4599 zero = builder.makeUintConstant(0);
4600
4601 if (op == glslang::EOpConvBoolToUint64)
4602 one = builder.makeUint64Constant(1);
4603#ifdef AMD_EXTENSIONS
4604 else if (op == glslang::EOpConvBoolToUint16)
4605 one = builder.makeUint16Constant(1);
4606#endif
4607 else
4608 one = builder.makeUintConstant(1);
4609
John Kessenich140f3df2015-06-26 16:58:36 -06004610 convOp = spv::OpSelect;
4611 break;
4612
4613 case glslang::EOpConvIntToFloat:
4614 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004615 case glslang::EOpConvInt64ToFloat:
4616 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004617#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004618 case glslang::EOpConvInt16ToFloat:
4619 case glslang::EOpConvInt16ToDouble:
4620 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004621 case glslang::EOpConvIntToFloat16:
4622 case glslang::EOpConvInt64ToFloat16:
4623#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004624 convOp = spv::OpConvertSToF;
4625 break;
4626
4627 case glslang::EOpConvUintToFloat:
4628 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004629 case glslang::EOpConvUint64ToFloat:
4630 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004631#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004632 case glslang::EOpConvUint16ToFloat:
4633 case glslang::EOpConvUint16ToDouble:
4634 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004635 case glslang::EOpConvUintToFloat16:
4636 case glslang::EOpConvUint64ToFloat16:
4637#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004638 convOp = spv::OpConvertUToF;
4639 break;
4640
4641 case glslang::EOpConvDoubleToFloat:
4642 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004643#ifdef AMD_EXTENSIONS
4644 case glslang::EOpConvDoubleToFloat16:
4645 case glslang::EOpConvFloat16ToDouble:
4646 case glslang::EOpConvFloatToFloat16:
4647 case glslang::EOpConvFloat16ToFloat:
4648#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004649 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004650 if (builder.isMatrixType(destType))
4651 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004652 break;
4653
4654 case glslang::EOpConvFloatToInt:
4655 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004656 case glslang::EOpConvFloatToInt64:
4657 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004658#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004659 case glslang::EOpConvFloatToInt16:
4660 case glslang::EOpConvDoubleToInt16:
4661 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004662 case glslang::EOpConvFloat16ToInt:
4663 case glslang::EOpConvFloat16ToInt64:
4664#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004665 convOp = spv::OpConvertFToS;
4666 break;
4667
4668 case glslang::EOpConvUintToInt:
4669 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004670 case glslang::EOpConvUint64ToInt64:
4671 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004672#ifdef AMD_EXTENSIONS
4673 case glslang::EOpConvUint16ToInt16:
4674 case glslang::EOpConvInt16ToUint16:
4675#endif
qininge24aa5e2016-04-07 15:40:27 -04004676 if (builder.isInSpecConstCodeGenMode()) {
4677 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004678 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4679 zero = builder.makeUint64Constant(0);
4680#ifdef AMD_EXTENSIONS
4681 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4682 zero = builder.makeUint16Constant(0);
4683#endif
4684 else
4685 zero = builder.makeUintConstant(0);
4686
qining189b2032016-04-12 23:16:20 -04004687 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004688 // Use OpIAdd, instead of OpBitcast to do the conversion when
4689 // generating for OpSpecConstantOp instruction.
4690 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4691 }
4692 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004693 convOp = spv::OpBitcast;
4694 break;
4695
4696 case glslang::EOpConvFloatToUint:
4697 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004698 case glslang::EOpConvFloatToUint64:
4699 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004700#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004701 case glslang::EOpConvFloatToUint16:
4702 case glslang::EOpConvDoubleToUint16:
4703 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004704 case glslang::EOpConvFloat16ToUint:
4705 case glslang::EOpConvFloat16ToUint64:
4706#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004707 convOp = spv::OpConvertFToU;
4708 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004709
4710 case glslang::EOpConvIntToInt64:
4711 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004712#ifdef AMD_EXTENSIONS
4713 case glslang::EOpConvIntToInt16:
4714 case glslang::EOpConvInt16ToInt:
4715 case glslang::EOpConvInt64ToInt16:
4716 case glslang::EOpConvInt16ToInt64:
4717#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004718 convOp = spv::OpSConvert;
4719 break;
4720
4721 case glslang::EOpConvUintToUint64:
4722 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004723#ifdef AMD_EXTENSIONS
4724 case glslang::EOpConvUintToUint16:
4725 case glslang::EOpConvUint16ToUint:
4726 case glslang::EOpConvUint64ToUint16:
4727 case glslang::EOpConvUint16ToUint64:
4728#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004729 convOp = spv::OpUConvert;
4730 break;
4731
4732 case glslang::EOpConvIntToUint64:
4733 case glslang::EOpConvInt64ToUint:
4734 case glslang::EOpConvUint64ToInt:
4735 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004736#ifdef AMD_EXTENSIONS
4737 case glslang::EOpConvInt16ToUint:
4738 case glslang::EOpConvUintToInt16:
4739 case glslang::EOpConvInt16ToUint64:
4740 case glslang::EOpConvUint64ToInt16:
4741 case glslang::EOpConvUint16ToInt:
4742 case glslang::EOpConvIntToUint16:
4743 case glslang::EOpConvUint16ToInt64:
4744 case glslang::EOpConvInt64ToUint16:
4745#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004746 // OpSConvert/OpUConvert + OpBitCast
4747 switch (op) {
4748 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004749#ifdef AMD_EXTENSIONS
4750 case glslang::EOpConvInt16ToUint64:
4751#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004752 convOp = spv::OpSConvert;
4753 type = builder.makeIntType(64);
4754 break;
4755 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004756#ifdef AMD_EXTENSIONS
4757 case glslang::EOpConvInt16ToUint:
4758#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004759 convOp = spv::OpSConvert;
4760 type = builder.makeIntType(32);
4761 break;
4762 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004763#ifdef AMD_EXTENSIONS
4764 case glslang::EOpConvUint16ToInt:
4765#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004766 convOp = spv::OpUConvert;
4767 type = builder.makeUintType(32);
4768 break;
4769 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004770#ifdef AMD_EXTENSIONS
4771 case glslang::EOpConvUint16ToInt64:
4772#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004773 convOp = spv::OpUConvert;
4774 type = builder.makeUintType(64);
4775 break;
Rex Xucabbb782017-03-24 13:41:14 +08004776#ifdef AMD_EXTENSIONS
4777 case glslang::EOpConvUintToInt16:
4778 case glslang::EOpConvUint64ToInt16:
4779 convOp = spv::OpUConvert;
4780 type = builder.makeUintType(16);
4781 break;
4782 case glslang::EOpConvIntToUint16:
4783 case glslang::EOpConvInt64ToUint16:
4784 convOp = spv::OpSConvert;
4785 type = builder.makeIntType(16);
4786 break;
4787#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004788 default:
4789 assert(0);
4790 break;
4791 }
4792
4793 if (vectorSize > 0)
4794 type = builder.makeVectorType(type, vectorSize);
4795
4796 operand = builder.createUnaryOp(convOp, type, operand);
4797
4798 if (builder.isInSpecConstCodeGenMode()) {
4799 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004800#ifdef AMD_EXTENSIONS
4801 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4802 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4803 zero = builder.makeUint64Constant(0);
4804 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4805 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4806 zero = builder.makeUint16Constant(0);
4807 else
4808 zero = builder.makeUintConstant(0);
4809#else
4810 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4811 zero = builder.makeUint64Constant(0);
4812 else
4813 zero = builder.makeUintConstant(0);
4814#endif
4815
Rex Xu8ff43de2016-04-22 16:51:45 +08004816 zero = makeSmearedConstant(zero, vectorSize);
4817 // Use OpIAdd, instead of OpBitcast to do the conversion when
4818 // generating for OpSpecConstantOp instruction.
4819 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4820 }
4821 // For normal run-time conversion instruction, use OpBitcast.
4822 convOp = spv::OpBitcast;
4823 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004824 default:
4825 break;
4826 }
4827
4828 spv::Id result = 0;
4829 if (convOp == spv::OpNop)
4830 return result;
4831
4832 if (convOp == spv::OpSelect) {
4833 zero = makeSmearedConstant(zero, vectorSize);
4834 one = makeSmearedConstant(one, vectorSize);
4835 result = builder.createTriOp(convOp, destType, operand, one, zero);
4836 } else
4837 result = builder.createUnaryOp(convOp, destType, operand);
4838
John Kessenich32cfd492016-02-02 12:37:46 -07004839 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004840}
4841
4842spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4843{
4844 if (vectorSize == 0)
4845 return constant;
4846
4847 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4848 std::vector<spv::Id> components;
4849 for (int c = 0; c < vectorSize; ++c)
4850 components.push_back(constant);
4851 return builder.makeCompositeConstant(vectorTypeId, components);
4852}
4853
John Kessenich426394d2015-07-23 10:22:48 -06004854// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004855spv::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 -06004856{
4857 spv::Op opCode = spv::OpNop;
4858
4859 switch (op) {
4860 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004861 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004862 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004863 opCode = spv::OpAtomicIAdd;
4864 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004865 case glslang::EOpAtomicCounterSubtract:
4866 opCode = spv::OpAtomicISub;
4867 break;
John Kessenich426394d2015-07-23 10:22:48 -06004868 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004869 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004870 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004871 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004872 break;
4873 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004874 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004875 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004876 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004877 break;
4878 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004879 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004880 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004881 opCode = spv::OpAtomicAnd;
4882 break;
4883 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004884 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004885 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004886 opCode = spv::OpAtomicOr;
4887 break;
4888 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004889 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004890 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004891 opCode = spv::OpAtomicXor;
4892 break;
4893 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004894 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004895 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004896 opCode = spv::OpAtomicExchange;
4897 break;
4898 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004899 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004900 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004901 opCode = spv::OpAtomicCompareExchange;
4902 break;
4903 case glslang::EOpAtomicCounterIncrement:
4904 opCode = spv::OpAtomicIIncrement;
4905 break;
4906 case glslang::EOpAtomicCounterDecrement:
4907 opCode = spv::OpAtomicIDecrement;
4908 break;
4909 case glslang::EOpAtomicCounter:
4910 opCode = spv::OpAtomicLoad;
4911 break;
4912 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004913 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004914 break;
4915 }
4916
Rex Xue8fe8b02017-09-26 15:42:56 +08004917 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4918 builder.addCapability(spv::CapabilityInt64Atomics);
4919
John Kessenich426394d2015-07-23 10:22:48 -06004920 // Sort out the operands
4921 // - mapping from glslang -> SPV
4922 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004923 // - compare-exchange swaps the value and comparator
4924 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004925 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004926 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4927 auto opIt = operands.begin(); // walk the glslang operands
4928 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004929 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4930 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4931 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004932 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4933 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004934 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004935 spvAtomicOperands.push_back(*(opIt + 1));
4936 spvAtomicOperands.push_back(*opIt);
4937 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004938 }
John Kessenich426394d2015-07-23 10:22:48 -06004939
John Kessenich3e60a6f2015-09-14 22:45:16 -06004940 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004941 for (; opIt != operands.end(); ++opIt)
4942 spvAtomicOperands.push_back(*opIt);
4943
John Kessenich48d6e792017-10-06 21:21:48 -06004944 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4945
4946 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4947 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4948 if (op == glslang::EOpAtomicCounterDecrement)
4949 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4950
4951 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004952}
4953
John Kessenich91cef522016-05-05 16:45:40 -06004954// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004955spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004956{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004957#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004958 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004959 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004960#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004961
Rex Xu51596642016-09-21 18:56:12 +08004962 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004963 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004964 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4965
chaocf200da82016-12-20 12:44:35 -08004966 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4967 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004968 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4969 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004970 } else if (op == glslang::EOpAnyInvocation ||
4971 op == glslang::EOpAllInvocations ||
4972 op == glslang::EOpAllInvocationsEqual) {
4973 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4974 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004975 } else {
4976 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004977#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004978 if (op == glslang::EOpMinInvocationsNonUniform ||
4979 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004980 op == glslang::EOpAddInvocationsNonUniform ||
4981 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4982 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4983 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4984 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4985 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4986 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004987 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004988#endif
Rex Xu51596642016-09-21 18:56:12 +08004989
4990 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004991#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004992 switch (op) {
4993 case glslang::EOpMinInvocations:
4994 case glslang::EOpMaxInvocations:
4995 case glslang::EOpAddInvocations:
4996 case glslang::EOpMinInvocationsNonUniform:
4997 case glslang::EOpMaxInvocationsNonUniform:
4998 case glslang::EOpAddInvocationsNonUniform:
4999 groupOperation = spv::GroupOperationReduce;
5000 spvGroupOperands.push_back(groupOperation);
5001 break;
5002 case glslang::EOpMinInvocationsInclusiveScan:
5003 case glslang::EOpMaxInvocationsInclusiveScan:
5004 case glslang::EOpAddInvocationsInclusiveScan:
5005 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5006 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5007 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5008 groupOperation = spv::GroupOperationInclusiveScan;
5009 spvGroupOperands.push_back(groupOperation);
5010 break;
5011 case glslang::EOpMinInvocationsExclusiveScan:
5012 case glslang::EOpMaxInvocationsExclusiveScan:
5013 case glslang::EOpAddInvocationsExclusiveScan:
5014 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5015 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5016 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5017 groupOperation = spv::GroupOperationExclusiveScan;
5018 spvGroupOperands.push_back(groupOperation);
5019 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005020 default:
5021 break;
Rex Xu430ef402016-10-14 17:22:23 +08005022 }
Rex Xu9d93a232016-05-05 12:30:44 +08005023#endif
Rex Xu51596642016-09-21 18:56:12 +08005024 }
5025
5026 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5027 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005028
5029 switch (op) {
5030 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005031 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005032 break;
John Kessenich91cef522016-05-05 16:45:40 -06005033 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005034 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005035 break;
John Kessenich91cef522016-05-05 16:45:40 -06005036 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005037 opCode = spv::OpSubgroupAllEqualKHR;
5038 break;
Rex Xu51596642016-09-21 18:56:12 +08005039 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005040 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005041 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005042 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005043 break;
5044 case glslang::EOpReadFirstInvocation:
5045 opCode = spv::OpSubgroupFirstInvocationKHR;
5046 break;
5047 case glslang::EOpBallot:
5048 {
5049 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5050 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5051 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5052 //
5053 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5054 //
5055 spv::Id uintType = builder.makeUintType(32);
5056 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5057 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5058
5059 std::vector<spv::Id> components;
5060 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5061 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5062
5063 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5064 return builder.createUnaryOp(spv::OpBitcast, typeId,
5065 builder.createCompositeConstruct(uvec2Type, components));
5066 }
5067
Rex Xu9d93a232016-05-05 12:30:44 +08005068#ifdef AMD_EXTENSIONS
5069 case glslang::EOpMinInvocations:
5070 case glslang::EOpMaxInvocations:
5071 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005072 case glslang::EOpMinInvocationsInclusiveScan:
5073 case glslang::EOpMaxInvocationsInclusiveScan:
5074 case glslang::EOpAddInvocationsInclusiveScan:
5075 case glslang::EOpMinInvocationsExclusiveScan:
5076 case glslang::EOpMaxInvocationsExclusiveScan:
5077 case glslang::EOpAddInvocationsExclusiveScan:
5078 if (op == glslang::EOpMinInvocations ||
5079 op == glslang::EOpMinInvocationsInclusiveScan ||
5080 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005081 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005082 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005083 else {
5084 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005085 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005086 else
Rex Xu51596642016-09-21 18:56:12 +08005087 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005088 }
Rex Xu430ef402016-10-14 17:22:23 +08005089 } else if (op == glslang::EOpMaxInvocations ||
5090 op == glslang::EOpMaxInvocationsInclusiveScan ||
5091 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005092 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005093 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005094 else {
5095 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005096 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005097 else
Rex Xu51596642016-09-21 18:56:12 +08005098 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005099 }
5100 } else {
5101 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005102 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005103 else
Rex Xu51596642016-09-21 18:56:12 +08005104 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005105 }
5106
Rex Xu2bbbe062016-08-23 15:41:05 +08005107 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005108 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005109
5110 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005111 case glslang::EOpMinInvocationsNonUniform:
5112 case glslang::EOpMaxInvocationsNonUniform:
5113 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005114 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5115 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5116 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5117 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5118 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5119 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5120 if (op == glslang::EOpMinInvocationsNonUniform ||
5121 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5122 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005123 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005124 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005125 else {
5126 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005127 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005128 else
Rex Xu51596642016-09-21 18:56:12 +08005129 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005130 }
5131 }
Rex Xu430ef402016-10-14 17:22:23 +08005132 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5133 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5134 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005135 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005136 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005137 else {
5138 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005139 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005140 else
Rex Xu51596642016-09-21 18:56:12 +08005141 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005142 }
5143 }
5144 else {
5145 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005146 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005147 else
Rex Xu51596642016-09-21 18:56:12 +08005148 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005149 }
5150
Rex Xu2bbbe062016-08-23 15:41:05 +08005151 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005152 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005153
5154 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005155#endif
John Kessenich91cef522016-05-05 16:45:40 -06005156 default:
5157 logger->missingFunctionality("invocation operation");
5158 return spv::NoResult;
5159 }
Rex Xu51596642016-09-21 18:56:12 +08005160
5161 assert(opCode != spv::OpNop);
5162 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005163}
5164
Rex Xu2bbbe062016-08-23 15:41:05 +08005165// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005166spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005167{
Rex Xub7072052016-09-26 15:53:40 +08005168#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005169 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5170 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005171 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005172 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005173 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5174 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5175 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005176#else
5177 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5178 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005179 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5180 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005181#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005182
5183 // Handle group invocation operations scalar by scalar.
5184 // The result type is the same type as the original type.
5185 // The algorithm is to:
5186 // - break the vector into scalars
5187 // - apply the operation to each scalar
5188 // - make a vector out the scalar results
5189
5190 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005191 int numComponents = builder.getNumComponents(operands[0]);
5192 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005193 std::vector<spv::Id> results;
5194
5195 // do each scalar op
5196 for (int comp = 0; comp < numComponents; ++comp) {
5197 std::vector<unsigned int> indexes;
5198 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005199 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005200 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005201 if (op == spv::OpSubgroupReadInvocationKHR) {
5202 spvGroupOperands.push_back(scalar);
5203 spvGroupOperands.push_back(operands[1]);
5204 } else if (op == spv::OpGroupBroadcast) {
5205 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005206 spvGroupOperands.push_back(scalar);
5207 spvGroupOperands.push_back(operands[1]);
5208 } else {
chaocf200da82016-12-20 12:44:35 -08005209 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005210 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005211 spvGroupOperands.push_back(scalar);
5212 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005213
Rex Xub7072052016-09-26 15:53:40 +08005214 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005215 }
5216
5217 // put the pieces together
5218 return builder.createCompositeConstruct(typeId, results);
5219}
Rex Xu2bbbe062016-08-23 15:41:05 +08005220
John Kessenich5e4b1242015-08-06 22:53:06 -06005221spv::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 -06005222{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005223#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005224 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005225 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5226#else
Rex Xucabbb782017-03-24 13:41:14 +08005227 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005228 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005229#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005230
John Kessenich140f3df2015-06-26 16:58:36 -06005231 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005232 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005233 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005234 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005235 spv::Id typeId0 = 0;
5236 if (consumedOperands > 0)
5237 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005238 spv::Id typeId1 = 0;
5239 if (consumedOperands > 1)
5240 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005241 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005242
5243 switch (op) {
5244 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005245 if (isFloat)
5246 libCall = spv::GLSLstd450FMin;
5247 else if (isUnsigned)
5248 libCall = spv::GLSLstd450UMin;
5249 else
5250 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005251 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005252 break;
5253 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005254 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005255 break;
5256 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005257 if (isFloat)
5258 libCall = spv::GLSLstd450FMax;
5259 else if (isUnsigned)
5260 libCall = spv::GLSLstd450UMax;
5261 else
5262 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005263 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005264 break;
5265 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 break;
5268 case glslang::EOpDot:
5269 opCode = spv::OpDot;
5270 break;
5271 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005272 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005273 break;
5274
5275 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 if (isFloat)
5277 libCall = spv::GLSLstd450FClamp;
5278 else if (isUnsigned)
5279 libCall = spv::GLSLstd450UClamp;
5280 else
5281 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005282 builder.promoteScalar(precision, operands.front(), operands[1]);
5283 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005284 break;
5285 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005286 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5287 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005288 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005289 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005290 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005291 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005292 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005293 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005294 break;
5295 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005296 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005297 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005298 break;
5299 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005300 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005301 builder.promoteScalar(precision, operands[0], operands[2]);
5302 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005303 break;
5304
5305 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005306 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005307 break;
5308 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005309 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005310 break;
5311 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005312 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005313 break;
5314 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005315 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005316 break;
5317 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005318 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005319 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005320 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005321 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005322 libCall = spv::GLSLstd450InterpolateAtSample;
5323 break;
5324 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005325 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005326 libCall = spv::GLSLstd450InterpolateAtOffset;
5327 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005328 case glslang::EOpAddCarry:
5329 opCode = spv::OpIAddCarry;
5330 typeId = builder.makeStructResultType(typeId0, typeId0);
5331 consumedOperands = 2;
5332 break;
5333 case glslang::EOpSubBorrow:
5334 opCode = spv::OpISubBorrow;
5335 typeId = builder.makeStructResultType(typeId0, typeId0);
5336 consumedOperands = 2;
5337 break;
5338 case glslang::EOpUMulExtended:
5339 opCode = spv::OpUMulExtended;
5340 typeId = builder.makeStructResultType(typeId0, typeId0);
5341 consumedOperands = 2;
5342 break;
5343 case glslang::EOpIMulExtended:
5344 opCode = spv::OpSMulExtended;
5345 typeId = builder.makeStructResultType(typeId0, typeId0);
5346 consumedOperands = 2;
5347 break;
5348 case glslang::EOpBitfieldExtract:
5349 if (isUnsigned)
5350 opCode = spv::OpBitFieldUExtract;
5351 else
5352 opCode = spv::OpBitFieldSExtract;
5353 break;
5354 case glslang::EOpBitfieldInsert:
5355 opCode = spv::OpBitFieldInsert;
5356 break;
5357
5358 case glslang::EOpFma:
5359 libCall = spv::GLSLstd450Fma;
5360 break;
5361 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005362 {
5363 libCall = spv::GLSLstd450FrexpStruct;
5364 assert(builder.isPointerType(typeId1));
5365 typeId1 = builder.getContainedTypeId(typeId1);
5366#ifdef AMD_EXTENSIONS
5367 int width = builder.getScalarTypeWidth(typeId1);
5368#else
5369 int width = 32;
5370#endif
5371 if (builder.getNumComponents(operands[0]) == 1)
5372 frexpIntType = builder.makeIntegerType(width, true);
5373 else
5374 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5375 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5376 consumedOperands = 1;
5377 }
John Kessenich55e7d112015-11-15 21:33:39 -07005378 break;
5379 case glslang::EOpLdexp:
5380 libCall = spv::GLSLstd450Ldexp;
5381 break;
5382
Rex Xu574ab042016-04-14 16:53:07 +08005383 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005384 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005385
Rex Xu9d93a232016-05-05 12:30:44 +08005386#ifdef AMD_EXTENSIONS
5387 case glslang::EOpSwizzleInvocations:
5388 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5389 libCall = spv::SwizzleInvocationsAMD;
5390 break;
5391 case glslang::EOpSwizzleInvocationsMasked:
5392 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5393 libCall = spv::SwizzleInvocationsMaskedAMD;
5394 break;
5395 case glslang::EOpWriteInvocation:
5396 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5397 libCall = spv::WriteInvocationAMD;
5398 break;
5399
5400 case glslang::EOpMin3:
5401 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5402 if (isFloat)
5403 libCall = spv::FMin3AMD;
5404 else {
5405 if (isUnsigned)
5406 libCall = spv::UMin3AMD;
5407 else
5408 libCall = spv::SMin3AMD;
5409 }
5410 break;
5411 case glslang::EOpMax3:
5412 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5413 if (isFloat)
5414 libCall = spv::FMax3AMD;
5415 else {
5416 if (isUnsigned)
5417 libCall = spv::UMax3AMD;
5418 else
5419 libCall = spv::SMax3AMD;
5420 }
5421 break;
5422 case glslang::EOpMid3:
5423 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5424 if (isFloat)
5425 libCall = spv::FMid3AMD;
5426 else {
5427 if (isUnsigned)
5428 libCall = spv::UMid3AMD;
5429 else
5430 libCall = spv::SMid3AMD;
5431 }
5432 break;
5433
5434 case glslang::EOpInterpolateAtVertex:
5435 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5436 libCall = spv::InterpolateAtVertexAMD;
5437 break;
5438#endif
5439
John Kessenich140f3df2015-06-26 16:58:36 -06005440 default:
5441 return 0;
5442 }
5443
5444 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005445 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005446 // Use an extended instruction from the standard library.
5447 // Construct the call arguments, without modifying the original operands vector.
5448 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5449 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005450 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005451 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005452 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005453 case 0:
5454 // should all be handled by visitAggregate and createNoArgOperation
5455 assert(0);
5456 return 0;
5457 case 1:
5458 // should all be handled by createUnaryOperation
5459 assert(0);
5460 return 0;
5461 case 2:
5462 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5463 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005464 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005465 // anything 3 or over doesn't have l-value operands, so all should be consumed
5466 assert(consumedOperands == operands.size());
5467 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 }
5470 }
5471
John Kessenich55e7d112015-11-15 21:33:39 -07005472 // Decode the return types that were structures
5473 switch (op) {
5474 case glslang::EOpAddCarry:
5475 case glslang::EOpSubBorrow:
5476 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5477 id = builder.createCompositeExtract(id, typeId0, 0);
5478 break;
5479 case glslang::EOpUMulExtended:
5480 case glslang::EOpIMulExtended:
5481 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5482 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5483 break;
5484 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005485 {
5486 assert(operands.size() == 2);
5487 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5488 // "exp" is floating-point type (from HLSL intrinsic)
5489 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5490 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5491 builder.createStore(member1, operands[1]);
5492 } else
5493 // "exp" is integer type (from GLSL built-in function)
5494 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5495 id = builder.createCompositeExtract(id, typeId0, 0);
5496 }
John Kessenich55e7d112015-11-15 21:33:39 -07005497 break;
5498 default:
5499 break;
5500 }
5501
John Kessenich32cfd492016-02-02 12:37:46 -07005502 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005503}
5504
Rex Xu9d93a232016-05-05 12:30:44 +08005505// Intrinsics with no arguments (or no return value, and no precision).
5506spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005507{
5508 // TODO: get the barrier operands correct
5509
5510 switch (op) {
5511 case glslang::EOpEmitVertex:
5512 builder.createNoResultOp(spv::OpEmitVertex);
5513 return 0;
5514 case glslang::EOpEndPrimitive:
5515 builder.createNoResultOp(spv::OpEndPrimitive);
5516 return 0;
5517 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005518 if (glslangIntermediate->getStage() == EShLangTessControl) {
5519 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5520 // TODO: prefer the following, when available:
5521 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5522 // spv::MemorySemanticsPatchMask |
5523 // spv::MemorySemanticsAcquireReleaseMask);
5524 } else {
5525 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5526 spv::MemorySemanticsWorkgroupMemoryMask |
5527 spv::MemorySemanticsAcquireReleaseMask);
5528 }
John Kessenich140f3df2015-06-26 16:58:36 -06005529 return 0;
5530 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005531 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5532 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005533 return 0;
5534 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005535 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5536 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005537 return 0;
5538 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005539 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5540 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005541 return 0;
5542 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005543 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5544 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005545 return 0;
5546 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005547 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5548 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005549 return 0;
5550 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005551 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5552 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005553 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005554 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005555 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005556 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005557 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005558 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005559 case glslang::EOpDeviceMemoryBarrier:
5560 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5561 spv::MemorySemanticsImageMemoryMask |
5562 spv::MemorySemanticsAcquireReleaseMask);
5563 return 0;
5564 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5565 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5566 spv::MemorySemanticsImageMemoryMask |
5567 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005568 return 0;
5569 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005570 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5571 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005572 return 0;
5573 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005574 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5575 spv::MemorySemanticsWorkgroupMemoryMask |
5576 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005577 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005578#ifdef AMD_EXTENSIONS
5579 case glslang::EOpTime:
5580 {
5581 std::vector<spv::Id> args; // Dummy arguments
5582 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5583 return builder.setPrecision(id, precision);
5584 }
5585#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005586 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005587 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005588 return 0;
5589 }
5590}
5591
5592spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5593{
John Kessenich2f273362015-07-18 22:34:27 -06005594 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005595 spv::Id id;
5596 if (symbolValues.end() != iter) {
5597 id = iter->second;
5598 return id;
5599 }
5600
5601 // it was not found, create it
5602 id = createSpvVariable(symbol);
5603 symbolValues[symbol->getId()] = id;
5604
Rex Xuc884b4a2016-06-29 15:03:44 +08005605 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005606 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005607 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005608 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005609 if (symbol->getType().getQualifier().hasSpecConstantId())
5610 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005611 if (symbol->getQualifier().hasIndex())
5612 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5613 if (symbol->getQualifier().hasComponent())
5614 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005615 // atomic counters use this:
5616 if (symbol->getQualifier().hasOffset())
5617 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005618 }
5619
scygan2c864272016-05-18 18:09:17 +02005620 if (symbol->getQualifier().hasLocation())
5621 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005622 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005623 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005624 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005625 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005626 }
John Kessenich140f3df2015-06-26 16:58:36 -06005627 if (symbol->getQualifier().hasSet())
5628 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005629 else if (IsDescriptorResource(symbol->getType())) {
5630 // default to 0
5631 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5632 }
John Kessenich140f3df2015-06-26 16:58:36 -06005633 if (symbol->getQualifier().hasBinding())
5634 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005635 if (symbol->getQualifier().hasAttachment())
5636 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005637 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005638 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005639 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005640 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005641 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005642 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005643 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5644 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5645 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5646 }
5647 if (symbol->getQualifier().hasXfbOffset())
5648 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005649 }
5650
Rex Xu1da878f2016-02-21 20:59:01 +08005651 if (symbol->getType().isImage()) {
5652 std::vector<spv::Decoration> memory;
5653 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5654 for (unsigned int i = 0; i < memory.size(); ++i)
5655 addDecoration(id, memory[i]);
5656 }
5657
John Kessenich140f3df2015-06-26 16:58:36 -06005658 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005659 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005660 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005661 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005662
John Kessenichecba76f2017-01-06 00:34:48 -07005663#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005664 if (builtIn == spv::BuiltInSampleMask) {
5665 spv::Decoration decoration;
5666 // GL_NV_sample_mask_override_coverage extension
5667 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005668 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005669 else
5670 decoration = (spv::Decoration)spv::DecorationMax;
5671 addDecoration(id, decoration);
5672 if (decoration != spv::DecorationMax) {
5673 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5674 }
5675 }
chaoc771d89f2017-01-13 01:10:53 -08005676 else if (builtIn == spv::BuiltInLayer) {
5677 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005678 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005679 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5680 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5681 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5682 }
John Kessenichb41bff62017-08-11 13:07:17 -06005683 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005684 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5685 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5686 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5687 }
5688 }
5689
chaoc6e5acae2016-12-20 13:28:52 -08005690 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005691 addDecoration(id, spv::DecorationPassthroughNV);
5692 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005693 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5694 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005695#endif
5696
John Kessenich140f3df2015-06-26 16:58:36 -06005697 return id;
5698}
5699
John Kessenich55e7d112015-11-15 21:33:39 -07005700// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005701void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5702{
John Kessenich4016e382016-07-15 11:53:56 -06005703 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005704 builder.addDecoration(id, dec);
5705}
5706
John Kessenich55e7d112015-11-15 21:33:39 -07005707// If 'dec' is valid, add a one-operand decoration to an object
5708void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5709{
John Kessenich4016e382016-07-15 11:53:56 -06005710 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005711 builder.addDecoration(id, dec, value);
5712}
5713
5714// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005715void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5716{
John Kessenich4016e382016-07-15 11:53:56 -06005717 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005718 builder.addMemberDecoration(id, (unsigned)member, dec);
5719}
5720
John Kessenich92187592016-02-01 13:45:25 -07005721// If 'dec' is valid, add a one-operand decoration to a struct member
5722void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5723{
John Kessenich4016e382016-07-15 11:53:56 -06005724 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005725 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5726}
5727
John Kessenich55e7d112015-11-15 21:33:39 -07005728// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005729// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005730//
5731// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5732//
5733// Recursively walk the nodes. The nodes form a tree whose leaves are
5734// regular constants, which themselves are trees that createSpvConstant()
5735// recursively walks. So, this function walks the "top" of the tree:
5736// - emit specialization constant-building instructions for specConstant
5737// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005738spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005739{
John Kessenich7cc0e282016-03-20 00:46:02 -06005740 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005741
qining4f4bb812016-04-03 23:55:17 -04005742 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005743 if (! node.getQualifier().specConstant) {
5744 // hand off to the non-spec-constant path
5745 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5746 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005747 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005748 nextConst, false);
5749 }
5750
5751 // We now know we have a specialization constant to build
5752
John Kessenichd94c0032016-05-30 19:29:40 -06005753 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005754 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5755 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5756 std::vector<spv::Id> dimConstId;
5757 for (int dim = 0; dim < 3; ++dim) {
5758 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5759 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5760 if (specConst)
5761 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5762 }
5763 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5764 }
5765
5766 // An AST node labelled as specialization constant should be a symbol node.
5767 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5768 if (auto* sn = node.getAsSymbolNode()) {
5769 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005770 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5771 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5772 // will set the builder into spec constant op instruction generating mode.
5773 sub_tree->traverse(this);
5774 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005775 } else if (auto* const_union_array = &sn->getConstArray()){
5776 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005777 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5778 builder.addName(id, sn->getName().c_str());
5779 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005780 }
5781 }
qining4f4bb812016-04-03 23:55:17 -04005782
5783 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5784 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005785 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005786 exit(1);
5787 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005788}
5789
John Kessenich140f3df2015-06-26 16:58:36 -06005790// Use 'consts' as the flattened glslang source of scalar constants to recursively
5791// build the aggregate SPIR-V constant.
5792//
5793// If there are not enough elements present in 'consts', 0 will be substituted;
5794// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5795//
qining08408382016-03-21 09:51:37 -04005796spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005797{
5798 // vector of constants for SPIR-V
5799 std::vector<spv::Id> spvConsts;
5800
5801 // Type is used for struct and array constants
5802 spv::Id typeId = convertGlslangToSpvType(glslangType);
5803
5804 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005805 glslang::TType elementType(glslangType, 0);
5806 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005807 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005808 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005809 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005810 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005811 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005812 } else if (glslangType.getStruct()) {
5813 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5814 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005815 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005816 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005817 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5818 bool zero = nextConst >= consts.size();
5819 switch (glslangType.getBasicType()) {
5820 case glslang::EbtInt:
5821 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5822 break;
5823 case glslang::EbtUint:
5824 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5825 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005826 case glslang::EbtInt64:
5827 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5828 break;
5829 case glslang::EbtUint64:
5830 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5831 break;
Rex Xucabbb782017-03-24 13:41:14 +08005832#ifdef AMD_EXTENSIONS
5833 case glslang::EbtInt16:
5834 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5835 break;
5836 case glslang::EbtUint16:
5837 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5838 break;
5839#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005840 case glslang::EbtFloat:
5841 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5842 break;
5843 case glslang::EbtDouble:
5844 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5845 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005846#ifdef AMD_EXTENSIONS
5847 case glslang::EbtFloat16:
5848 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5849 break;
5850#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005851 case glslang::EbtBool:
5852 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5853 break;
5854 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005855 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 }
5858 ++nextConst;
5859 }
5860 } else {
5861 // we have a non-aggregate (scalar) constant
5862 bool zero = nextConst >= consts.size();
5863 spv::Id scalar = 0;
5864 switch (glslangType.getBasicType()) {
5865 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005866 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005869 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005870 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005871 case glslang::EbtInt64:
5872 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5873 break;
5874 case glslang::EbtUint64:
5875 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5876 break;
Rex Xucabbb782017-03-24 13:41:14 +08005877#ifdef AMD_EXTENSIONS
5878 case glslang::EbtInt16:
5879 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5880 break;
5881 case glslang::EbtUint16:
5882 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5883 break;
5884#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005885 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005886 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005887 break;
5888 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005889 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005890 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005891#ifdef AMD_EXTENSIONS
5892 case glslang::EbtFloat16:
5893 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5894 break;
5895#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005896 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005897 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005900 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
5902 }
5903 ++nextConst;
5904 return scalar;
5905 }
5906
5907 return builder.makeCompositeConstant(typeId, spvConsts);
5908}
5909
John Kessenich7c1aa102015-10-15 13:29:11 -06005910// Return true if the node is a constant or symbol whose reading has no
5911// non-trivial observable cost or effect.
5912bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5913{
5914 // don't know what this is
5915 if (node == nullptr)
5916 return false;
5917
5918 // a constant is safe
5919 if (node->getAsConstantUnion() != nullptr)
5920 return true;
5921
5922 // not a symbol means non-trivial
5923 if (node->getAsSymbolNode() == nullptr)
5924 return false;
5925
5926 // a symbol, depends on what's being read
5927 switch (node->getType().getQualifier().storage) {
5928 case glslang::EvqTemporary:
5929 case glslang::EvqGlobal:
5930 case glslang::EvqIn:
5931 case glslang::EvqInOut:
5932 case glslang::EvqConst:
5933 case glslang::EvqConstReadOnly:
5934 case glslang::EvqUniform:
5935 return true;
5936 default:
5937 return false;
5938 }
qining25262b32016-05-06 17:25:16 -04005939}
John Kessenich7c1aa102015-10-15 13:29:11 -06005940
5941// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005942// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005943// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005944// Return true if trivial.
5945bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5946{
5947 if (node == nullptr)
5948 return false;
5949
John Kessenich84cc15f2017-05-24 16:44:47 -06005950 // count non scalars as trivial, as well as anything coming from HLSL
5951 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005952 return true;
5953
John Kessenich7c1aa102015-10-15 13:29:11 -06005954 // symbols and constants are trivial
5955 if (isTrivialLeaf(node))
5956 return true;
5957
5958 // otherwise, it needs to be a simple operation or one or two leaf nodes
5959
5960 // not a simple operation
5961 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5962 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5963 if (binaryNode == nullptr && unaryNode == nullptr)
5964 return false;
5965
5966 // not on leaf nodes
5967 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5968 return false;
5969
5970 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5971 return false;
5972 }
5973
5974 switch (node->getAsOperator()->getOp()) {
5975 case glslang::EOpLogicalNot:
5976 case glslang::EOpConvIntToBool:
5977 case glslang::EOpConvUintToBool:
5978 case glslang::EOpConvFloatToBool:
5979 case glslang::EOpConvDoubleToBool:
5980 case glslang::EOpEqual:
5981 case glslang::EOpNotEqual:
5982 case glslang::EOpLessThan:
5983 case glslang::EOpGreaterThan:
5984 case glslang::EOpLessThanEqual:
5985 case glslang::EOpGreaterThanEqual:
5986 case glslang::EOpIndexDirect:
5987 case glslang::EOpIndexDirectStruct:
5988 case glslang::EOpLogicalXor:
5989 case glslang::EOpAny:
5990 case glslang::EOpAll:
5991 return true;
5992 default:
5993 return false;
5994 }
5995}
5996
5997// Emit short-circuiting code, where 'right' is never evaluated unless
5998// the left side is true (for &&) or false (for ||).
5999spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6000{
6001 spv::Id boolTypeId = builder.makeBoolType();
6002
6003 // emit left operand
6004 builder.clearAccessChain();
6005 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006006 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006007
6008 // Operands to accumulate OpPhi operands
6009 std::vector<spv::Id> phiOperands;
6010 // accumulate left operand's phi information
6011 phiOperands.push_back(leftId);
6012 phiOperands.push_back(builder.getBuildPoint()->getId());
6013
6014 // Make the two kinds of operation symmetric with a "!"
6015 // || => emit "if (! left) result = right"
6016 // && => emit "if ( left) result = right"
6017 //
6018 // TODO: this runtime "not" for || could be avoided by adding functionality
6019 // to 'builder' to have an "else" without an "then"
6020 if (op == glslang::EOpLogicalOr)
6021 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6022
6023 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006024 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006025
6026 // emit right operand as the "then" part of the "if"
6027 builder.clearAccessChain();
6028 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006029 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006030
6031 // accumulate left operand's phi information
6032 phiOperands.push_back(rightId);
6033 phiOperands.push_back(builder.getBuildPoint()->getId());
6034
6035 // finish the "if"
6036 ifBuilder.makeEndIf();
6037
6038 // phi together the two results
6039 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6040}
6041
Frank Henigman541f7bb2018-01-16 00:18:26 -05006042#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006043// Return type Id of the imported set of extended instructions corresponds to the name.
6044// Import this set if it has not been imported yet.
6045spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6046{
6047 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6048 return extBuiltinMap[name];
6049 else {
Rex Xu51596642016-09-21 18:56:12 +08006050 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006051 spv::Id extBuiltins = builder.import(name);
6052 extBuiltinMap[name] = extBuiltins;
6053 return extBuiltins;
6054 }
6055}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006056#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006057
John Kessenich140f3df2015-06-26 16:58:36 -06006058}; // end anonymous namespace
6059
6060namespace glslang {
6061
John Kessenich68d78fd2015-07-12 19:28:10 -06006062void GetSpirvVersion(std::string& version)
6063{
John Kessenich9e55f632015-07-15 10:03:39 -06006064 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006065 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006066 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006067 version = buf;
6068}
6069
John Kessenicha372a3e2017-11-02 22:32:14 -06006070// For low-order part of the generator's magic number. Bump up
6071// when there is a change in the style (e.g., if SSA form changes,
6072// or a different instruction sequence to do something gets used).
6073int GetSpirvGeneratorVersion()
6074{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006075 // return 1; // start
6076 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006077 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
6078 return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenicha372a3e2017-11-02 22:32:14 -06006079}
6080
John Kessenich140f3df2015-06-26 16:58:36 -06006081// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006082void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006083{
6084 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006085 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006086 if (out.fail())
6087 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006088 for (int i = 0; i < (int)spirv.size(); ++i) {
6089 unsigned int word = spirv[i];
6090 out.write((const char*)&word, 4);
6091 }
6092 out.close();
6093}
6094
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006095// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006096void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006097{
6098 std::ofstream out;
6099 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006100 if (out.fail())
6101 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006102 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006103 if (varName != nullptr) {
6104 out << "\t #pragma once" << std::endl;
6105 out << "const uint32_t " << varName << "[] = {" << std::endl;
6106 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006107 const int WORDS_PER_LINE = 8;
6108 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6109 out << "\t";
6110 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6111 const unsigned int word = spirv[i + j];
6112 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6113 if (i + j + 1 < (int)spirv.size()) {
6114 out << ",";
6115 }
6116 }
6117 out << std::endl;
6118 }
Flavio15017db2017-02-15 14:29:33 -08006119 if (varName != nullptr) {
6120 out << "};";
6121 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006122 out.close();
6123}
6124
GregFcd1f1692017-09-21 18:40:22 -06006125#ifdef ENABLE_OPT
6126void errHandler(const std::string& str) {
6127 std::cerr << str << std::endl;
6128}
6129#endif
6130
John Kessenich140f3df2015-06-26 16:58:36 -06006131//
6132// Set up the glslang traversal
6133//
John Kessenich121853f2017-05-31 17:11:16 -06006134void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006135{
Lei Zhang17535f72016-05-04 15:55:59 -04006136 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006137 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006138}
6139
John Kessenich121853f2017-05-31 17:11:16 -06006140void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6141 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006142{
John Kessenich140f3df2015-06-26 16:58:36 -06006143 TIntermNode* root = intermediate.getTreeRoot();
6144
6145 if (root == 0)
6146 return;
6147
John Kessenich121853f2017-05-31 17:11:16 -06006148 glslang::SpvOptions defaultOptions;
6149 if (options == nullptr)
6150 options = &defaultOptions;
6151
John Kessenich140f3df2015-06-26 16:58:36 -06006152 glslang::GetThreadPoolAllocator().push();
6153
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006154 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006155 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006156 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006157 it.dumpSpv(spirv);
6158
GregFcd1f1692017-09-21 18:40:22 -06006159#ifdef ENABLE_OPT
6160 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6161 // eg. forward and remove memory writes of opaque types.
6162 if ((intermediate.getSource() == EShSourceHlsl ||
6163 options->optimizeSize) &&
6164 !options->disableOptimizer) {
6165 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6166
6167 spvtools::Optimizer optimizer(target_env);
6168 optimizer.SetMessageConsumer([](spv_message_level_t level,
6169 const char* source,
6170 const spv_position_t& position,
6171 const char* message) {
6172 std::cerr << StringifyMessage(level, source, position, message)
6173 << std::endl;
6174 });
6175
6176 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006177 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6178 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006179 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6180 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6181 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6182 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006183 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006184 optimizer.RegisterPass(CreateAggressiveDCEPass());
6185 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006186 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006187 optimizer.RegisterPass(CreateBlockMergePass());
6188 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6189 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006190 optimizer.RegisterPass(CreateDeadInsertElimPass());
6191 if (options->optimizeSize) {
6192 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6193 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6194 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6195 }
GregFcd1f1692017-09-21 18:40:22 -06006196 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006197
6198 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6199 return;
6200
6201 // Remove dead module-level objects: functions, types, vars
6202 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6203 spv::spirvbin_t Remapper(0);
6204 Remapper.registerErrorHandler(errHandler);
6205 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6206 }
6207#endif
6208
John Kessenich140f3df2015-06-26 16:58:36 -06006209 glslang::GetThreadPoolAllocator().pop();
6210}
6211
6212}; // end namespace glslang