blob: 92c60a8ca783c531b50846ac6ea6806fa36083ae [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);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002343#ifdef AMD_EXTENSIONS
2344 case glslang::EbtFloat16:
2345 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2346 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2347 return builder.makeFloatType(16);
2348#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002349 case glslang::EbtInt: return builder.makeIntType(32);
2350 case glslang::EbtUint: return builder.makeUintType(32);
2351 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002352 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002353 return builder.makeFloatType(32);
2354 }
2355}
2356
John Kessenich8c8505c2016-07-26 12:50:38 -06002357// If node is a swizzle operation, return the type that should be used if
2358// the swizzle base is first consumed by another operation, before the swizzle
2359// is applied.
2360spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2361{
John Kessenichecba76f2017-01-06 00:34:48 -07002362 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002363 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2364 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2365 else
2366 return spv::NoType;
2367}
2368
2369// When inverting a swizzle with a parent op, this function
2370// will apply the swizzle operation to a completed parent operation.
2371spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2372{
2373 std::vector<unsigned> swizzle;
2374 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2375 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2376}
2377
John Kessenich8c8505c2016-07-26 12:50:38 -06002378// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2379void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2380{
2381 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2382 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2383 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2384}
2385
John Kessenich3ac051e2015-12-20 11:29:16 -07002386// Convert from a glslang type to an SPV type, by calling into a
2387// recursive version of this function. This establishes the inherited
2388// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002389spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2390{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002391 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002392}
2393
2394// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002395// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002396// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002397spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002398{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002399 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002400
2401 switch (type.getBasicType()) {
2402 case glslang::EbtVoid:
2403 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002404 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002405 break;
2406 case glslang::EbtFloat:
2407 spvType = builder.makeFloatType(32);
2408 break;
2409 case glslang::EbtDouble:
2410 spvType = builder.makeFloatType(64);
2411 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002412#ifdef AMD_EXTENSIONS
2413 case glslang::EbtFloat16:
2414 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002415 spvType = builder.makeFloatType(16);
2416 break;
2417#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002418 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002419 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2420 // a 32-bit int where non-0 means true.
2421 if (explicitLayout != glslang::ElpNone)
2422 spvType = builder.makeUintType(32);
2423 else
2424 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002425 break;
2426 case glslang::EbtInt:
2427 spvType = builder.makeIntType(32);
2428 break;
2429 case glslang::EbtUint:
2430 spvType = builder.makeUintType(32);
2431 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002432 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002433 spvType = builder.makeIntType(64);
2434 break;
2435 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002436 spvType = builder.makeUintType(64);
2437 break;
Rex Xucabbb782017-03-24 13:41:14 +08002438#ifdef AMD_EXTENSIONS
2439 case glslang::EbtInt16:
2440 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2441 spvType = builder.makeIntType(16);
2442 break;
2443 case glslang::EbtUint16:
2444 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2445 spvType = builder.makeUintType(16);
2446 break;
2447#endif
John Kessenich426394d2015-07-23 10:22:48 -06002448 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002449 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002450 spvType = builder.makeUintType(32);
2451 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 case glslang::EbtSampler:
2453 {
2454 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002455 if (sampler.sampler) {
2456 // pure sampler
2457 spvType = builder.makeSamplerType();
2458 } else {
2459 // an image is present, make its type
2460 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2461 sampler.image ? 2 : 1, TranslateImageFormat(type));
2462 if (sampler.combined) {
2463 // already has both image and sampler, make the combined type
2464 spvType = builder.makeSampledImageType(spvType);
2465 }
John Kessenich55e7d112015-11-15 21:33:39 -07002466 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002467 }
John Kessenich140f3df2015-06-26 16:58:36 -06002468 break;
2469 case glslang::EbtStruct:
2470 case glslang::EbtBlock:
2471 {
2472 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002473 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002474
2475 // Try to share structs for different layouts, but not yet for other
2476 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002477 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002478 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002479 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002480 break;
2481
2482 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002483 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002484 memberRemapper[glslangMembers].resize(glslangMembers->size());
2485 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002486 }
2487 break;
2488 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002489 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002490 break;
2491 }
2492
2493 if (type.isMatrix())
2494 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2495 else {
2496 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2497 if (type.getVectorSize() > 1)
2498 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2499 }
2500
2501 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002502 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2503
John Kessenichc9a80832015-09-12 12:17:44 -06002504 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002505 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002506 // We need to decorate array strides for types needing explicit layout, except blocks.
2507 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002508 // Use a dummy glslang type for querying internal strides of
2509 // arrays of arrays, but using just a one-dimensional array.
2510 glslang::TType simpleArrayType(type, 0); // deference type of the array
2511 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2512 simpleArrayType.getArraySizes().dereference();
2513
2514 // Will compute the higher-order strides here, rather than making a whole
2515 // pile of types and doing repetitive recursion on their contents.
2516 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2517 }
John Kessenichf8842e52016-01-04 19:22:56 -07002518
2519 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002520 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002521 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002522 if (stride > 0)
2523 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002524 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002525 }
2526 } else {
2527 // single-dimensional array, and don't yet have stride
2528
John Kessenichf8842e52016-01-04 19:22:56 -07002529 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002530 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2531 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002532 }
John Kessenich31ed4832015-09-09 17:51:38 -06002533
John Kessenichc9a80832015-09-12 12:17:44 -06002534 // Do the outer dimension, which might not be known for a runtime-sized array
2535 if (type.isRuntimeSizedArray()) {
2536 spvType = builder.makeRuntimeArray(spvType);
2537 } else {
2538 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002539 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002540 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002541 if (stride > 0)
2542 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002543 }
2544
2545 return spvType;
2546}
2547
John Kessenich0e737842017-03-24 18:38:16 -06002548// TODO: this functionality should exist at a higher level, in creating the AST
2549//
2550// Identify interface members that don't have their required extension turned on.
2551//
2552bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2553{
2554 auto& extensions = glslangIntermediate->getRequestedExtensions();
2555
Rex Xubcf291a2017-03-29 23:01:36 +08002556 if (member.getFieldName() == "gl_ViewportMask" &&
2557 extensions.find("GL_NV_viewport_array2") == extensions.end())
2558 return true;
2559 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2560 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2561 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002562 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2563 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2564 return true;
2565 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2566 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2567 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002568 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2569 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2570 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002571
2572 return false;
2573};
2574
John Kessenich6090df02016-06-30 21:18:02 -06002575// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2576// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2577// Mutually recursive with convertGlslangToSpvType().
2578spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2579 const glslang::TTypeList* glslangMembers,
2580 glslang::TLayoutPacking explicitLayout,
2581 const glslang::TQualifier& qualifier)
2582{
2583 // Create a vector of struct types for SPIR-V to consume
2584 std::vector<spv::Id> spvMembers;
2585 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 -06002586 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2587 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2588 if (glslangMember.hiddenMember()) {
2589 ++memberDelta;
2590 if (type.getBasicType() == glslang::EbtBlock)
2591 memberRemapper[glslangMembers][i] = -1;
2592 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002593 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002594 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002595 if (filterMember(glslangMember))
2596 continue;
2597 }
John Kessenich6090df02016-06-30 21:18:02 -06002598 // modify just this child's view of the qualifier
2599 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2600 InheritQualifiers(memberQualifier, qualifier);
2601
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002602 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002603 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002604 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002605
2606 // recurse
2607 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2608 }
2609 }
2610
2611 // Make the SPIR-V type
2612 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002613 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002614 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2615
2616 // Decorate it
2617 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2618
2619 return spvType;
2620}
2621
2622void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2623 const glslang::TTypeList* glslangMembers,
2624 glslang::TLayoutPacking explicitLayout,
2625 const glslang::TQualifier& qualifier,
2626 spv::Id spvType)
2627{
2628 // Name and decorate the non-hidden members
2629 int offset = -1;
2630 int locationOffset = 0; // for use within the members of this struct
2631 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2632 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2633 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002634 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002635 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002636 if (filterMember(glslangMember))
2637 continue;
2638 }
John Kessenich6090df02016-06-30 21:18:02 -06002639
2640 // modify just this child's view of the qualifier
2641 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2642 InheritQualifiers(memberQualifier, qualifier);
2643
2644 // using -1 above to indicate a hidden member
2645 if (member >= 0) {
2646 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2647 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2648 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2649 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002650 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2651 type.getQualifier().storage == glslang::EvqVaryingOut) {
2652 if (type.getBasicType() == glslang::EbtBlock ||
2653 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002654 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2655 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2656 }
2657 }
2658 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2659
Rex Xu286ca432017-07-27 14:33:16 +08002660 if (type.getBasicType() == glslang::EbtBlock &&
2661 qualifier.storage == glslang::EvqBuffer) {
2662 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002663 std::vector<spv::Decoration> memory;
2664 TranslateMemoryDecoration(memberQualifier, memory);
2665 for (unsigned int i = 0; i < memory.size(); ++i)
2666 addMemberDecoration(spvType, member, memory[i]);
2667 }
2668
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002669 // Location assignment was already completed correctly by the front end,
2670 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002671 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002672 // ill-specified and decisions have been made to not allow this.
2673 if (! type.isArray() && memberQualifier.hasLocation())
2674 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002675
John Kessenich2f47bc92016-06-30 21:47:35 -06002676 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenichc5215792018-02-27 13:23:08 -07002677 locationOffset += glslangIntermediate->computeTypeLocationSize(
2678 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002679
John Kessenich6090df02016-06-30 21:18:02 -06002680 // component, XFB, others
2681 if (glslangMember.getQualifier().hasComponent())
2682 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2683 if (glslangMember.getQualifier().hasXfbOffset())
2684 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2685 else if (explicitLayout != glslang::ElpNone) {
2686 // figure out what to do with offset, which is accumulating
2687 int nextOffset;
2688 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2689 if (offset >= 0)
2690 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2691 offset = nextOffset;
2692 }
2693
2694 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2695 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2696
2697 // built-in variable decorations
2698 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002699 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002700 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002701
2702#ifdef NV_EXTENSIONS
2703 if (builtIn == spv::BuiltInLayer) {
2704 // SPV_NV_viewport_array2 extension
2705 if (glslangMember.getQualifier().layoutViewportRelative){
2706 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2707 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2708 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2709 }
2710 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2711 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2712 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2713 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2714 }
2715 }
chaocdf3956c2017-02-14 14:52:34 -08002716 if (glslangMember.getQualifier().layoutPassthrough) {
2717 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2718 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2719 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2720 }
chaoc771d89f2017-01-13 01:10:53 -08002721#endif
John Kessenich6090df02016-06-30 21:18:02 -06002722 }
2723 }
2724
2725 // Decorate the structure
2726 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002727 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002728 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2729 builder.addCapability(spv::CapabilityGeometryStreams);
2730 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2731 }
John Kessenich6090df02016-06-30 21:18:02 -06002732}
2733
John Kessenich6c292d32016-02-15 20:58:50 -07002734// Turn the expression forming the array size into an id.
2735// This is not quite trivial, because of specialization constants.
2736// Sometimes, a raw constant is turned into an Id, and sometimes
2737// a specialization constant expression is.
2738spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2739{
2740 // First, see if this is sized with a node, meaning a specialization constant:
2741 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2742 if (specNode != nullptr) {
2743 builder.clearAccessChain();
2744 specNode->traverse(this);
2745 return accessChainLoad(specNode->getAsTyped()->getType());
2746 }
qining25262b32016-05-06 17:25:16 -04002747
John Kessenich6c292d32016-02-15 20:58:50 -07002748 // Otherwise, need a compile-time (front end) size, get it:
2749 int size = arraySizes.getDimSize(dim);
2750 assert(size > 0);
2751 return builder.makeUintConstant(size);
2752}
2753
John Kessenich103bef92016-02-08 21:38:15 -07002754// Wrap the builder's accessChainLoad to:
2755// - localize handling of RelaxedPrecision
2756// - use the SPIR-V inferred type instead of another conversion of the glslang type
2757// (avoids unnecessary work and possible type punning for structures)
2758// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002759spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2760{
John Kessenich103bef92016-02-08 21:38:15 -07002761 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2762 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2763
2764 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002765 if (type.getBasicType() == glslang::EbtBool) {
2766 if (builder.isScalarType(nominalTypeId)) {
2767 // Conversion for bool
2768 spv::Id boolType = builder.makeBoolType();
2769 if (nominalTypeId != boolType)
2770 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2771 } else if (builder.isVectorType(nominalTypeId)) {
2772 // Conversion for bvec
2773 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2774 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2775 if (nominalTypeId != bvecType)
2776 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2777 }
2778 }
John Kessenich103bef92016-02-08 21:38:15 -07002779
2780 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002781}
2782
Rex Xu27253232016-02-23 17:51:09 +08002783// Wrap the builder's accessChainStore to:
2784// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002785//
2786// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002787void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2788{
2789 // Need to convert to abstract types when necessary
2790 if (type.getBasicType() == glslang::EbtBool) {
2791 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2792
2793 if (builder.isScalarType(nominalTypeId)) {
2794 // Conversion for bool
2795 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002796 if (nominalTypeId != boolType) {
2797 // keep these outside arguments, for determinant order-of-evaluation
2798 spv::Id one = builder.makeUintConstant(1);
2799 spv::Id zero = builder.makeUintConstant(0);
2800 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2801 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002802 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002803 } else if (builder.isVectorType(nominalTypeId)) {
2804 // Conversion for bvec
2805 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2806 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002807 if (nominalTypeId != bvecType) {
2808 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002809 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2810 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2811 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002812 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002813 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2814 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002815 }
2816 }
2817
2818 builder.accessChainStore(rvalue);
2819}
2820
John Kessenich4bf71552016-09-02 11:20:21 -06002821// For storing when types match at the glslang level, but not might match at the
2822// SPIR-V level.
2823//
2824// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002825// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002826// as in a member-decorated way.
2827//
2828// NOTE: This function can handle any store request; if it's not special it
2829// simplifies to a simple OpStore.
2830//
2831// Implicitly uses the existing builder.accessChain as the storage target.
2832void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2833{
John Kessenichb3e24e42016-09-11 12:33:43 -06002834 // we only do the complex path here if it's an aggregate
2835 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002836 accessChainStore(type, rValue);
2837 return;
2838 }
2839
John Kessenichb3e24e42016-09-11 12:33:43 -06002840 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002841 spv::Id rType = builder.getTypeId(rValue);
2842 spv::Id lValue = builder.accessChainGetLValue();
2843 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2844 if (lType == rType) {
2845 accessChainStore(type, rValue);
2846 return;
2847 }
2848
John Kessenichb3e24e42016-09-11 12:33:43 -06002849 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002850 // where the two types were the same type in GLSL. This requires member
2851 // by member copy, recursively.
2852
John Kessenichb3e24e42016-09-11 12:33:43 -06002853 // If an array, copy element by element.
2854 if (type.isArray()) {
2855 glslang::TType glslangElementType(type, 0);
2856 spv::Id elementRType = builder.getContainedTypeId(rType);
2857 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2858 // get the source member
2859 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002860
John Kessenichb3e24e42016-09-11 12:33:43 -06002861 // set up the target storage
2862 builder.clearAccessChain();
2863 builder.setAccessChainLValue(lValue);
2864 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002865
John Kessenichb3e24e42016-09-11 12:33:43 -06002866 // store the member
2867 multiTypeStore(glslangElementType, elementRValue);
2868 }
2869 } else {
2870 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002871
John Kessenichb3e24e42016-09-11 12:33:43 -06002872 // loop over structure members
2873 const glslang::TTypeList& members = *type.getStruct();
2874 for (int m = 0; m < (int)members.size(); ++m) {
2875 const glslang::TType& glslangMemberType = *members[m].type;
2876
2877 // get the source member
2878 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2879 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2880
2881 // set up the target storage
2882 builder.clearAccessChain();
2883 builder.setAccessChainLValue(lValue);
2884 builder.accessChainPush(builder.makeIntConstant(m));
2885
2886 // store the member
2887 multiTypeStore(glslangMemberType, memberRValue);
2888 }
John Kessenich4bf71552016-09-02 11:20:21 -06002889 }
2890}
2891
John Kessenichf85e8062015-12-19 13:57:10 -07002892// Decide whether or not this type should be
2893// decorated with offsets and strides, and if so
2894// whether std140 or std430 rules should be applied.
2895glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002896{
John Kessenichf85e8062015-12-19 13:57:10 -07002897 // has to be a block
2898 if (type.getBasicType() != glslang::EbtBlock)
2899 return glslang::ElpNone;
2900
2901 // has to be a uniform or buffer block
2902 if (type.getQualifier().storage != glslang::EvqUniform &&
2903 type.getQualifier().storage != glslang::EvqBuffer)
2904 return glslang::ElpNone;
2905
2906 // return the layout to use
2907 switch (type.getQualifier().layoutPacking) {
2908 case glslang::ElpStd140:
2909 case glslang::ElpStd430:
2910 return type.getQualifier().layoutPacking;
2911 default:
2912 return glslang::ElpNone;
2913 }
John Kessenich31ed4832015-09-09 17:51:38 -06002914}
2915
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002916// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002917int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002918{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002919 int size;
John Kessenich49987892015-12-29 17:11:44 -07002920 int stride;
2921 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002922
2923 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002924}
2925
John Kessenich49987892015-12-29 17:11:44 -07002926// 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 -07002927// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002928int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002929{
John Kessenich49987892015-12-29 17:11:44 -07002930 glslang::TType elementType;
2931 elementType.shallowCopy(matrixType);
2932 elementType.clearArraySizes();
2933
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002934 int size;
John Kessenich49987892015-12-29 17:11:44 -07002935 int stride;
2936 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2937
2938 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002939}
2940
John Kessenich5e4b1242015-08-06 22:53:06 -06002941// Given a member type of a struct, realign the current offset for it, and compute
2942// the next (not yet aligned) offset for the next member, which will get aligned
2943// on the next call.
2944// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2945// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2946// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002947void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002948 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002949{
2950 // this will get a positive value when deemed necessary
2951 nextOffset = -1;
2952
John Kessenich5e4b1242015-08-06 22:53:06 -06002953 // override anything in currentOffset with user-set offset
2954 if (memberType.getQualifier().hasOffset())
2955 currentOffset = memberType.getQualifier().layoutOffset;
2956
2957 // It could be that current linker usage in glslang updated all the layoutOffset,
2958 // in which case the following code does not matter. But, that's not quite right
2959 // once cross-compilation unit GLSL validation is done, as the original user
2960 // settings are needed in layoutOffset, and then the following will come into play.
2961
John Kessenichf85e8062015-12-19 13:57:10 -07002962 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002963 if (! memberType.getQualifier().hasOffset())
2964 currentOffset = -1;
2965
2966 return;
2967 }
2968
John Kessenichf85e8062015-12-19 13:57:10 -07002969 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002970 if (currentOffset < 0)
2971 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002972
John Kessenich5e4b1242015-08-06 22:53:06 -06002973 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2974 // but possibly not yet correctly aligned.
2975
2976 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002977 int dummyStride;
2978 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002979
2980 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002981 // TODO: make this consistent in early phases of code:
2982 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2983 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2984 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002985 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002986 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002987 int dummySize;
2988 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2989 if (componentAlignment <= 4)
2990 memberAlignment = componentAlignment;
2991 }
2992
2993 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002994 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002995
2996 // Bump up to vec4 if there is a bad straddle
2997 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2998 glslang::RoundToPow2(currentOffset, 16);
2999
John Kessenich5e4b1242015-08-06 22:53:06 -06003000 nextOffset = currentOffset + memberSize;
3001}
3002
David Netoa901ffe2016-06-08 14:11:40 +01003003void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003004{
David Netoa901ffe2016-06-08 14:11:40 +01003005 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3006 switch (glslangBuiltIn)
3007 {
3008 case glslang::EbvClipDistance:
3009 case glslang::EbvCullDistance:
3010 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003011#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003012 case glslang::EbvViewportMaskNV:
3013 case glslang::EbvSecondaryPositionNV:
3014 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003015 case glslang::EbvPositionPerViewNV:
3016 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003017#endif
David Netoa901ffe2016-06-08 14:11:40 +01003018 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3019 // Alternately, we could just call this for any glslang built-in, since the
3020 // capability already guards against duplicates.
3021 TranslateBuiltInDecoration(glslangBuiltIn, false);
3022 break;
3023 default:
3024 // Capabilities were already generated when the struct was declared.
3025 break;
3026 }
John Kessenichebb50532016-05-16 19:22:05 -06003027}
3028
John Kessenich6fccb3c2016-09-19 16:01:41 -06003029bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003030{
John Kessenicheee9d532016-09-19 18:09:30 -06003031 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003032}
3033
John Kessenichd41993d2017-09-10 15:21:05 -06003034// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003035// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3036// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003037bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3038{
John Kessenich6a14f782017-12-04 02:48:10 -07003039 assert(qualifier == glslang::EvqIn ||
3040 qualifier == glslang::EvqOut ||
3041 qualifier == glslang::EvqInOut ||
3042 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003043 return qualifier != glslang::EvqConstReadOnly;
3044}
3045
3046// Is parameter pass-by-original?
3047bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3048 bool implicitThisParam)
3049{
3050 if (implicitThisParam) // implicit this
3051 return true;
3052 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003053 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003054 return paramType.containsOpaque() || // sampler, etc.
3055 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3056}
3057
John Kessenich140f3df2015-06-26 16:58:36 -06003058// Make all the functions, skeletally, without actually visiting their bodies.
3059void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3060{
John Kessenichfad62972017-07-18 02:35:46 -06003061 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3062 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3063 if (paramPrecision != spv::NoPrecision)
3064 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003065 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003066 };
3067
John Kessenich140f3df2015-06-26 16:58:36 -06003068 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3069 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003070 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003071 continue;
3072
3073 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003074 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003075 //
qining25262b32016-05-06 17:25:16 -04003076 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003077 // function. What it is an address of varies:
3078 //
John Kessenich4bf71552016-09-02 11:20:21 -06003079 // - "in" parameters not marked as "const" can be written to without modifying the calling
3080 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003081 //
3082 // - "const in" parameters can just be the r-value, as no writes need occur.
3083 //
John Kessenich4bf71552016-09-02 11:20:21 -06003084 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3085 // 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 -06003086
3087 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003088 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003089 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3090
John Kessenichfad62972017-07-18 02:35:46 -06003091 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3092 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003093
John Kessenichfad62972017-07-18 02:35:46 -06003094 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003095 for (int p = 0; p < (int)parameters.size(); ++p) {
3096 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3097 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003098 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003099 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003100 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003101 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3102 else
John Kessenich4bf71552016-09-02 11:20:21 -06003103 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003104 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003105 paramTypes.push_back(typeId);
3106 }
3107
3108 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003109 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3110 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003111 glslFunction->getName().c_str(), paramTypes,
3112 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003113 if (implicitThis)
3114 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003115
3116 // Track function to emit/call later
3117 functionMap[glslFunction->getName().c_str()] = function;
3118
3119 // Set the parameter id's
3120 for (int p = 0; p < (int)parameters.size(); ++p) {
3121 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3122 // give a name too
3123 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3124 }
3125 }
3126}
3127
3128// Process all the initializers, while skipping the functions and link objects
3129void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3130{
3131 builder.setBuildPoint(shaderEntry->getLastBlock());
3132 for (int i = 0; i < (int)initializers.size(); ++i) {
3133 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3134 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3135
3136 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003137 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003138 initializer->traverse(this);
3139 }
3140 }
3141}
3142
3143// Process all the functions, while skipping initializers.
3144void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3145{
3146 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3147 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003148 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003149 node->traverse(this);
3150 }
3151}
3152
3153void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3154{
qining25262b32016-05-06 17:25:16 -04003155 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003156 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003157 currentFunction = functionMap[node->getName().c_str()];
3158 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003159 builder.setBuildPoint(functionBlock);
3160}
3161
Rex Xu04db3f52015-09-16 11:44:02 +08003162void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003163{
Rex Xufc618912015-09-09 16:42:49 +08003164 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003165
3166 glslang::TSampler sampler = {};
3167 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003168#ifdef AMD_EXTENSIONS
3169 bool f16ShadowCompare = false;
3170#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003171 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003172 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3173 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003174#ifdef AMD_EXTENSIONS
3175 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3176#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003177 }
3178
John Kessenich140f3df2015-06-26 16:58:36 -06003179 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3180 builder.clearAccessChain();
3181 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003182
3183 // Special case l-value operands
3184 bool lvalue = false;
3185 switch (node.getOp()) {
3186 case glslang::EOpImageAtomicAdd:
3187 case glslang::EOpImageAtomicMin:
3188 case glslang::EOpImageAtomicMax:
3189 case glslang::EOpImageAtomicAnd:
3190 case glslang::EOpImageAtomicOr:
3191 case glslang::EOpImageAtomicXor:
3192 case glslang::EOpImageAtomicExchange:
3193 case glslang::EOpImageAtomicCompSwap:
3194 if (i == 0)
3195 lvalue = true;
3196 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003197 case glslang::EOpSparseImageLoad:
3198 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3199 lvalue = true;
3200 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003201#ifdef AMD_EXTENSIONS
3202 case glslang::EOpSparseTexture:
3203 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3204 lvalue = true;
3205 break;
3206 case glslang::EOpSparseTextureClamp:
3207 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3208 lvalue = true;
3209 break;
3210 case glslang::EOpSparseTextureLod:
3211 case glslang::EOpSparseTextureOffset:
3212 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3213 lvalue = true;
3214 break;
3215#else
Rex Xu48edadf2015-12-31 16:11:41 +08003216 case glslang::EOpSparseTexture:
3217 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3218 lvalue = true;
3219 break;
3220 case glslang::EOpSparseTextureClamp:
3221 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3222 lvalue = true;
3223 break;
3224 case glslang::EOpSparseTextureLod:
3225 case glslang::EOpSparseTextureOffset:
3226 if (i == 3)
3227 lvalue = true;
3228 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003229#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003230 case glslang::EOpSparseTextureFetch:
3231 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3232 lvalue = true;
3233 break;
3234 case glslang::EOpSparseTextureFetchOffset:
3235 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3236 lvalue = true;
3237 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003238#ifdef AMD_EXTENSIONS
3239 case glslang::EOpSparseTextureLodOffset:
3240 case glslang::EOpSparseTextureGrad:
3241 case glslang::EOpSparseTextureOffsetClamp:
3242 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3243 lvalue = true;
3244 break;
3245 case glslang::EOpSparseTextureGradOffset:
3246 case glslang::EOpSparseTextureGradClamp:
3247 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3248 lvalue = true;
3249 break;
3250 case glslang::EOpSparseTextureGradOffsetClamp:
3251 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3252 lvalue = true;
3253 break;
3254#else
Rex Xu48edadf2015-12-31 16:11:41 +08003255 case glslang::EOpSparseTextureLodOffset:
3256 case glslang::EOpSparseTextureGrad:
3257 case glslang::EOpSparseTextureOffsetClamp:
3258 if (i == 4)
3259 lvalue = true;
3260 break;
3261 case glslang::EOpSparseTextureGradOffset:
3262 case glslang::EOpSparseTextureGradClamp:
3263 if (i == 5)
3264 lvalue = true;
3265 break;
3266 case glslang::EOpSparseTextureGradOffsetClamp:
3267 if (i == 6)
3268 lvalue = true;
3269 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003270#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003271 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003272 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3273 lvalue = true;
3274 break;
3275 case glslang::EOpSparseTextureGatherOffset:
3276 case glslang::EOpSparseTextureGatherOffsets:
3277 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3278 lvalue = true;
3279 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003280#ifdef AMD_EXTENSIONS
3281 case glslang::EOpSparseTextureGatherLod:
3282 if (i == 3)
3283 lvalue = true;
3284 break;
3285 case glslang::EOpSparseTextureGatherLodOffset:
3286 case glslang::EOpSparseTextureGatherLodOffsets:
3287 if (i == 4)
3288 lvalue = true;
3289 break;
Rex Xu129799a2017-07-05 17:23:28 +08003290 case glslang::EOpSparseImageLoadLod:
3291 if (i == 3)
3292 lvalue = true;
3293 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003294#endif
Rex Xufc618912015-09-09 16:42:49 +08003295 default:
3296 break;
3297 }
3298
Rex Xu6b86d492015-09-16 17:48:22 +08003299 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003300 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003301 else
John Kessenich32cfd492016-02-02 12:37:46 -07003302 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003303 }
3304}
3305
John Kessenichfc51d282015-08-19 13:34:18 -06003306void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003307{
John Kessenichfc51d282015-08-19 13:34:18 -06003308 builder.clearAccessChain();
3309 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003310 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003311}
John Kessenich140f3df2015-06-26 16:58:36 -06003312
John Kessenichfc51d282015-08-19 13:34:18 -06003313spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3314{
John Kesseniche485c7a2017-05-31 18:50:53 -06003315 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003316 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003317
3318 builder.setLine(node->getLoc().line);
3319
John Kessenichfc51d282015-08-19 13:34:18 -06003320 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003321 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3322 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003323#ifdef AMD_EXTENSIONS
3324 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3325 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3326 : false;
3327#endif
3328
John Kessenichfc51d282015-08-19 13:34:18 -06003329 std::vector<spv::Id> arguments;
3330 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003331 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003332 else
3333 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003334 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003335
3336 spv::Builder::TextureParameters params = { };
3337 params.sampler = arguments[0];
3338
Rex Xu04db3f52015-09-16 11:44:02 +08003339 glslang::TCrackedTextureOp cracked;
3340 node->crackTexture(sampler, cracked);
3341
amhagan05506bb2017-06-13 16:53:02 -04003342 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003343
John Kessenichfc51d282015-08-19 13:34:18 -06003344 // Check for queries
3345 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003346 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3347 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003348 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003349
John Kessenichfc51d282015-08-19 13:34:18 -06003350 switch (node->getOp()) {
3351 case glslang::EOpImageQuerySize:
3352 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003353 if (arguments.size() > 1) {
3354 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003355 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003356 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003357 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003358 case glslang::EOpImageQuerySamples:
3359 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003360 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003361 case glslang::EOpTextureQueryLod:
3362 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003363 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003364 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003365 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003366 case glslang::EOpSparseTexelsResident:
3367 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003368 default:
3369 assert(0);
3370 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 }
John Kessenich140f3df2015-06-26 16:58:36 -06003372 }
3373
LoopDawg4425f242018-02-18 11:40:01 -07003374 int components = node->getType().getVectorSize();
3375
3376 if (node->getOp() == glslang::EOpTextureFetch) {
3377 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3378 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3379 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3380 // here around e.g. which ones return scalars or other types.
3381 components = 4;
3382 }
3383
3384 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3385
3386 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3387
Rex Xufc618912015-09-09 16:42:49 +08003388 // Check for image functions other than queries
3389 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003390 std::vector<spv::Id> operands;
3391 auto opIt = arguments.begin();
3392 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003393
3394 // Handle subpass operations
3395 // TODO: GLSL should change to have the "MS" only on the type rather than the
3396 // built-in function.
3397 if (cracked.subpass) {
3398 // add on the (0,0) coordinate
3399 spv::Id zero = builder.makeIntConstant(0);
3400 std::vector<spv::Id> comps;
3401 comps.push_back(zero);
3402 comps.push_back(zero);
3403 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3404 if (sampler.ms) {
3405 operands.push_back(spv::ImageOperandsSampleMask);
3406 operands.push_back(*(opIt++));
3407 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003408 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3409 builder.setPrecision(result, precision);
3410 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003411 }
3412
John Kessenich56bab042015-09-16 10:54:31 -06003413 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003414#ifdef AMD_EXTENSIONS
3415 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3416#else
John Kessenich56bab042015-09-16 10:54:31 -06003417 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003418#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003419 if (sampler.ms) {
3420 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003421 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003422#ifdef AMD_EXTENSIONS
3423 } else if (cracked.lod) {
3424 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3425 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3426
3427 operands.push_back(spv::ImageOperandsLodMask);
3428 operands.push_back(*opIt);
3429#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003430 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003431 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3432 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003433
LoopDawg4425f242018-02-18 11:40:01 -07003434 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3435 builder.setPrecision(result[0], precision);
3436
3437 // If needed, add a conversion constructor to the proper size.
3438 if (components != node->getType().getVectorSize())
3439 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3440
3441 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003442#ifdef AMD_EXTENSIONS
3443 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3444#else
John Kessenich56bab042015-09-16 10:54:31 -06003445 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003446#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003447 if (sampler.ms) {
3448 operands.push_back(*(opIt + 1));
3449 operands.push_back(spv::ImageOperandsSampleMask);
3450 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003451#ifdef AMD_EXTENSIONS
3452 } else if (cracked.lod) {
3453 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3454 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3455
3456 operands.push_back(*(opIt + 1));
3457 operands.push_back(spv::ImageOperandsLodMask);
3458 operands.push_back(*opIt);
3459#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003460 } else
3461 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003462 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003463 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3464 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003465 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003466#ifdef AMD_EXTENSIONS
3467 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3468#else
Rex Xu5eafa472016-02-19 22:24:03 +08003469 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003470#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003471 builder.addCapability(spv::CapabilitySparseResidency);
3472 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3473 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3474
3475 if (sampler.ms) {
3476 operands.push_back(spv::ImageOperandsSampleMask);
3477 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003478#ifdef AMD_EXTENSIONS
3479 } else if (cracked.lod) {
3480 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3481 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3482
3483 operands.push_back(spv::ImageOperandsLodMask);
3484 operands.push_back(*opIt++);
3485#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003486 }
3487
3488 // Create the return type that was a special structure
3489 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003490 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003491 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3492 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3493
3494 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3495
3496 // Decode the return type
3497 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3498 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003499 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003500 // Process image atomic operations
3501
3502 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3503 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003504 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003505
John Kessenich8c8505c2016-07-26 12:50:38 -06003506 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003507 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003508
3509 std::vector<spv::Id> operands;
3510 operands.push_back(pointer);
3511 for (; opIt != arguments.end(); ++opIt)
3512 operands.push_back(*opIt);
3513
John Kessenich8c8505c2016-07-26 12:50:38 -06003514 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003515 }
3516 }
3517
amhagan05506bb2017-06-13 16:53:02 -04003518#ifdef AMD_EXTENSIONS
3519 // Check for fragment mask functions other than queries
3520 if (cracked.fragMask) {
3521 assert(sampler.ms);
3522
3523 auto opIt = arguments.begin();
3524 std::vector<spv::Id> operands;
3525
3526 // Extract the image if necessary
3527 if (builder.isSampledImage(params.sampler))
3528 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3529
3530 operands.push_back(params.sampler);
3531 ++opIt;
3532
3533 if (sampler.isSubpass()) {
3534 // add on the (0,0) coordinate
3535 spv::Id zero = builder.makeIntConstant(0);
3536 std::vector<spv::Id> comps;
3537 comps.push_back(zero);
3538 comps.push_back(zero);
3539 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3540 }
3541
3542 for (; opIt != arguments.end(); ++opIt)
3543 operands.push_back(*opIt);
3544
3545 spv::Op fragMaskOp = spv::OpNop;
3546 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3547 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3548 else if (node->getOp() == glslang::EOpFragmentFetch)
3549 fragMaskOp = spv::OpFragmentFetchAMD;
3550
3551 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3552 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3553 return builder.createOp(fragMaskOp, resultType(), operands);
3554 }
3555#endif
3556
Rex Xufc618912015-09-09 16:42:49 +08003557 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003558 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003559 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3560
John Kessenichfc51d282015-08-19 13:34:18 -06003561 // check for bias argument
3562 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003563#ifdef AMD_EXTENSIONS
3564 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3565#else
Rex Xu71519fe2015-11-11 15:35:47 +08003566 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003567#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003568 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003569#ifdef AMD_EXTENSIONS
3570 if (cracked.gather)
3571 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003572
3573 if (f16ShadowCompare)
3574 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003575#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003576 if (cracked.offset)
3577 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003578#ifdef AMD_EXTENSIONS
3579 else if (cracked.offsets)
3580 ++nonBiasArgCount;
3581#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003582 if (cracked.grad)
3583 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003584 if (cracked.lodClamp)
3585 ++nonBiasArgCount;
3586 if (sparse)
3587 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003588
3589 if ((int)arguments.size() > nonBiasArgCount)
3590 bias = true;
3591 }
3592
John Kessenicha5c33d62016-06-02 23:45:21 -06003593 // See if the sampler param should really be just the SPV image part
3594 if (cracked.fetch) {
3595 // a fetch needs to have the image extracted first
3596 if (builder.isSampledImage(params.sampler))
3597 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3598 }
3599
Rex Xu225e0fc2016-11-17 17:47:59 +08003600#ifdef AMD_EXTENSIONS
3601 if (cracked.gather) {
3602 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3603 if (bias || cracked.lod ||
3604 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3605 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003606 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003607 }
3608 }
3609#endif
3610
John Kessenichfc51d282015-08-19 13:34:18 -06003611 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003612
John Kessenichfc51d282015-08-19 13:34:18 -06003613 params.coords = arguments[1];
3614 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003615 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003616
3617 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003618#ifdef AMD_EXTENSIONS
3619 if (cubeCompare || f16ShadowCompare) {
3620#else
Rex Xu48edadf2015-12-31 16:11:41 +08003621 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003622#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003623 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003624 ++extraArgs;
3625 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003626 params.Dref = arguments[2];
3627 ++extraArgs;
3628 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003629 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003630 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003631 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003632 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003633 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003634 dRefComp = builder.getNumComponents(params.coords) - 1;
3635 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003636 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3637 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003638
3639 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003640 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003641 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003642 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003643 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3644 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3645 noImplicitLod = true;
3646 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003647
3648 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003649 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003650 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003651 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003652 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003653
3654 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003655 if (cracked.grad) {
3656 params.gradX = arguments[2 + extraArgs];
3657 params.gradY = arguments[3 + extraArgs];
3658 extraArgs += 2;
3659 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003660
3661 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003662 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003663 params.offset = arguments[2 + extraArgs];
3664 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003665 } else if (cracked.offsets) {
3666 params.offsets = arguments[2 + extraArgs];
3667 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003668 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003669
3670 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003671 if (cracked.lodClamp) {
3672 params.lodClamp = arguments[2 + extraArgs];
3673 ++extraArgs;
3674 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003675
3676 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003677 if (sparse) {
3678 params.texelOut = arguments[2 + extraArgs];
3679 ++extraArgs;
3680 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003681
John Kessenich76d4dfc2016-06-16 12:43:23 -06003682 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003683 if (cracked.gather && ! sampler.shadow) {
3684 // default component is 0, if missing, otherwise an argument
3685 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003686 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003687 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003688 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003689 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003690 }
3691
3692 // bias
3693 if (bias) {
3694 params.bias = arguments[2 + extraArgs];
3695 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003696 }
John Kessenichfc51d282015-08-19 13:34:18 -06003697
John Kessenich65336482016-06-16 14:06:26 -06003698 // projective component (might not to move)
3699 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3700 // are divided by the last component of P."
3701 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3702 // unused components will appear after all used components."
3703 if (cracked.proj) {
3704 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3705 int projTargetComp;
3706 switch (sampler.dim) {
3707 case glslang::Esd1D: projTargetComp = 1; break;
3708 case glslang::Esd2D: projTargetComp = 2; break;
3709 case glslang::EsdRect: projTargetComp = 2; break;
3710 default: projTargetComp = projSourceComp; break;
3711 }
3712 // copy the projective coordinate if we have to
3713 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003714 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003715 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3716 projSourceComp);
3717 params.coords = builder.createCompositeInsert(projComp, params.coords,
3718 builder.getTypeId(params.coords), projTargetComp);
3719 }
3720 }
3721
LoopDawg4425f242018-02-18 11:40:01 -07003722 std::vector<spv::Id> result = {
3723 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3724 };
3725
3726 if (components != node->getType().getVectorSize())
3727 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3728
3729 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003730}
3731
3732spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3733{
3734 // Grab the function's pointer from the previously created function
3735 spv::Function* function = functionMap[node->getName().c_str()];
3736 if (! function)
3737 return 0;
3738
3739 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3740 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3741
3742 // See comments in makeFunctions() for details about the semantics for parameter passing.
3743 //
3744 // These imply we need a four step process:
3745 // 1. Evaluate the arguments
3746 // 2. Allocate and make copies of in, out, and inout arguments
3747 // 3. Make the call
3748 // 4. Copy back the results
3749
3750 // 1. Evaluate the arguments
3751 std::vector<spv::Builder::AccessChain> lValues;
3752 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003753 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003755 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003756 // build l-value
3757 builder.clearAccessChain();
3758 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003759 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003760 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003761 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3762 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003763 // save l-value
3764 lValues.push_back(builder.getAccessChain());
3765 } else {
3766 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003767 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003768 }
3769 }
3770
3771 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3772 // copy the original into that space.
3773 //
3774 // Also, build up the list of actual arguments to pass in for the call
3775 int lValueCount = 0;
3776 int rValueCount = 0;
3777 std::vector<spv::Id> spvArgs;
3778 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003779 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003780 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003781 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003782 builder.setAccessChain(lValues[lValueCount]);
3783 arg = builder.accessChainGetLValue();
3784 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003785 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003786 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003787 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3788 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3789 // need to copy the input into output space
3790 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003791 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003792 builder.clearAccessChain();
3793 builder.setAccessChainLValue(arg);
3794 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003795 }
3796 ++lValueCount;
3797 } else {
3798 arg = rValues[rValueCount];
3799 ++rValueCount;
3800 }
3801 spvArgs.push_back(arg);
3802 }
3803
3804 // 3. Make the call.
3805 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003806 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003807
3808 // 4. Copy back out an "out" arguments.
3809 lValueCount = 0;
3810 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003811 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003812 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3813 ++lValueCount;
3814 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003815 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3816 spv::Id copy = builder.createLoad(spvArgs[a]);
3817 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003818 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003819 }
3820 ++lValueCount;
3821 }
3822 }
3823
3824 return result;
3825}
3826
3827// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003828spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3829 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003830 spv::Id typeId, spv::Id left, spv::Id right,
3831 glslang::TBasicType typeProxy, bool reduceComparison)
3832{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003833#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003834 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003835 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3836#else
Rex Xucabbb782017-03-24 13:41:14 +08003837 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003838 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003839#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003840 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003841
3842 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003843 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003844 bool comparison = false;
3845
3846 switch (op) {
3847 case glslang::EOpAdd:
3848 case glslang::EOpAddAssign:
3849 if (isFloat)
3850 binOp = spv::OpFAdd;
3851 else
3852 binOp = spv::OpIAdd;
3853 break;
3854 case glslang::EOpSub:
3855 case glslang::EOpSubAssign:
3856 if (isFloat)
3857 binOp = spv::OpFSub;
3858 else
3859 binOp = spv::OpISub;
3860 break;
3861 case glslang::EOpMul:
3862 case glslang::EOpMulAssign:
3863 if (isFloat)
3864 binOp = spv::OpFMul;
3865 else
3866 binOp = spv::OpIMul;
3867 break;
3868 case glslang::EOpVectorTimesScalar:
3869 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003870 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003871 if (builder.isVector(right))
3872 std::swap(left, right);
3873 assert(builder.isScalar(right));
3874 needMatchingVectors = false;
3875 binOp = spv::OpVectorTimesScalar;
3876 } else
3877 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003878 break;
3879 case glslang::EOpVectorTimesMatrix:
3880 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003881 binOp = spv::OpVectorTimesMatrix;
3882 break;
3883 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003884 binOp = spv::OpMatrixTimesVector;
3885 break;
3886 case glslang::EOpMatrixTimesScalar:
3887 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003888 binOp = spv::OpMatrixTimesScalar;
3889 break;
3890 case glslang::EOpMatrixTimesMatrix:
3891 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003892 binOp = spv::OpMatrixTimesMatrix;
3893 break;
3894 case glslang::EOpOuterProduct:
3895 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003896 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003897 break;
3898
3899 case glslang::EOpDiv:
3900 case glslang::EOpDivAssign:
3901 if (isFloat)
3902 binOp = spv::OpFDiv;
3903 else if (isUnsigned)
3904 binOp = spv::OpUDiv;
3905 else
3906 binOp = spv::OpSDiv;
3907 break;
3908 case glslang::EOpMod:
3909 case glslang::EOpModAssign:
3910 if (isFloat)
3911 binOp = spv::OpFMod;
3912 else if (isUnsigned)
3913 binOp = spv::OpUMod;
3914 else
3915 binOp = spv::OpSMod;
3916 break;
3917 case glslang::EOpRightShift:
3918 case glslang::EOpRightShiftAssign:
3919 if (isUnsigned)
3920 binOp = spv::OpShiftRightLogical;
3921 else
3922 binOp = spv::OpShiftRightArithmetic;
3923 break;
3924 case glslang::EOpLeftShift:
3925 case glslang::EOpLeftShiftAssign:
3926 binOp = spv::OpShiftLeftLogical;
3927 break;
3928 case glslang::EOpAnd:
3929 case glslang::EOpAndAssign:
3930 binOp = spv::OpBitwiseAnd;
3931 break;
3932 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003933 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003934 binOp = spv::OpLogicalAnd;
3935 break;
3936 case glslang::EOpInclusiveOr:
3937 case glslang::EOpInclusiveOrAssign:
3938 binOp = spv::OpBitwiseOr;
3939 break;
3940 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003941 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003942 binOp = spv::OpLogicalOr;
3943 break;
3944 case glslang::EOpExclusiveOr:
3945 case glslang::EOpExclusiveOrAssign:
3946 binOp = spv::OpBitwiseXor;
3947 break;
3948 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003949 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003950 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003951 break;
3952
3953 case glslang::EOpLessThan:
3954 case glslang::EOpGreaterThan:
3955 case glslang::EOpLessThanEqual:
3956 case glslang::EOpGreaterThanEqual:
3957 case glslang::EOpEqual:
3958 case glslang::EOpNotEqual:
3959 case glslang::EOpVectorEqual:
3960 case glslang::EOpVectorNotEqual:
3961 comparison = true;
3962 break;
3963 default:
3964 break;
3965 }
3966
John Kessenich7c1aa102015-10-15 13:29:11 -06003967 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003968 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003969 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003970 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003971 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003972
3973 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003974 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003975 builder.promoteScalar(precision, left, right);
3976
qining25262b32016-05-06 17:25:16 -04003977 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3978 addDecoration(result, noContraction);
3979 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003980 }
3981
3982 if (! comparison)
3983 return 0;
3984
John Kessenich7c1aa102015-10-15 13:29:11 -06003985 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003986
John Kessenich4583b612016-08-07 19:14:22 -06003987 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3988 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003989 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003990
3991 switch (op) {
3992 case glslang::EOpLessThan:
3993 if (isFloat)
3994 binOp = spv::OpFOrdLessThan;
3995 else if (isUnsigned)
3996 binOp = spv::OpULessThan;
3997 else
3998 binOp = spv::OpSLessThan;
3999 break;
4000 case glslang::EOpGreaterThan:
4001 if (isFloat)
4002 binOp = spv::OpFOrdGreaterThan;
4003 else if (isUnsigned)
4004 binOp = spv::OpUGreaterThan;
4005 else
4006 binOp = spv::OpSGreaterThan;
4007 break;
4008 case glslang::EOpLessThanEqual:
4009 if (isFloat)
4010 binOp = spv::OpFOrdLessThanEqual;
4011 else if (isUnsigned)
4012 binOp = spv::OpULessThanEqual;
4013 else
4014 binOp = spv::OpSLessThanEqual;
4015 break;
4016 case glslang::EOpGreaterThanEqual:
4017 if (isFloat)
4018 binOp = spv::OpFOrdGreaterThanEqual;
4019 else if (isUnsigned)
4020 binOp = spv::OpUGreaterThanEqual;
4021 else
4022 binOp = spv::OpSGreaterThanEqual;
4023 break;
4024 case glslang::EOpEqual:
4025 case glslang::EOpVectorEqual:
4026 if (isFloat)
4027 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004028 else if (isBool)
4029 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004030 else
4031 binOp = spv::OpIEqual;
4032 break;
4033 case glslang::EOpNotEqual:
4034 case glslang::EOpVectorNotEqual:
4035 if (isFloat)
4036 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004037 else if (isBool)
4038 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004039 else
4040 binOp = spv::OpINotEqual;
4041 break;
4042 default:
4043 break;
4044 }
4045
qining25262b32016-05-06 17:25:16 -04004046 if (binOp != spv::OpNop) {
4047 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
4048 addDecoration(result, noContraction);
4049 return builder.setPrecision(result, precision);
4050 }
John Kessenich140f3df2015-06-26 16:58:36 -06004051
4052 return 0;
4053}
4054
John Kessenich04bb8a02015-12-12 12:28:14 -07004055//
4056// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4057// These can be any of:
4058//
4059// matrix * scalar
4060// scalar * matrix
4061// matrix * matrix linear algebraic
4062// matrix * vector
4063// vector * matrix
4064// matrix * matrix componentwise
4065// matrix op matrix op in {+, -, /}
4066// matrix op scalar op in {+, -, /}
4067// scalar op matrix op in {+, -, /}
4068//
qining25262b32016-05-06 17:25:16 -04004069spv::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 -07004070{
4071 bool firstClass = true;
4072
4073 // First, handle first-class matrix operations (* and matrix/scalar)
4074 switch (op) {
4075 case spv::OpFDiv:
4076 if (builder.isMatrix(left) && builder.isScalar(right)) {
4077 // turn matrix / scalar into a multiply...
4078 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
4079 op = spv::OpMatrixTimesScalar;
4080 } else
4081 firstClass = false;
4082 break;
4083 case spv::OpMatrixTimesScalar:
4084 if (builder.isMatrix(right))
4085 std::swap(left, right);
4086 assert(builder.isScalar(right));
4087 break;
4088 case spv::OpVectorTimesMatrix:
4089 assert(builder.isVector(left));
4090 assert(builder.isMatrix(right));
4091 break;
4092 case spv::OpMatrixTimesVector:
4093 assert(builder.isMatrix(left));
4094 assert(builder.isVector(right));
4095 break;
4096 case spv::OpMatrixTimesMatrix:
4097 assert(builder.isMatrix(left));
4098 assert(builder.isMatrix(right));
4099 break;
4100 default:
4101 firstClass = false;
4102 break;
4103 }
4104
qining25262b32016-05-06 17:25:16 -04004105 if (firstClass) {
4106 spv::Id result = builder.createBinOp(op, typeId, left, right);
4107 addDecoration(result, noContraction);
4108 return builder.setPrecision(result, precision);
4109 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004110
LoopDawg592860c2016-06-09 08:57:35 -06004111 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004112 // The result type of all of them is the same type as the (a) matrix operand.
4113 // The algorithm is to:
4114 // - break the matrix(es) into vectors
4115 // - smear any scalar to a vector
4116 // - do vector operations
4117 // - make a matrix out the vector results
4118 switch (op) {
4119 case spv::OpFAdd:
4120 case spv::OpFSub:
4121 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004122 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004123 case spv::OpFMul:
4124 {
4125 // one time set up...
4126 bool leftMat = builder.isMatrix(left);
4127 bool rightMat = builder.isMatrix(right);
4128 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4129 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4130 spv::Id scalarType = builder.getScalarTypeId(typeId);
4131 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4132 std::vector<spv::Id> results;
4133 spv::Id smearVec = spv::NoResult;
4134 if (builder.isScalar(left))
4135 smearVec = builder.smearScalar(precision, left, vecType);
4136 else if (builder.isScalar(right))
4137 smearVec = builder.smearScalar(precision, right, vecType);
4138
4139 // do each vector op
4140 for (unsigned int c = 0; c < numCols; ++c) {
4141 std::vector<unsigned int> indexes;
4142 indexes.push_back(c);
4143 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4144 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004145 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4146 addDecoration(result, noContraction);
4147 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004148 }
4149
4150 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004151 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004152 }
4153 default:
4154 assert(0);
4155 return spv::NoResult;
4156 }
4157}
4158
qining25262b32016-05-06 17:25:16 -04004159spv::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 -06004160{
4161 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004162 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004163 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004164#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004165 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004166 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4167#else
Rex Xucabbb782017-03-24 13:41:14 +08004168 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004169 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004170#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004171
4172 switch (op) {
4173 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004174 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004175 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004176 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004177 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004178 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004179 unaryOp = spv::OpSNegate;
4180 break;
4181
4182 case glslang::EOpLogicalNot:
4183 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 unaryOp = spv::OpLogicalNot;
4185 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 case glslang::EOpBitwiseNot:
4187 unaryOp = spv::OpNot;
4188 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004189
John Kessenich140f3df2015-06-26 16:58:36 -06004190 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004191 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004192 break;
4193 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004194 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004195 break;
4196 case glslang::EOpTranspose:
4197 unaryOp = spv::OpTranspose;
4198 break;
4199
4200 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004201 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004202 break;
4203 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004204 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004205 break;
4206 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004207 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004208 break;
4209 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004210 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004211 break;
4212 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004213 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004214 break;
4215 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004216 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004217 break;
4218 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004219 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004220 break;
4221 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004222 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004223 break;
4224
4225 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004226 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004227 break;
4228 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004229 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004230 break;
4231 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004232 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004233 break;
4234 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004235 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004236 break;
4237 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004238 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004239 break;
4240 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004241 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004242 break;
4243
4244 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004245 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004246 break;
4247 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004248 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004249 break;
4250
4251 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004252 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004253 break;
4254 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004255 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004256 break;
4257 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004258 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004259 break;
4260 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004261 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004262 break;
4263 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004264 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004265 break;
4266 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004267 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004268 break;
4269
4270 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004271 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004272 break;
4273 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004274 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004275 break;
4276 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004277 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004278 break;
4279 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004280 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004281 break;
4282 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004283 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004284 break;
4285 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004286 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004287 break;
4288
4289 case glslang::EOpIsNan:
4290 unaryOp = spv::OpIsNan;
4291 break;
4292 case glslang::EOpIsInf:
4293 unaryOp = spv::OpIsInf;
4294 break;
LoopDawg592860c2016-06-09 08:57:35 -06004295 case glslang::EOpIsFinite:
4296 unaryOp = spv::OpIsFinite;
4297 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004298
Rex Xucbc426e2015-12-15 16:03:10 +08004299 case glslang::EOpFloatBitsToInt:
4300 case glslang::EOpFloatBitsToUint:
4301 case glslang::EOpIntBitsToFloat:
4302 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004303 case glslang::EOpDoubleBitsToInt64:
4304 case glslang::EOpDoubleBitsToUint64:
4305 case glslang::EOpInt64BitsToDouble:
4306 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004307#ifdef AMD_EXTENSIONS
4308 case glslang::EOpFloat16BitsToInt16:
4309 case glslang::EOpFloat16BitsToUint16:
4310 case glslang::EOpInt16BitsToFloat16:
4311 case glslang::EOpUint16BitsToFloat16:
4312#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004313 unaryOp = spv::OpBitcast;
4314 break;
4315
John Kessenich140f3df2015-06-26 16:58:36 -06004316 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004317 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004318 break;
4319 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004320 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004321 break;
4322 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004323 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004324 break;
4325 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004326 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004327 break;
4328 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004329 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004330 break;
4331 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004333 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004334 case glslang::EOpPackSnorm4x8:
4335 libCall = spv::GLSLstd450PackSnorm4x8;
4336 break;
4337 case glslang::EOpUnpackSnorm4x8:
4338 libCall = spv::GLSLstd450UnpackSnorm4x8;
4339 break;
4340 case glslang::EOpPackUnorm4x8:
4341 libCall = spv::GLSLstd450PackUnorm4x8;
4342 break;
4343 case glslang::EOpUnpackUnorm4x8:
4344 libCall = spv::GLSLstd450UnpackUnorm4x8;
4345 break;
4346 case glslang::EOpPackDouble2x32:
4347 libCall = spv::GLSLstd450PackDouble2x32;
4348 break;
4349 case glslang::EOpUnpackDouble2x32:
4350 libCall = spv::GLSLstd450UnpackDouble2x32;
4351 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004352
Rex Xu8ff43de2016-04-22 16:51:45 +08004353 case glslang::EOpPackInt2x32:
4354 case glslang::EOpUnpackInt2x32:
4355 case glslang::EOpPackUint2x32:
4356 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004357 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004358 break;
4359
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004360#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004361 case glslang::EOpPackInt2x16:
4362 case glslang::EOpUnpackInt2x16:
4363 case glslang::EOpPackUint2x16:
4364 case glslang::EOpUnpackUint2x16:
4365 case glslang::EOpPackInt4x16:
4366 case glslang::EOpUnpackInt4x16:
4367 case glslang::EOpPackUint4x16:
4368 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004369 case glslang::EOpPackFloat2x16:
4370 case glslang::EOpUnpackFloat2x16:
4371 unaryOp = spv::OpBitcast;
4372 break;
4373#endif
4374
John Kessenich140f3df2015-06-26 16:58:36 -06004375 case glslang::EOpDPdx:
4376 unaryOp = spv::OpDPdx;
4377 break;
4378 case glslang::EOpDPdy:
4379 unaryOp = spv::OpDPdy;
4380 break;
4381 case glslang::EOpFwidth:
4382 unaryOp = spv::OpFwidth;
4383 break;
4384 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004385 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004386 unaryOp = spv::OpDPdxFine;
4387 break;
4388 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004389 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004390 unaryOp = spv::OpDPdyFine;
4391 break;
4392 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004393 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004394 unaryOp = spv::OpFwidthFine;
4395 break;
4396 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004397 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004398 unaryOp = spv::OpDPdxCoarse;
4399 break;
4400 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004401 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004402 unaryOp = spv::OpDPdyCoarse;
4403 break;
4404 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004405 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004406 unaryOp = spv::OpFwidthCoarse;
4407 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004408 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004409 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004410 libCall = spv::GLSLstd450InterpolateAtCentroid;
4411 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004412 case glslang::EOpAny:
4413 unaryOp = spv::OpAny;
4414 break;
4415 case glslang::EOpAll:
4416 unaryOp = spv::OpAll;
4417 break;
4418
4419 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004420 if (isFloat)
4421 libCall = spv::GLSLstd450FAbs;
4422 else
4423 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004424 break;
4425 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004426 if (isFloat)
4427 libCall = spv::GLSLstd450FSign;
4428 else
4429 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004430 break;
4431
John Kessenichfc51d282015-08-19 13:34:18 -06004432 case glslang::EOpAtomicCounterIncrement:
4433 case glslang::EOpAtomicCounterDecrement:
4434 case glslang::EOpAtomicCounter:
4435 {
4436 // Handle all of the atomics in one place, in createAtomicOperation()
4437 std::vector<spv::Id> operands;
4438 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004439 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004440 }
4441
John Kessenichfc51d282015-08-19 13:34:18 -06004442 case glslang::EOpBitFieldReverse:
4443 unaryOp = spv::OpBitReverse;
4444 break;
4445 case glslang::EOpBitCount:
4446 unaryOp = spv::OpBitCount;
4447 break;
4448 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004449 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004450 break;
4451 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004452 if (isUnsigned)
4453 libCall = spv::GLSLstd450FindUMsb;
4454 else
4455 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004456 break;
4457
Rex Xu574ab042016-04-14 16:53:07 +08004458 case glslang::EOpBallot:
4459 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004460 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004461 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004462 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004463#ifdef AMD_EXTENSIONS
4464 case glslang::EOpMinInvocations:
4465 case glslang::EOpMaxInvocations:
4466 case glslang::EOpAddInvocations:
4467 case glslang::EOpMinInvocationsNonUniform:
4468 case glslang::EOpMaxInvocationsNonUniform:
4469 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004470 case glslang::EOpMinInvocationsInclusiveScan:
4471 case glslang::EOpMaxInvocationsInclusiveScan:
4472 case glslang::EOpAddInvocationsInclusiveScan:
4473 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4474 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4475 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4476 case glslang::EOpMinInvocationsExclusiveScan:
4477 case glslang::EOpMaxInvocationsExclusiveScan:
4478 case glslang::EOpAddInvocationsExclusiveScan:
4479 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4480 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4481 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004482#endif
Rex Xu51596642016-09-21 18:56:12 +08004483 {
4484 std::vector<spv::Id> operands;
4485 operands.push_back(operand);
4486 return createInvocationsOperation(op, typeId, operands, typeProxy);
4487 }
Rex Xu9d93a232016-05-05 12:30:44 +08004488
4489#ifdef AMD_EXTENSIONS
4490 case glslang::EOpMbcnt:
4491 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4492 libCall = spv::MbcntAMD;
4493 break;
4494
4495 case glslang::EOpCubeFaceIndex:
4496 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4497 libCall = spv::CubeFaceIndexAMD;
4498 break;
4499
4500 case glslang::EOpCubeFaceCoord:
4501 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4502 libCall = spv::CubeFaceCoordAMD;
4503 break;
4504#endif
Rex Xu338b1852016-05-05 20:38:33 +08004505
John Kessenich140f3df2015-06-26 16:58:36 -06004506 default:
4507 return 0;
4508 }
4509
4510 spv::Id id;
4511 if (libCall >= 0) {
4512 std::vector<spv::Id> args;
4513 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004514 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004515 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004516 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004517 }
John Kessenich140f3df2015-06-26 16:58:36 -06004518
qining25262b32016-05-06 17:25:16 -04004519 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004520 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004521}
4522
John Kessenich7a53f762016-01-20 11:19:27 -07004523// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004524spv::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 -07004525{
4526 // Handle unary operations vector by vector.
4527 // The result type is the same type as the original type.
4528 // The algorithm is to:
4529 // - break the matrix into vectors
4530 // - apply the operation to each vector
4531 // - make a matrix out the vector results
4532
4533 // get the types sorted out
4534 int numCols = builder.getNumColumns(operand);
4535 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004536 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4537 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004538 std::vector<spv::Id> results;
4539
4540 // do each vector op
4541 for (int c = 0; c < numCols; ++c) {
4542 std::vector<unsigned int> indexes;
4543 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004544 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4545 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4546 addDecoration(destVec, noContraction);
4547 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004548 }
4549
4550 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004551 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004552}
4553
Rex Xu73e3ce72016-04-27 18:48:17 +08004554spv::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 -06004555{
4556 spv::Op convOp = spv::OpNop;
4557 spv::Id zero = 0;
4558 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004559 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004560
4561 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4562
4563 switch (op) {
4564 case glslang::EOpConvIntToBool:
4565 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004566 case glslang::EOpConvInt64ToBool:
4567 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004568#ifdef AMD_EXTENSIONS
4569 case glslang::EOpConvInt16ToBool:
4570 case glslang::EOpConvUint16ToBool:
4571#endif
4572 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4573 zero = builder.makeUint64Constant(0);
4574#ifdef AMD_EXTENSIONS
4575 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4576 zero = builder.makeUint16Constant(0);
4577#endif
4578 else
4579 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004580 zero = makeSmearedConstant(zero, vectorSize);
4581 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4582
4583 case glslang::EOpConvFloatToBool:
4584 zero = builder.makeFloatConstant(0.0F);
4585 zero = makeSmearedConstant(zero, vectorSize);
4586 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4587
4588 case glslang::EOpConvDoubleToBool:
4589 zero = builder.makeDoubleConstant(0.0);
4590 zero = makeSmearedConstant(zero, vectorSize);
4591 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4592
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004593#ifdef AMD_EXTENSIONS
4594 case glslang::EOpConvFloat16ToBool:
4595 zero = builder.makeFloat16Constant(0.0F);
4596 zero = makeSmearedConstant(zero, vectorSize);
4597 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4598#endif
4599
John Kessenich140f3df2015-06-26 16:58:36 -06004600 case glslang::EOpConvBoolToFloat:
4601 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004602 zero = builder.makeFloatConstant(0.0F);
4603 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004604 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004605
John Kessenich140f3df2015-06-26 16:58:36 -06004606 case glslang::EOpConvBoolToDouble:
4607 convOp = spv::OpSelect;
4608 zero = builder.makeDoubleConstant(0.0);
4609 one = builder.makeDoubleConstant(1.0);
4610 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004611
4612#ifdef AMD_EXTENSIONS
4613 case glslang::EOpConvBoolToFloat16:
4614 convOp = spv::OpSelect;
4615 zero = builder.makeFloat16Constant(0.0F);
4616 one = builder.makeFloat16Constant(1.0F);
4617 break;
4618#endif
4619
John Kessenich140f3df2015-06-26 16:58:36 -06004620 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004621 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004622#ifdef AMD_EXTENSIONS
4623 case glslang::EOpConvBoolToInt16:
4624#endif
4625 if (op == glslang::EOpConvBoolToInt64)
4626 zero = builder.makeInt64Constant(0);
4627#ifdef AMD_EXTENSIONS
4628 else if (op == glslang::EOpConvBoolToInt16)
4629 zero = builder.makeInt16Constant(0);
4630#endif
4631 else
4632 zero = builder.makeIntConstant(0);
4633
4634 if (op == glslang::EOpConvBoolToInt64)
4635 one = builder.makeInt64Constant(1);
4636#ifdef AMD_EXTENSIONS
4637 else if (op == glslang::EOpConvBoolToInt16)
4638 one = builder.makeInt16Constant(1);
4639#endif
4640 else
4641 one = builder.makeIntConstant(1);
4642
John Kessenich140f3df2015-06-26 16:58:36 -06004643 convOp = spv::OpSelect;
4644 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004645
John Kessenich140f3df2015-06-26 16:58:36 -06004646 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004647 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004648#ifdef AMD_EXTENSIONS
4649 case glslang::EOpConvBoolToUint16:
4650#endif
4651 if (op == glslang::EOpConvBoolToUint64)
4652 zero = builder.makeUint64Constant(0);
4653#ifdef AMD_EXTENSIONS
4654 else if (op == glslang::EOpConvBoolToUint16)
4655 zero = builder.makeUint16Constant(0);
4656#endif
4657 else
4658 zero = builder.makeUintConstant(0);
4659
4660 if (op == glslang::EOpConvBoolToUint64)
4661 one = builder.makeUint64Constant(1);
4662#ifdef AMD_EXTENSIONS
4663 else if (op == glslang::EOpConvBoolToUint16)
4664 one = builder.makeUint16Constant(1);
4665#endif
4666 else
4667 one = builder.makeUintConstant(1);
4668
John Kessenich140f3df2015-06-26 16:58:36 -06004669 convOp = spv::OpSelect;
4670 break;
4671
4672 case glslang::EOpConvIntToFloat:
4673 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004674 case glslang::EOpConvInt64ToFloat:
4675 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004676#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004677 case glslang::EOpConvInt16ToFloat:
4678 case glslang::EOpConvInt16ToDouble:
4679 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004680 case glslang::EOpConvIntToFloat16:
4681 case glslang::EOpConvInt64ToFloat16:
4682#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004683 convOp = spv::OpConvertSToF;
4684 break;
4685
4686 case glslang::EOpConvUintToFloat:
4687 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004688 case glslang::EOpConvUint64ToFloat:
4689 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004690#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004691 case glslang::EOpConvUint16ToFloat:
4692 case glslang::EOpConvUint16ToDouble:
4693 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004694 case glslang::EOpConvUintToFloat16:
4695 case glslang::EOpConvUint64ToFloat16:
4696#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004697 convOp = spv::OpConvertUToF;
4698 break;
4699
4700 case glslang::EOpConvDoubleToFloat:
4701 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004702#ifdef AMD_EXTENSIONS
4703 case glslang::EOpConvDoubleToFloat16:
4704 case glslang::EOpConvFloat16ToDouble:
4705 case glslang::EOpConvFloatToFloat16:
4706 case glslang::EOpConvFloat16ToFloat:
4707#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004708 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004709 if (builder.isMatrixType(destType))
4710 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004711 break;
4712
4713 case glslang::EOpConvFloatToInt:
4714 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004715 case glslang::EOpConvFloatToInt64:
4716 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004717#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004718 case glslang::EOpConvFloatToInt16:
4719 case glslang::EOpConvDoubleToInt16:
4720 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004721 case glslang::EOpConvFloat16ToInt:
4722 case glslang::EOpConvFloat16ToInt64:
4723#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004724 convOp = spv::OpConvertFToS;
4725 break;
4726
4727 case glslang::EOpConvUintToInt:
4728 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004729 case glslang::EOpConvUint64ToInt64:
4730 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004731#ifdef AMD_EXTENSIONS
4732 case glslang::EOpConvUint16ToInt16:
4733 case glslang::EOpConvInt16ToUint16:
4734#endif
qininge24aa5e2016-04-07 15:40:27 -04004735 if (builder.isInSpecConstCodeGenMode()) {
4736 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004737 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4738 zero = builder.makeUint64Constant(0);
4739#ifdef AMD_EXTENSIONS
4740 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4741 zero = builder.makeUint16Constant(0);
4742#endif
4743 else
4744 zero = builder.makeUintConstant(0);
4745
qining189b2032016-04-12 23:16:20 -04004746 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004747 // Use OpIAdd, instead of OpBitcast to do the conversion when
4748 // generating for OpSpecConstantOp instruction.
4749 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4750 }
4751 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004752 convOp = spv::OpBitcast;
4753 break;
4754
4755 case glslang::EOpConvFloatToUint:
4756 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004757 case glslang::EOpConvFloatToUint64:
4758 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004759#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004760 case glslang::EOpConvFloatToUint16:
4761 case glslang::EOpConvDoubleToUint16:
4762 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004763 case glslang::EOpConvFloat16ToUint:
4764 case glslang::EOpConvFloat16ToUint64:
4765#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004766 convOp = spv::OpConvertFToU;
4767 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004768
4769 case glslang::EOpConvIntToInt64:
4770 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004771#ifdef AMD_EXTENSIONS
4772 case glslang::EOpConvIntToInt16:
4773 case glslang::EOpConvInt16ToInt:
4774 case glslang::EOpConvInt64ToInt16:
4775 case glslang::EOpConvInt16ToInt64:
4776#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004777 convOp = spv::OpSConvert;
4778 break;
4779
4780 case glslang::EOpConvUintToUint64:
4781 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004782#ifdef AMD_EXTENSIONS
4783 case glslang::EOpConvUintToUint16:
4784 case glslang::EOpConvUint16ToUint:
4785 case glslang::EOpConvUint64ToUint16:
4786 case glslang::EOpConvUint16ToUint64:
4787#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004788 convOp = spv::OpUConvert;
4789 break;
4790
4791 case glslang::EOpConvIntToUint64:
4792 case glslang::EOpConvInt64ToUint:
4793 case glslang::EOpConvUint64ToInt:
4794 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004795#ifdef AMD_EXTENSIONS
4796 case glslang::EOpConvInt16ToUint:
4797 case glslang::EOpConvUintToInt16:
4798 case glslang::EOpConvInt16ToUint64:
4799 case glslang::EOpConvUint64ToInt16:
4800 case glslang::EOpConvUint16ToInt:
4801 case glslang::EOpConvIntToUint16:
4802 case glslang::EOpConvUint16ToInt64:
4803 case glslang::EOpConvInt64ToUint16:
4804#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004805 // OpSConvert/OpUConvert + OpBitCast
4806 switch (op) {
4807 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004808#ifdef AMD_EXTENSIONS
4809 case glslang::EOpConvInt16ToUint64:
4810#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004811 convOp = spv::OpSConvert;
4812 type = builder.makeIntType(64);
4813 break;
4814 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004815#ifdef AMD_EXTENSIONS
4816 case glslang::EOpConvInt16ToUint:
4817#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004818 convOp = spv::OpSConvert;
4819 type = builder.makeIntType(32);
4820 break;
4821 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004822#ifdef AMD_EXTENSIONS
4823 case glslang::EOpConvUint16ToInt:
4824#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004825 convOp = spv::OpUConvert;
4826 type = builder.makeUintType(32);
4827 break;
4828 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004829#ifdef AMD_EXTENSIONS
4830 case glslang::EOpConvUint16ToInt64:
4831#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004832 convOp = spv::OpUConvert;
4833 type = builder.makeUintType(64);
4834 break;
Rex Xucabbb782017-03-24 13:41:14 +08004835#ifdef AMD_EXTENSIONS
4836 case glslang::EOpConvUintToInt16:
4837 case glslang::EOpConvUint64ToInt16:
4838 convOp = spv::OpUConvert;
4839 type = builder.makeUintType(16);
4840 break;
4841 case glslang::EOpConvIntToUint16:
4842 case glslang::EOpConvInt64ToUint16:
4843 convOp = spv::OpSConvert;
4844 type = builder.makeIntType(16);
4845 break;
4846#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004847 default:
4848 assert(0);
4849 break;
4850 }
4851
4852 if (vectorSize > 0)
4853 type = builder.makeVectorType(type, vectorSize);
4854
4855 operand = builder.createUnaryOp(convOp, type, operand);
4856
4857 if (builder.isInSpecConstCodeGenMode()) {
4858 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004859#ifdef AMD_EXTENSIONS
4860 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4861 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4862 zero = builder.makeUint64Constant(0);
4863 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4864 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4865 zero = builder.makeUint16Constant(0);
4866 else
4867 zero = builder.makeUintConstant(0);
4868#else
4869 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4870 zero = builder.makeUint64Constant(0);
4871 else
4872 zero = builder.makeUintConstant(0);
4873#endif
4874
Rex Xu8ff43de2016-04-22 16:51:45 +08004875 zero = makeSmearedConstant(zero, vectorSize);
4876 // Use OpIAdd, instead of OpBitcast to do the conversion when
4877 // generating for OpSpecConstantOp instruction.
4878 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4879 }
4880 // For normal run-time conversion instruction, use OpBitcast.
4881 convOp = spv::OpBitcast;
4882 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004883 default:
4884 break;
4885 }
4886
4887 spv::Id result = 0;
4888 if (convOp == spv::OpNop)
4889 return result;
4890
4891 if (convOp == spv::OpSelect) {
4892 zero = makeSmearedConstant(zero, vectorSize);
4893 one = makeSmearedConstant(one, vectorSize);
4894 result = builder.createTriOp(convOp, destType, operand, one, zero);
4895 } else
4896 result = builder.createUnaryOp(convOp, destType, operand);
4897
John Kessenich32cfd492016-02-02 12:37:46 -07004898 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004899}
4900
4901spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4902{
4903 if (vectorSize == 0)
4904 return constant;
4905
4906 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4907 std::vector<spv::Id> components;
4908 for (int c = 0; c < vectorSize; ++c)
4909 components.push_back(constant);
4910 return builder.makeCompositeConstant(vectorTypeId, components);
4911}
4912
John Kessenich426394d2015-07-23 10:22:48 -06004913// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004914spv::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 -06004915{
4916 spv::Op opCode = spv::OpNop;
4917
4918 switch (op) {
4919 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004920 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004921 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004922 opCode = spv::OpAtomicIAdd;
4923 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004924 case glslang::EOpAtomicCounterSubtract:
4925 opCode = spv::OpAtomicISub;
4926 break;
John Kessenich426394d2015-07-23 10:22:48 -06004927 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004928 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004929 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004930 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004931 break;
4932 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004933 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004934 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004935 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004936 break;
4937 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004938 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004939 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004940 opCode = spv::OpAtomicAnd;
4941 break;
4942 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004943 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004944 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004945 opCode = spv::OpAtomicOr;
4946 break;
4947 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004948 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004949 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004950 opCode = spv::OpAtomicXor;
4951 break;
4952 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004953 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004954 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004955 opCode = spv::OpAtomicExchange;
4956 break;
4957 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004958 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004959 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004960 opCode = spv::OpAtomicCompareExchange;
4961 break;
4962 case glslang::EOpAtomicCounterIncrement:
4963 opCode = spv::OpAtomicIIncrement;
4964 break;
4965 case glslang::EOpAtomicCounterDecrement:
4966 opCode = spv::OpAtomicIDecrement;
4967 break;
4968 case glslang::EOpAtomicCounter:
4969 opCode = spv::OpAtomicLoad;
4970 break;
4971 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004972 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004973 break;
4974 }
4975
Rex Xue8fe8b02017-09-26 15:42:56 +08004976 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4977 builder.addCapability(spv::CapabilityInt64Atomics);
4978
John Kessenich426394d2015-07-23 10:22:48 -06004979 // Sort out the operands
4980 // - mapping from glslang -> SPV
4981 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004982 // - compare-exchange swaps the value and comparator
4983 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004984 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004985 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4986 auto opIt = operands.begin(); // walk the glslang operands
4987 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004988 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4989 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4990 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004991 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4992 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004993 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004994 spvAtomicOperands.push_back(*(opIt + 1));
4995 spvAtomicOperands.push_back(*opIt);
4996 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004997 }
John Kessenich426394d2015-07-23 10:22:48 -06004998
John Kessenich3e60a6f2015-09-14 22:45:16 -06004999 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005000 for (; opIt != operands.end(); ++opIt)
5001 spvAtomicOperands.push_back(*opIt);
5002
John Kessenich48d6e792017-10-06 21:21:48 -06005003 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5004
5005 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5006 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5007 if (op == glslang::EOpAtomicCounterDecrement)
5008 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5009
5010 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005011}
5012
John Kessenich91cef522016-05-05 16:45:40 -06005013// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005014spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005015{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005016#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05005017 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005018 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005019#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005020
Rex Xu51596642016-09-21 18:56:12 +08005021 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005022 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005023 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5024
chaocf200da82016-12-20 12:44:35 -08005025 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5026 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005027 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5028 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005029 } else if (op == glslang::EOpAnyInvocation ||
5030 op == glslang::EOpAllInvocations ||
5031 op == glslang::EOpAllInvocationsEqual) {
5032 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5033 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005034 } else {
5035 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005036#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005037 if (op == glslang::EOpMinInvocationsNonUniform ||
5038 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005039 op == glslang::EOpAddInvocationsNonUniform ||
5040 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5041 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5042 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5043 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5044 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5045 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005046 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005047#endif
Rex Xu51596642016-09-21 18:56:12 +08005048
5049 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005050#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005051 switch (op) {
5052 case glslang::EOpMinInvocations:
5053 case glslang::EOpMaxInvocations:
5054 case glslang::EOpAddInvocations:
5055 case glslang::EOpMinInvocationsNonUniform:
5056 case glslang::EOpMaxInvocationsNonUniform:
5057 case glslang::EOpAddInvocationsNonUniform:
5058 groupOperation = spv::GroupOperationReduce;
5059 spvGroupOperands.push_back(groupOperation);
5060 break;
5061 case glslang::EOpMinInvocationsInclusiveScan:
5062 case glslang::EOpMaxInvocationsInclusiveScan:
5063 case glslang::EOpAddInvocationsInclusiveScan:
5064 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5065 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5066 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5067 groupOperation = spv::GroupOperationInclusiveScan;
5068 spvGroupOperands.push_back(groupOperation);
5069 break;
5070 case glslang::EOpMinInvocationsExclusiveScan:
5071 case glslang::EOpMaxInvocationsExclusiveScan:
5072 case glslang::EOpAddInvocationsExclusiveScan:
5073 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5074 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5075 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5076 groupOperation = spv::GroupOperationExclusiveScan;
5077 spvGroupOperands.push_back(groupOperation);
5078 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005079 default:
5080 break;
Rex Xu430ef402016-10-14 17:22:23 +08005081 }
Rex Xu9d93a232016-05-05 12:30:44 +08005082#endif
Rex Xu51596642016-09-21 18:56:12 +08005083 }
5084
5085 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5086 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005087
5088 switch (op) {
5089 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005090 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005091 break;
John Kessenich91cef522016-05-05 16:45:40 -06005092 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005093 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005094 break;
John Kessenich91cef522016-05-05 16:45:40 -06005095 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005096 opCode = spv::OpSubgroupAllEqualKHR;
5097 break;
Rex Xu51596642016-09-21 18:56:12 +08005098 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005099 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005100 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005101 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005102 break;
5103 case glslang::EOpReadFirstInvocation:
5104 opCode = spv::OpSubgroupFirstInvocationKHR;
5105 break;
5106 case glslang::EOpBallot:
5107 {
5108 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5109 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5110 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5111 //
5112 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5113 //
5114 spv::Id uintType = builder.makeUintType(32);
5115 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5116 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5117
5118 std::vector<spv::Id> components;
5119 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5120 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5121
5122 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5123 return builder.createUnaryOp(spv::OpBitcast, typeId,
5124 builder.createCompositeConstruct(uvec2Type, components));
5125 }
5126
Rex Xu9d93a232016-05-05 12:30:44 +08005127#ifdef AMD_EXTENSIONS
5128 case glslang::EOpMinInvocations:
5129 case glslang::EOpMaxInvocations:
5130 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005131 case glslang::EOpMinInvocationsInclusiveScan:
5132 case glslang::EOpMaxInvocationsInclusiveScan:
5133 case glslang::EOpAddInvocationsInclusiveScan:
5134 case glslang::EOpMinInvocationsExclusiveScan:
5135 case glslang::EOpMaxInvocationsExclusiveScan:
5136 case glslang::EOpAddInvocationsExclusiveScan:
5137 if (op == glslang::EOpMinInvocations ||
5138 op == glslang::EOpMinInvocationsInclusiveScan ||
5139 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005140 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005141 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005142 else {
5143 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005144 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005145 else
Rex Xu51596642016-09-21 18:56:12 +08005146 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005147 }
Rex Xu430ef402016-10-14 17:22:23 +08005148 } else if (op == glslang::EOpMaxInvocations ||
5149 op == glslang::EOpMaxInvocationsInclusiveScan ||
5150 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005151 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005152 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005153 else {
5154 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005155 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005156 else
Rex Xu51596642016-09-21 18:56:12 +08005157 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005158 }
5159 } else {
5160 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005161 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005162 else
Rex Xu51596642016-09-21 18:56:12 +08005163 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005164 }
5165
Rex Xu2bbbe062016-08-23 15:41:05 +08005166 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005167 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005168
5169 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005170 case glslang::EOpMinInvocationsNonUniform:
5171 case glslang::EOpMaxInvocationsNonUniform:
5172 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005173 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5174 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5175 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5176 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5177 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5178 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5179 if (op == glslang::EOpMinInvocationsNonUniform ||
5180 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5181 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005182 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005183 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005184 else {
5185 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005186 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005187 else
Rex Xu51596642016-09-21 18:56:12 +08005188 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005189 }
5190 }
Rex Xu430ef402016-10-14 17:22:23 +08005191 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5192 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5193 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005194 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005195 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005196 else {
5197 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005198 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005199 else
Rex Xu51596642016-09-21 18:56:12 +08005200 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005201 }
5202 }
5203 else {
5204 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005205 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005206 else
Rex Xu51596642016-09-21 18:56:12 +08005207 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005208 }
5209
Rex Xu2bbbe062016-08-23 15:41:05 +08005210 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005211 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005212
5213 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005214#endif
John Kessenich91cef522016-05-05 16:45:40 -06005215 default:
5216 logger->missingFunctionality("invocation operation");
5217 return spv::NoResult;
5218 }
Rex Xu51596642016-09-21 18:56:12 +08005219
5220 assert(opCode != spv::OpNop);
5221 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005222}
5223
Rex Xu2bbbe062016-08-23 15:41:05 +08005224// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005225spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005226{
Rex Xub7072052016-09-26 15:53:40 +08005227#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005228 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5229 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005230 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005231 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005232 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5233 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5234 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005235#else
5236 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5237 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005238 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5239 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005240#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005241
5242 // Handle group invocation operations scalar by scalar.
5243 // The result type is the same type as the original type.
5244 // The algorithm is to:
5245 // - break the vector into scalars
5246 // - apply the operation to each scalar
5247 // - make a vector out the scalar results
5248
5249 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005250 int numComponents = builder.getNumComponents(operands[0]);
5251 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005252 std::vector<spv::Id> results;
5253
5254 // do each scalar op
5255 for (int comp = 0; comp < numComponents; ++comp) {
5256 std::vector<unsigned int> indexes;
5257 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005258 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005259 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005260 if (op == spv::OpSubgroupReadInvocationKHR) {
5261 spvGroupOperands.push_back(scalar);
5262 spvGroupOperands.push_back(operands[1]);
5263 } else if (op == spv::OpGroupBroadcast) {
5264 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005265 spvGroupOperands.push_back(scalar);
5266 spvGroupOperands.push_back(operands[1]);
5267 } else {
chaocf200da82016-12-20 12:44:35 -08005268 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005269 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005270 spvGroupOperands.push_back(scalar);
5271 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005272
Rex Xub7072052016-09-26 15:53:40 +08005273 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005274 }
5275
5276 // put the pieces together
5277 return builder.createCompositeConstruct(typeId, results);
5278}
Rex Xu2bbbe062016-08-23 15:41:05 +08005279
John Kessenich5e4b1242015-08-06 22:53:06 -06005280spv::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 -06005281{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005282#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005283 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005284 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5285#else
Rex Xucabbb782017-03-24 13:41:14 +08005286 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005287 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005288#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005289
John Kessenich140f3df2015-06-26 16:58:36 -06005290 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005291 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005292 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005293 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005294 spv::Id typeId0 = 0;
5295 if (consumedOperands > 0)
5296 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005297 spv::Id typeId1 = 0;
5298 if (consumedOperands > 1)
5299 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005300 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005301
5302 switch (op) {
5303 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005304 if (isFloat)
5305 libCall = spv::GLSLstd450FMin;
5306 else if (isUnsigned)
5307 libCall = spv::GLSLstd450UMin;
5308 else
5309 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005310 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005311 break;
5312 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005313 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005314 break;
5315 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005316 if (isFloat)
5317 libCall = spv::GLSLstd450FMax;
5318 else if (isUnsigned)
5319 libCall = spv::GLSLstd450UMax;
5320 else
5321 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005322 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005323 break;
5324 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 break;
5327 case glslang::EOpDot:
5328 opCode = spv::OpDot;
5329 break;
5330 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005331 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005332 break;
5333
5334 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 if (isFloat)
5336 libCall = spv::GLSLstd450FClamp;
5337 else if (isUnsigned)
5338 libCall = spv::GLSLstd450UClamp;
5339 else
5340 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005341 builder.promoteScalar(precision, operands.front(), operands[1]);
5342 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005343 break;
5344 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005345 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5346 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005347 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005348 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005349 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005350 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005351 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005352 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005353 break;
5354 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005355 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005356 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005357 break;
5358 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005359 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005360 builder.promoteScalar(precision, operands[0], operands[2]);
5361 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005362 break;
5363
5364 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005365 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005366 break;
5367 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005368 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005369 break;
5370 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005371 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005372 break;
5373 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005374 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005375 break;
5376 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005377 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005378 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005379 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005380 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005381 libCall = spv::GLSLstd450InterpolateAtSample;
5382 break;
5383 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005384 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005385 libCall = spv::GLSLstd450InterpolateAtOffset;
5386 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005387 case glslang::EOpAddCarry:
5388 opCode = spv::OpIAddCarry;
5389 typeId = builder.makeStructResultType(typeId0, typeId0);
5390 consumedOperands = 2;
5391 break;
5392 case glslang::EOpSubBorrow:
5393 opCode = spv::OpISubBorrow;
5394 typeId = builder.makeStructResultType(typeId0, typeId0);
5395 consumedOperands = 2;
5396 break;
5397 case glslang::EOpUMulExtended:
5398 opCode = spv::OpUMulExtended;
5399 typeId = builder.makeStructResultType(typeId0, typeId0);
5400 consumedOperands = 2;
5401 break;
5402 case glslang::EOpIMulExtended:
5403 opCode = spv::OpSMulExtended;
5404 typeId = builder.makeStructResultType(typeId0, typeId0);
5405 consumedOperands = 2;
5406 break;
5407 case glslang::EOpBitfieldExtract:
5408 if (isUnsigned)
5409 opCode = spv::OpBitFieldUExtract;
5410 else
5411 opCode = spv::OpBitFieldSExtract;
5412 break;
5413 case glslang::EOpBitfieldInsert:
5414 opCode = spv::OpBitFieldInsert;
5415 break;
5416
5417 case glslang::EOpFma:
5418 libCall = spv::GLSLstd450Fma;
5419 break;
5420 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005421 {
5422 libCall = spv::GLSLstd450FrexpStruct;
5423 assert(builder.isPointerType(typeId1));
5424 typeId1 = builder.getContainedTypeId(typeId1);
5425#ifdef AMD_EXTENSIONS
5426 int width = builder.getScalarTypeWidth(typeId1);
5427#else
5428 int width = 32;
5429#endif
5430 if (builder.getNumComponents(operands[0]) == 1)
5431 frexpIntType = builder.makeIntegerType(width, true);
5432 else
5433 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5434 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5435 consumedOperands = 1;
5436 }
John Kessenich55e7d112015-11-15 21:33:39 -07005437 break;
5438 case glslang::EOpLdexp:
5439 libCall = spv::GLSLstd450Ldexp;
5440 break;
5441
Rex Xu574ab042016-04-14 16:53:07 +08005442 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005443 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005444
Rex Xu9d93a232016-05-05 12:30:44 +08005445#ifdef AMD_EXTENSIONS
5446 case glslang::EOpSwizzleInvocations:
5447 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5448 libCall = spv::SwizzleInvocationsAMD;
5449 break;
5450 case glslang::EOpSwizzleInvocationsMasked:
5451 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5452 libCall = spv::SwizzleInvocationsMaskedAMD;
5453 break;
5454 case glslang::EOpWriteInvocation:
5455 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5456 libCall = spv::WriteInvocationAMD;
5457 break;
5458
5459 case glslang::EOpMin3:
5460 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5461 if (isFloat)
5462 libCall = spv::FMin3AMD;
5463 else {
5464 if (isUnsigned)
5465 libCall = spv::UMin3AMD;
5466 else
5467 libCall = spv::SMin3AMD;
5468 }
5469 break;
5470 case glslang::EOpMax3:
5471 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5472 if (isFloat)
5473 libCall = spv::FMax3AMD;
5474 else {
5475 if (isUnsigned)
5476 libCall = spv::UMax3AMD;
5477 else
5478 libCall = spv::SMax3AMD;
5479 }
5480 break;
5481 case glslang::EOpMid3:
5482 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5483 if (isFloat)
5484 libCall = spv::FMid3AMD;
5485 else {
5486 if (isUnsigned)
5487 libCall = spv::UMid3AMD;
5488 else
5489 libCall = spv::SMid3AMD;
5490 }
5491 break;
5492
5493 case glslang::EOpInterpolateAtVertex:
5494 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5495 libCall = spv::InterpolateAtVertexAMD;
5496 break;
5497#endif
5498
John Kessenich140f3df2015-06-26 16:58:36 -06005499 default:
5500 return 0;
5501 }
5502
5503 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005504 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005505 // Use an extended instruction from the standard library.
5506 // Construct the call arguments, without modifying the original operands vector.
5507 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5508 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005509 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005510 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005511 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005512 case 0:
5513 // should all be handled by visitAggregate and createNoArgOperation
5514 assert(0);
5515 return 0;
5516 case 1:
5517 // should all be handled by createUnaryOperation
5518 assert(0);
5519 return 0;
5520 case 2:
5521 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5522 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005523 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005524 // anything 3 or over doesn't have l-value operands, so all should be consumed
5525 assert(consumedOperands == operands.size());
5526 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005527 break;
5528 }
5529 }
5530
John Kessenich55e7d112015-11-15 21:33:39 -07005531 // Decode the return types that were structures
5532 switch (op) {
5533 case glslang::EOpAddCarry:
5534 case glslang::EOpSubBorrow:
5535 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5536 id = builder.createCompositeExtract(id, typeId0, 0);
5537 break;
5538 case glslang::EOpUMulExtended:
5539 case glslang::EOpIMulExtended:
5540 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5541 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5542 break;
5543 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005544 {
5545 assert(operands.size() == 2);
5546 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5547 // "exp" is floating-point type (from HLSL intrinsic)
5548 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5549 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5550 builder.createStore(member1, operands[1]);
5551 } else
5552 // "exp" is integer type (from GLSL built-in function)
5553 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5554 id = builder.createCompositeExtract(id, typeId0, 0);
5555 }
John Kessenich55e7d112015-11-15 21:33:39 -07005556 break;
5557 default:
5558 break;
5559 }
5560
John Kessenich32cfd492016-02-02 12:37:46 -07005561 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005562}
5563
Rex Xu9d93a232016-05-05 12:30:44 +08005564// Intrinsics with no arguments (or no return value, and no precision).
5565spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005566{
5567 // TODO: get the barrier operands correct
5568
5569 switch (op) {
5570 case glslang::EOpEmitVertex:
5571 builder.createNoResultOp(spv::OpEmitVertex);
5572 return 0;
5573 case glslang::EOpEndPrimitive:
5574 builder.createNoResultOp(spv::OpEndPrimitive);
5575 return 0;
5576 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005577 if (glslangIntermediate->getStage() == EShLangTessControl) {
5578 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5579 // TODO: prefer the following, when available:
5580 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5581 // spv::MemorySemanticsPatchMask |
5582 // spv::MemorySemanticsAcquireReleaseMask);
5583 } else {
5584 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5585 spv::MemorySemanticsWorkgroupMemoryMask |
5586 spv::MemorySemanticsAcquireReleaseMask);
5587 }
John Kessenich140f3df2015-06-26 16:58:36 -06005588 return 0;
5589 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005590 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5591 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005592 return 0;
5593 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005594 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5595 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005596 return 0;
5597 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005598 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5599 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005600 return 0;
5601 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005602 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5603 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005604 return 0;
5605 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005606 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5607 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005608 return 0;
5609 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005610 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5611 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005612 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005613 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005614 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005615 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005616 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005617 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005618 case glslang::EOpDeviceMemoryBarrier:
5619 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5620 spv::MemorySemanticsImageMemoryMask |
5621 spv::MemorySemanticsAcquireReleaseMask);
5622 return 0;
5623 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5624 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5625 spv::MemorySemanticsImageMemoryMask |
5626 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005627 return 0;
5628 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005629 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5630 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005631 return 0;
5632 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005633 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5634 spv::MemorySemanticsWorkgroupMemoryMask |
5635 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005636 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005637#ifdef AMD_EXTENSIONS
5638 case glslang::EOpTime:
5639 {
5640 std::vector<spv::Id> args; // Dummy arguments
5641 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5642 return builder.setPrecision(id, precision);
5643 }
5644#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005645 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005646 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005647 return 0;
5648 }
5649}
5650
5651spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5652{
John Kessenich2f273362015-07-18 22:34:27 -06005653 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005654 spv::Id id;
5655 if (symbolValues.end() != iter) {
5656 id = iter->second;
5657 return id;
5658 }
5659
5660 // it was not found, create it
5661 id = createSpvVariable(symbol);
5662 symbolValues[symbol->getId()] = id;
5663
Rex Xuc884b4a2016-06-29 15:03:44 +08005664 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005665 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005666 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005667 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005668 if (symbol->getType().getQualifier().hasSpecConstantId())
5669 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005670 if (symbol->getQualifier().hasIndex())
5671 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5672 if (symbol->getQualifier().hasComponent())
5673 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005674 // atomic counters use this:
5675 if (symbol->getQualifier().hasOffset())
5676 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005677 }
5678
scygan2c864272016-05-18 18:09:17 +02005679 if (symbol->getQualifier().hasLocation())
5680 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005681 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005682 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005683 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005684 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005685 }
John Kessenich140f3df2015-06-26 16:58:36 -06005686 if (symbol->getQualifier().hasSet())
5687 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005688 else if (IsDescriptorResource(symbol->getType())) {
5689 // default to 0
5690 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5691 }
John Kessenich140f3df2015-06-26 16:58:36 -06005692 if (symbol->getQualifier().hasBinding())
5693 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005694 if (symbol->getQualifier().hasAttachment())
5695 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005696 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005697 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005698 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005699 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005700 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005701 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005702 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5703 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5704 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5705 }
5706 if (symbol->getQualifier().hasXfbOffset())
5707 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005708 }
5709
Rex Xu1da878f2016-02-21 20:59:01 +08005710 if (symbol->getType().isImage()) {
5711 std::vector<spv::Decoration> memory;
5712 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5713 for (unsigned int i = 0; i < memory.size(); ++i)
5714 addDecoration(id, memory[i]);
5715 }
5716
John Kessenich140f3df2015-06-26 16:58:36 -06005717 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005718 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005719 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005720 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005721
John Kessenichecba76f2017-01-06 00:34:48 -07005722#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005723 if (builtIn == spv::BuiltInSampleMask) {
5724 spv::Decoration decoration;
5725 // GL_NV_sample_mask_override_coverage extension
5726 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005727 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005728 else
5729 decoration = (spv::Decoration)spv::DecorationMax;
5730 addDecoration(id, decoration);
5731 if (decoration != spv::DecorationMax) {
5732 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5733 }
5734 }
chaoc771d89f2017-01-13 01:10:53 -08005735 else if (builtIn == spv::BuiltInLayer) {
5736 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005737 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005738 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5739 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5740 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5741 }
John Kessenichb41bff62017-08-11 13:07:17 -06005742 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005743 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5744 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5745 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5746 }
5747 }
5748
chaoc6e5acae2016-12-20 13:28:52 -08005749 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005750 addDecoration(id, spv::DecorationPassthroughNV);
5751 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005752 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5753 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005754#endif
5755
John Kessenich140f3df2015-06-26 16:58:36 -06005756 return id;
5757}
5758
John Kessenich55e7d112015-11-15 21:33:39 -07005759// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005760void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5761{
John Kessenich4016e382016-07-15 11:53:56 -06005762 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005763 builder.addDecoration(id, dec);
5764}
5765
John Kessenich55e7d112015-11-15 21:33:39 -07005766// If 'dec' is valid, add a one-operand decoration to an object
5767void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5768{
John Kessenich4016e382016-07-15 11:53:56 -06005769 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005770 builder.addDecoration(id, dec, value);
5771}
5772
5773// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005774void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5775{
John Kessenich4016e382016-07-15 11:53:56 -06005776 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005777 builder.addMemberDecoration(id, (unsigned)member, dec);
5778}
5779
John Kessenich92187592016-02-01 13:45:25 -07005780// If 'dec' is valid, add a one-operand decoration to a struct member
5781void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5782{
John Kessenich4016e382016-07-15 11:53:56 -06005783 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005784 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5785}
5786
John Kessenich55e7d112015-11-15 21:33:39 -07005787// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005788// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005789//
5790// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5791//
5792// Recursively walk the nodes. The nodes form a tree whose leaves are
5793// regular constants, which themselves are trees that createSpvConstant()
5794// recursively walks. So, this function walks the "top" of the tree:
5795// - emit specialization constant-building instructions for specConstant
5796// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005797spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005798{
John Kessenich7cc0e282016-03-20 00:46:02 -06005799 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005800
qining4f4bb812016-04-03 23:55:17 -04005801 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005802 if (! node.getQualifier().specConstant) {
5803 // hand off to the non-spec-constant path
5804 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5805 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005806 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005807 nextConst, false);
5808 }
5809
5810 // We now know we have a specialization constant to build
5811
John Kessenichd94c0032016-05-30 19:29:40 -06005812 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005813 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5814 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5815 std::vector<spv::Id> dimConstId;
5816 for (int dim = 0; dim < 3; ++dim) {
5817 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5818 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5819 if (specConst)
5820 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5821 }
5822 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5823 }
5824
5825 // An AST node labelled as specialization constant should be a symbol node.
5826 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5827 if (auto* sn = node.getAsSymbolNode()) {
5828 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005829 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5830 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5831 // will set the builder into spec constant op instruction generating mode.
5832 sub_tree->traverse(this);
5833 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005834 } else if (auto* const_union_array = &sn->getConstArray()){
5835 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005836 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5837 builder.addName(id, sn->getName().c_str());
5838 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005839 }
5840 }
qining4f4bb812016-04-03 23:55:17 -04005841
5842 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5843 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005844 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005845 exit(1);
5846 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005847}
5848
John Kessenich140f3df2015-06-26 16:58:36 -06005849// Use 'consts' as the flattened glslang source of scalar constants to recursively
5850// build the aggregate SPIR-V constant.
5851//
5852// If there are not enough elements present in 'consts', 0 will be substituted;
5853// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5854//
qining08408382016-03-21 09:51:37 -04005855spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005856{
5857 // vector of constants for SPIR-V
5858 std::vector<spv::Id> spvConsts;
5859
5860 // Type is used for struct and array constants
5861 spv::Id typeId = convertGlslangToSpvType(glslangType);
5862
5863 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005864 glslang::TType elementType(glslangType, 0);
5865 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005866 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005867 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005868 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005869 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005870 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005871 } else if (glslangType.getStruct()) {
5872 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5873 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005874 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005875 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005876 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5877 bool zero = nextConst >= consts.size();
5878 switch (glslangType.getBasicType()) {
5879 case glslang::EbtInt:
5880 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5881 break;
5882 case glslang::EbtUint:
5883 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5884 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005885 case glslang::EbtInt64:
5886 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5887 break;
5888 case glslang::EbtUint64:
5889 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5890 break;
Rex Xucabbb782017-03-24 13:41:14 +08005891#ifdef AMD_EXTENSIONS
5892 case glslang::EbtInt16:
5893 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5894 break;
5895 case glslang::EbtUint16:
5896 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5897 break;
5898#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005899 case glslang::EbtFloat:
5900 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5901 break;
5902 case glslang::EbtDouble:
5903 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5904 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005905#ifdef AMD_EXTENSIONS
5906 case glslang::EbtFloat16:
5907 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5908 break;
5909#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005910 case glslang::EbtBool:
5911 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5912 break;
5913 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005914 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005915 break;
5916 }
5917 ++nextConst;
5918 }
5919 } else {
5920 // we have a non-aggregate (scalar) constant
5921 bool zero = nextConst >= consts.size();
5922 spv::Id scalar = 0;
5923 switch (glslangType.getBasicType()) {
5924 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005925 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005926 break;
5927 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005928 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005929 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005930 case glslang::EbtInt64:
5931 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5932 break;
5933 case glslang::EbtUint64:
5934 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5935 break;
Rex Xucabbb782017-03-24 13:41:14 +08005936#ifdef AMD_EXTENSIONS
5937 case glslang::EbtInt16:
5938 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5939 break;
5940 case glslang::EbtUint16:
5941 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5942 break;
5943#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005944 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005945 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005946 break;
5947 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005948 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005949 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005950#ifdef AMD_EXTENSIONS
5951 case glslang::EbtFloat16:
5952 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5953 break;
5954#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005955 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005956 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005957 break;
5958 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005959 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005960 break;
5961 }
5962 ++nextConst;
5963 return scalar;
5964 }
5965
5966 return builder.makeCompositeConstant(typeId, spvConsts);
5967}
5968
John Kessenich7c1aa102015-10-15 13:29:11 -06005969// Return true if the node is a constant or symbol whose reading has no
5970// non-trivial observable cost or effect.
5971bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5972{
5973 // don't know what this is
5974 if (node == nullptr)
5975 return false;
5976
5977 // a constant is safe
5978 if (node->getAsConstantUnion() != nullptr)
5979 return true;
5980
5981 // not a symbol means non-trivial
5982 if (node->getAsSymbolNode() == nullptr)
5983 return false;
5984
5985 // a symbol, depends on what's being read
5986 switch (node->getType().getQualifier().storage) {
5987 case glslang::EvqTemporary:
5988 case glslang::EvqGlobal:
5989 case glslang::EvqIn:
5990 case glslang::EvqInOut:
5991 case glslang::EvqConst:
5992 case glslang::EvqConstReadOnly:
5993 case glslang::EvqUniform:
5994 return true;
5995 default:
5996 return false;
5997 }
qining25262b32016-05-06 17:25:16 -04005998}
John Kessenich7c1aa102015-10-15 13:29:11 -06005999
6000// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006001// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006002// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006003// Return true if trivial.
6004bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6005{
6006 if (node == nullptr)
6007 return false;
6008
John Kessenich84cc15f2017-05-24 16:44:47 -06006009 // count non scalars as trivial, as well as anything coming from HLSL
6010 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006011 return true;
6012
John Kessenich7c1aa102015-10-15 13:29:11 -06006013 // symbols and constants are trivial
6014 if (isTrivialLeaf(node))
6015 return true;
6016
6017 // otherwise, it needs to be a simple operation or one or two leaf nodes
6018
6019 // not a simple operation
6020 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6021 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6022 if (binaryNode == nullptr && unaryNode == nullptr)
6023 return false;
6024
6025 // not on leaf nodes
6026 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6027 return false;
6028
6029 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6030 return false;
6031 }
6032
6033 switch (node->getAsOperator()->getOp()) {
6034 case glslang::EOpLogicalNot:
6035 case glslang::EOpConvIntToBool:
6036 case glslang::EOpConvUintToBool:
6037 case glslang::EOpConvFloatToBool:
6038 case glslang::EOpConvDoubleToBool:
6039 case glslang::EOpEqual:
6040 case glslang::EOpNotEqual:
6041 case glslang::EOpLessThan:
6042 case glslang::EOpGreaterThan:
6043 case glslang::EOpLessThanEqual:
6044 case glslang::EOpGreaterThanEqual:
6045 case glslang::EOpIndexDirect:
6046 case glslang::EOpIndexDirectStruct:
6047 case glslang::EOpLogicalXor:
6048 case glslang::EOpAny:
6049 case glslang::EOpAll:
6050 return true;
6051 default:
6052 return false;
6053 }
6054}
6055
6056// Emit short-circuiting code, where 'right' is never evaluated unless
6057// the left side is true (for &&) or false (for ||).
6058spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6059{
6060 spv::Id boolTypeId = builder.makeBoolType();
6061
6062 // emit left operand
6063 builder.clearAccessChain();
6064 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006065 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006066
6067 // Operands to accumulate OpPhi operands
6068 std::vector<spv::Id> phiOperands;
6069 // accumulate left operand's phi information
6070 phiOperands.push_back(leftId);
6071 phiOperands.push_back(builder.getBuildPoint()->getId());
6072
6073 // Make the two kinds of operation symmetric with a "!"
6074 // || => emit "if (! left) result = right"
6075 // && => emit "if ( left) result = right"
6076 //
6077 // TODO: this runtime "not" for || could be avoided by adding functionality
6078 // to 'builder' to have an "else" without an "then"
6079 if (op == glslang::EOpLogicalOr)
6080 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6081
6082 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006083 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006084
6085 // emit right operand as the "then" part of the "if"
6086 builder.clearAccessChain();
6087 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006088 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006089
6090 // accumulate left operand's phi information
6091 phiOperands.push_back(rightId);
6092 phiOperands.push_back(builder.getBuildPoint()->getId());
6093
6094 // finish the "if"
6095 ifBuilder.makeEndIf();
6096
6097 // phi together the two results
6098 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6099}
6100
Frank Henigman541f7bb2018-01-16 00:18:26 -05006101#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006102// Return type Id of the imported set of extended instructions corresponds to the name.
6103// Import this set if it has not been imported yet.
6104spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6105{
6106 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6107 return extBuiltinMap[name];
6108 else {
Rex Xu51596642016-09-21 18:56:12 +08006109 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006110 spv::Id extBuiltins = builder.import(name);
6111 extBuiltinMap[name] = extBuiltins;
6112 return extBuiltins;
6113 }
6114}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006115#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006116
John Kessenich140f3df2015-06-26 16:58:36 -06006117}; // end anonymous namespace
6118
6119namespace glslang {
6120
John Kessenich68d78fd2015-07-12 19:28:10 -06006121void GetSpirvVersion(std::string& version)
6122{
John Kessenich9e55f632015-07-15 10:03:39 -06006123 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006124 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006125 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006126 version = buf;
6127}
6128
John Kessenicha372a3e2017-11-02 22:32:14 -06006129// For low-order part of the generator's magic number. Bump up
6130// when there is a change in the style (e.g., if SSA form changes,
6131// or a different instruction sequence to do something gets used).
6132int GetSpirvGeneratorVersion()
6133{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006134 // return 1; // start
6135 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006136 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
6137 return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenicha372a3e2017-11-02 22:32:14 -06006138}
6139
John Kessenich140f3df2015-06-26 16:58:36 -06006140// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006141void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006142{
6143 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006144 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006145 if (out.fail())
6146 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006147 for (int i = 0; i < (int)spirv.size(); ++i) {
6148 unsigned int word = spirv[i];
6149 out.write((const char*)&word, 4);
6150 }
6151 out.close();
6152}
6153
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006154// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006155void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006156{
6157 std::ofstream out;
6158 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006159 if (out.fail())
6160 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006161 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006162 if (varName != nullptr) {
6163 out << "\t #pragma once" << std::endl;
6164 out << "const uint32_t " << varName << "[] = {" << std::endl;
6165 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006166 const int WORDS_PER_LINE = 8;
6167 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6168 out << "\t";
6169 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6170 const unsigned int word = spirv[i + j];
6171 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6172 if (i + j + 1 < (int)spirv.size()) {
6173 out << ",";
6174 }
6175 }
6176 out << std::endl;
6177 }
Flavio15017db2017-02-15 14:29:33 -08006178 if (varName != nullptr) {
6179 out << "};";
6180 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006181 out.close();
6182}
6183
GregFcd1f1692017-09-21 18:40:22 -06006184#ifdef ENABLE_OPT
6185void errHandler(const std::string& str) {
6186 std::cerr << str << std::endl;
6187}
6188#endif
6189
John Kessenich140f3df2015-06-26 16:58:36 -06006190//
6191// Set up the glslang traversal
6192//
John Kessenich121853f2017-05-31 17:11:16 -06006193void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006194{
Lei Zhang17535f72016-05-04 15:55:59 -04006195 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006196 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006197}
6198
John Kessenich121853f2017-05-31 17:11:16 -06006199void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6200 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006201{
John Kessenich140f3df2015-06-26 16:58:36 -06006202 TIntermNode* root = intermediate.getTreeRoot();
6203
6204 if (root == 0)
6205 return;
6206
John Kessenich121853f2017-05-31 17:11:16 -06006207 glslang::SpvOptions defaultOptions;
6208 if (options == nullptr)
6209 options = &defaultOptions;
6210
John Kessenich140f3df2015-06-26 16:58:36 -06006211 glslang::GetThreadPoolAllocator().push();
6212
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006213 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006214 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006215 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006216 it.dumpSpv(spirv);
6217
GregFcd1f1692017-09-21 18:40:22 -06006218#ifdef ENABLE_OPT
6219 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6220 // eg. forward and remove memory writes of opaque types.
6221 if ((intermediate.getSource() == EShSourceHlsl ||
6222 options->optimizeSize) &&
6223 !options->disableOptimizer) {
6224 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6225
6226 spvtools::Optimizer optimizer(target_env);
6227 optimizer.SetMessageConsumer([](spv_message_level_t level,
6228 const char* source,
6229 const spv_position_t& position,
6230 const char* message) {
6231 std::cerr << StringifyMessage(level, source, position, message)
6232 << std::endl;
6233 });
6234
6235 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006236 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6237 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006238 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6239 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6240 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6241 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006242 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006243 optimizer.RegisterPass(CreateAggressiveDCEPass());
6244 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006245 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006246 optimizer.RegisterPass(CreateBlockMergePass());
6247 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6248 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006249 optimizer.RegisterPass(CreateDeadInsertElimPass());
6250 if (options->optimizeSize) {
6251 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6252 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6253 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6254 }
GregFcd1f1692017-09-21 18:40:22 -06006255 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006256
6257 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6258 return;
6259
6260 // Remove dead module-level objects: functions, types, vars
6261 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6262 spv::spirvbin_t Remapper(0);
6263 Remapper.registerErrorHandler(errHandler);
6264 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6265 }
6266#endif
6267
John Kessenich140f3df2015-06-26 16:58:36 -06006268 glslang::GetThreadPoolAllocator().pop();
6269}
6270
6271}; // end namespace glslang