blob: 1661d5b1ea97bba666ae8682918c4d1b37aad591 [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"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800125 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600126 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600127 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
129 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600130 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
131 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
132 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700134 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600135 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600136 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
137 glslang::TLayoutPacking, const glslang::TQualifier&);
138 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
139 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700140 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700141 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800142 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600143 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700144 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
147 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 +0100148 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600149
John Kessenich6fccb3c2016-09-19 16:01:41 -0600150 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void makeFunctions(const glslang::TIntermSequence&);
152 void makeGlobalInitializers(const glslang::TIntermSequence&);
153 void visitFunctions(const glslang::TIntermSequence&);
154 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600156 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
157 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
159
qining25262b32016-05-06 17:25:16 -0400160 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);
161 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
162 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 +0800163 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 +0800164 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 -0600165 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800166 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 +0800167 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800168 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600169 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 +0800170 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
172 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700173 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700175 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400176 spv::Id createSpvConstant(const glslang::TIntermTyped&);
177 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600178 bool isTrivialLeaf(const glslang::TIntermTyped* node);
179 bool isTrivial(const glslang::TIntermTyped* node);
180 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800181 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich121853f2017-05-31 17:11:16 -0600183 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600185 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700186 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600187 int sequenceDepth;
188
Lei Zhang17535f72016-05-04 15:55:59 -0400189 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400190
John Kessenich140f3df2015-06-26 16:58:36 -0600191 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
192 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700193 bool inEntryPoint;
194 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700195 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 -0700196 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600197 const glslang::TIntermediate* glslangIntermediate;
198 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800199 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600200
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600202 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700204 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600205 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 -0600206 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600207};
208
209//
210// Helper functions for translating glslang representations to SPIR-V enumerants.
211//
212
213// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700214spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600215{
John Kessenich66e2faf2016-03-12 18:34:36 -0700216 switch (source) {
217 case glslang::EShSourceGlsl:
218 switch (profile) {
219 case ENoProfile:
220 case ECoreProfile:
221 case ECompatibilityProfile:
222 return spv::SourceLanguageGLSL;
223 case EEsProfile:
224 return spv::SourceLanguageESSL;
225 default:
226 return spv::SourceLanguageUnknown;
227 }
228 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600229 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 default:
231 return spv::SourceLanguageUnknown;
232 }
233}
234
235// Translate glslang language (stage) to SPIR-V execution model.
236spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
237{
238 switch (stage) {
239 case EShLangVertex: return spv::ExecutionModelVertex;
240 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
241 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
242 case EShLangGeometry: return spv::ExecutionModelGeometry;
243 case EShLangFragment: return spv::ExecutionModelFragment;
244 case EShLangCompute: return spv::ExecutionModelGLCompute;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::ExecutionModelFragment;
248 }
249}
250
John Kessenich140f3df2015-06-26 16:58:36 -0600251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
John Kessenichf6640762016-08-01 19:44:00 -0600268// Translate glslang precision to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenichf6640762016-08-01 19:44:00 -0600271 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang type to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
281{
282 return TranslatePrecisionDecoration(type.getQualifier().precision);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600286spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.getBasicType() == glslang::EbtBlock) {
289 switch (type.getQualifier().storage) {
290 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600291 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::EvqVaryingIn: return spv::DecorationBlock;
293 case glslang::EvqVaryingOut: return spv::DecorationBlock;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 break;
297 }
298 }
299
John Kessenich4016e382016-07-15 11:53:56 -0600300 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600301}
302
Rex Xu1da878f2016-02-21 20:59:01 +0800303// Translate glslang type to SPIR-V memory decorations.
304void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
305{
306 if (qualifier.coherent)
307 memory.push_back(spv::DecorationCoherent);
308 if (qualifier.volatil)
309 memory.push_back(spv::DecorationVolatile);
310 if (qualifier.restrict)
311 memory.push_back(spv::DecorationRestrict);
312 if (qualifier.readonly)
313 memory.push_back(spv::DecorationNonWritable);
314 if (qualifier.writeonly)
315 memory.push_back(spv::DecorationNonReadable);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700319spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::ElmRowMajor:
324 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 default:
328 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 }
331 } else {
332 switch (type.getBasicType()) {
333 default:
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 break;
336 case glslang::EbtBlock:
337 switch (type.getQualifier().storage) {
338 case glslang::EvqUniform:
339 case glslang::EvqBuffer:
340 switch (type.getQualifier().layoutPacking) {
341 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 }
346 case glslang::EvqVaryingIn:
347 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600349 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 }
355 }
356}
357
358// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600359// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700360// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800361spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600362{
Rex Xubbceed72016-05-21 09:40:44 +0800363 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700367 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800370#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800371 else if (qualifier.explicitInterp) {
372 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800373 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800374 }
Rex Xu9d93a232016-05-05 12:30:44 +0800375#endif
Rex Xubbceed72016-05-21 09:40:44 +0800376 else
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378}
379
380// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800382// should be applied.
383spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
384{
385 if (qualifier.patch)
386 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700389 else if (qualifier.sample) {
390 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700392 } else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600394}
395
John Kessenich92187592016-02-01 13:45:25 -0700396// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationInvariant;
401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600403}
404
qining9220dbb2016-05-04 17:34:38 -0400405// If glslang type is noContraction, return SPIR-V NoContraction decoration.
406spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
407{
408 if (qualifier.noContraction)
409 return spv::DecorationNoContraction;
410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400412}
413
David Netoa901ffe2016-06-08 14:11:40 +0100414// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
415// associated capabilities when required. For some built-in variables, a capability
416// is generated only when using the variable in an executable instruction, but not when
417// just declaring a struct member variable with it. This is true for PointSize,
418// ClipDistance, and CullDistance.
419spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
421 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700422 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600423 // Defer adding the capability until the built-in is actually used.
424 if (! memberDeclaration) {
425 switch (glslangIntermediate->getStage()) {
426 case EShLangGeometry:
427 builder.addCapability(spv::CapabilityGeometryPointSize);
428 break;
429 case EShLangTessControl:
430 case EShLangTessEvaluation:
431 builder.addCapability(spv::CapabilityTessellationPointSize);
432 break;
433 default:
434 break;
435 }
John Kessenich92187592016-02-01 13:45:25 -0700436 }
437 return spv::BuiltInPointSize;
438
John Kessenichebb50532016-05-16 19:22:05 -0600439 // These *Distance capabilities logically belong here, but if the member is declared and
440 // then never used, consumers of SPIR-V prefer the capability not be declared.
441 // They are now generated when used, rather than here when declared.
442 // Potentially, the specification should be more clear what the minimum
443 // use needed is to trigger the capability.
444 //
John Kessenich92187592016-02-01 13:45:25 -0700445 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100446 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800447 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700448 return spv::BuiltInClipDistance;
449
450 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100451 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800452 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInCullDistance;
454
455 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800456 if (!memberDeclaration) {
457 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800458#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800459 if (glslangIntermediate->getStage() == EShLangVertex ||
460 glslangIntermediate->getStage() == EShLangTessControl ||
461 glslangIntermediate->getStage() == EShLangTessEvaluation) {
462
463 builder.addExtension(spv::E_SPV_NV_viewport_array2);
464 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
465 }
chaoc771d89f2017-01-13 01:10:53 -0800466#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800467 }
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInViewportIndex;
469
John Kessenich5e801132016-02-15 11:09:46 -0700470 case glslang::EbvSampleId:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSampleId;
473
474 case glslang::EbvSamplePosition:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSamplePosition;
477
478 case glslang::EbvSampleMask:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleMask;
481
John Kessenich78a45572016-07-08 14:05:15 -0600482 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
chaoc771d89f2017-01-13 01:10:53 -0800490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
495
John Kessenich78a45572016-07-08 14:05:15 -0600496 return spv::BuiltInLayer;
497
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvVertexId: return spv::BuiltInVertexId;
500 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700501 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
502 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800505 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
506 builder.addCapability(spv::CapabilityDrawParameters);
507 return spv::BuiltInBaseVertex;
508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
519 case glslang::EbvPrimitiveId:
520 if (glslangIntermediate->getStage() == EShLangFragment)
521 builder.addCapability(spv::CapabilityGeometry);
522 return spv::BuiltInPrimitiveId;
523
Rex Xu37cdcee2017-06-29 17:46:34 +0800524 case glslang::EbvFragStencilRef:
525 logger->missingFunctionality("shader stencil export");
526 return spv::BuiltInMax;
527
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
530 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
531 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
532 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
533 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
534 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
535 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
537 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
538 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
539 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
540 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
541 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
542 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
543 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupSize;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupLocalInvocationId;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupEqMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupGeMaskKHR;
564
Rex Xu574ab042016-04-14 16:53:07 +0800565 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
568 return spv::BuiltInSubgroupGtMaskKHR;
569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupLeMaskKHR;
574
Rex Xu574ab042016-04-14 16:53:07 +0800575 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
577 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
578 return spv::BuiltInSubgroupLtMaskKHR;
579
Rex Xu9d93a232016-05-05 12:30:44 +0800580#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800581 case glslang::EbvBaryCoordNoPersp:
582 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
583 return spv::BuiltInBaryCoordNoPerspAMD;
584
585 case glslang::EbvBaryCoordNoPerspCentroid:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
588
589 case glslang::EbvBaryCoordNoPerspSample:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordNoPerspSampleAMD;
592
593 case glslang::EbvBaryCoordSmooth:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordSmoothAMD;
596
597 case glslang::EbvBaryCoordSmoothCentroid:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordSmoothCentroidAMD;
600
601 case glslang::EbvBaryCoordSmoothSample:
602 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
603 return spv::BuiltInBaryCoordSmoothSampleAMD;
604
605 case glslang::EbvBaryCoordPullModel:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800608#endif
chaoc771d89f2017-01-13 01:10:53 -0800609
John Kessenich6c8aaac2017-02-27 01:20:51 -0700610 case glslang::EbvDeviceIndex:
611 builder.addExtension(spv::E_SPV_KHR_device_group);
612 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700613 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614
615 case glslang::EbvViewIndex:
616 builder.addExtension(spv::E_SPV_KHR_multiview);
617 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700618 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700619
chaoc771d89f2017-01-13 01:10:53 -0800620#ifdef NV_EXTENSIONS
621 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_viewport_array2);
624 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInViewportMaskNV;
627 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryPositionNV;
633 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
636 builder.addCapability(spv::CapabilityShaderStereoViewNV);
637 }
chaoc771d89f2017-01-13 01:10:53 -0800638 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800639 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInPositionPerViewNV;
645 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
648 builder.addCapability(spv::CapabilityPerViewAttributesNV);
649 }
chaocdf3956c2017-02-14 14:52:34 -0800650 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800651#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800652 default:
653 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655}
656
Rex Xufc618912015-09-09 16:42:49 +0800657// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700658spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800659{
660 assert(type.getBasicType() == glslang::EbtSampler);
661
John Kessenich5d0fa972016-02-15 11:57:00 -0700662 // Check for capabilities
663 switch (type.getQualifier().layoutFormat) {
664 case glslang::ElfRg32f:
665 case glslang::ElfRg16f:
666 case glslang::ElfR11fG11fB10f:
667 case glslang::ElfR16f:
668 case glslang::ElfRgba16:
669 case glslang::ElfRgb10A2:
670 case glslang::ElfRg16:
671 case glslang::ElfRg8:
672 case glslang::ElfR16:
673 case glslang::ElfR8:
674 case glslang::ElfRgba16Snorm:
675 case glslang::ElfRg16Snorm:
676 case glslang::ElfRg8Snorm:
677 case glslang::ElfR16Snorm:
678 case glslang::ElfR8Snorm:
679
680 case glslang::ElfRg32i:
681 case glslang::ElfRg16i:
682 case glslang::ElfRg8i:
683 case glslang::ElfR16i:
684 case glslang::ElfR8i:
685
686 case glslang::ElfRgb10a2ui:
687 case glslang::ElfRg32ui:
688 case glslang::ElfRg16ui:
689 case glslang::ElfRg8ui:
690 case glslang::ElfR16ui:
691 case glslang::ElfR8ui:
692 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
693 break;
694
695 default:
696 break;
697 }
698
699 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800700 switch (type.getQualifier().layoutFormat) {
701 case glslang::ElfNone: return spv::ImageFormatUnknown;
702 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
703 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
704 case glslang::ElfR32f: return spv::ImageFormatR32f;
705 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
706 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
707 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
708 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
709 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
710 case glslang::ElfR16f: return spv::ImageFormatR16f;
711 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
712 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
713 case glslang::ElfRg16: return spv::ImageFormatRg16;
714 case glslang::ElfRg8: return spv::ImageFormatRg8;
715 case glslang::ElfR16: return spv::ImageFormatR16;
716 case glslang::ElfR8: return spv::ImageFormatR8;
717 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
718 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
719 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
720 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
721 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
722 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
723 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
724 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
725 case glslang::ElfR32i: return spv::ImageFormatR32i;
726 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
727 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
728 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
729 case glslang::ElfR16i: return spv::ImageFormatR16i;
730 case glslang::ElfR8i: return spv::ImageFormatR8i;
731 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
732 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
733 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
734 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
735 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
736 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
737 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
738 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
739 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
740 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600741 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800742 }
743}
744
Rex Xu57e65922017-07-04 23:23:40 +0800745spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
746{
747 switch (selectionControl) {
748 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
749 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
750 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
751 default: return spv::SelectionControlMaskNone;
752 }
753}
754
steve-lunargf1709e72017-05-02 20:14:50 -0600755spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
756{
757 switch (loopControl) {
758 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
759 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
760 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
761 // TODO: DependencyInfinite
762 // TODO: DependencyLength
763 default: return spv::LoopControlMaskNone;
764 }
765}
766
John Kessenicha5c5fb62017-05-05 05:09:58 -0600767// Translate glslang type to SPIR-V storage class.
768spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
769{
770 if (type.getQualifier().isPipeInput())
771 return spv::StorageClassInput;
772 else if (type.getQualifier().isPipeOutput())
773 return spv::StorageClassOutput;
774 else if (type.getBasicType() == glslang::EbtAtomicUint)
775 return spv::StorageClassAtomicCounter;
776 else if (type.containsOpaque())
777 return spv::StorageClassUniformConstant;
778 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
779 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
780 return spv::StorageClassStorageBuffer;
781 } else if (type.getQualifier().isUniformOrBuffer()) {
782 if (type.getQualifier().layoutPushConstant)
783 return spv::StorageClassPushConstant;
784 if (type.getBasicType() == glslang::EbtBlock)
785 return spv::StorageClassUniform;
786 else
787 return spv::StorageClassUniformConstant;
788 } else {
789 switch (type.getQualifier().storage) {
790 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
791 case glslang::EvqGlobal: return spv::StorageClassPrivate;
792 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
793 case glslang::EvqTemporary: return spv::StorageClassFunction;
794 default:
795 assert(0);
796 return spv::StorageClassFunction;
797 }
798 }
799}
800
qining25262b32016-05-06 17:25:16 -0400801// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700802// descriptor set.
803bool IsDescriptorResource(const glslang::TType& type)
804{
John Kessenichf7497e22016-03-08 21:36:22 -0700805 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700806 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700807 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700808
809 // non block...
810 // basically samplerXXX/subpass/sampler/texture are all included
811 // if they are the global-scope-class, not the function parameter
812 // (or local, if they ever exist) class.
813 if (type.getBasicType() == glslang::EbtSampler)
814 return type.getQualifier().isUniformOrBuffer();
815
816 // None of the above.
817 return false;
818}
819
John Kesseniche0b6cad2015-12-24 10:30:13 -0700820void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
821{
822 if (child.layoutMatrix == glslang::ElmNone)
823 child.layoutMatrix = parent.layoutMatrix;
824
825 if (parent.invariant)
826 child.invariant = true;
827 if (parent.nopersp)
828 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800829#ifdef AMD_EXTENSIONS
830 if (parent.explicitInterp)
831 child.explicitInterp = true;
832#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833 if (parent.flat)
834 child.flat = true;
835 if (parent.centroid)
836 child.centroid = true;
837 if (parent.patch)
838 child.patch = true;
839 if (parent.sample)
840 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800841 if (parent.coherent)
842 child.coherent = true;
843 if (parent.volatil)
844 child.volatil = true;
845 if (parent.restrict)
846 child.restrict = true;
847 if (parent.readonly)
848 child.readonly = true;
849 if (parent.writeonly)
850 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851}
852
John Kessenichf2b7f332016-09-01 17:05:23 -0600853bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700854{
John Kessenich7b9fa252016-01-21 18:56:57 -0700855 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600856 // - struct members might inherit from a struct declaration
857 // (note that non-block structs don't explicitly inherit,
858 // only implicitly, meaning no decoration involved)
859 // - affect decorations on the struct members
860 // (note smooth does not, and expecting something like volatile
861 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700862 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600863 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864}
865
John Kessenich140f3df2015-06-26 16:58:36 -0600866//
867// Implement the TGlslangToSpvTraverser class.
868//
869
John Kessenich121853f2017-05-31 17:11:16 -0600870TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
871 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
872 : TIntermTraverser(true, false, true),
873 options(options),
874 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600875 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400876 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700877 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600878 glslangIntermediate(glslangIntermediate)
879{
880 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
881
882 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700883 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600884 if (options.generateDebugInfo) {
885 builder.setSourceFile(glslangIntermediate->getSourceFile());
886 builder.setSourceText(glslangIntermediate->getSourceText());
John Kesseniche485c7a2017-05-31 18:50:53 -0600887 builder.setEmitOpLines();
John Kessenich121853f2017-05-31 17:11:16 -0600888 }
John Kessenich140f3df2015-06-26 16:58:36 -0600889 stdBuiltins = builder.import("GLSL.std.450");
890 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600891 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
892 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600895 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
896 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600897 builder.addSourceExtension(it->c_str());
898
899 // Add the top-level modes for this shader.
900
John Kessenich92187592016-02-01 13:45:25 -0700901 if (glslangIntermediate->getXfbMode()) {
902 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600903 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700904 }
John Kessenich140f3df2015-06-26 16:58:36 -0600905
906 unsigned int mode;
907 switch (glslangIntermediate->getStage()) {
908 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600909 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600910 break;
911
steve-lunarge7412492017-03-23 11:56:07 -0600912 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600913 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600914 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600915
steve-lunarge7412492017-03-23 11:56:07 -0600916 glslang::TLayoutGeometry primitive;
917
918 if (glslangIntermediate->getStage() == EShLangTessControl) {
919 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
920 primitive = glslangIntermediate->getOutputPrimitive();
921 } else {
922 primitive = glslangIntermediate->getInputPrimitive();
923 }
924
925 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700926 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
927 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
928 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600929 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600930 }
John Kessenich4016e382016-07-15 11:53:56 -0600931 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600932 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
933
John Kesseniche6903322015-10-13 16:29:02 -0600934 switch (glslangIntermediate->getVertexSpacing()) {
935 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
936 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
937 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600938 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600939 }
John Kessenich4016e382016-07-15 11:53:56 -0600940 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600941 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
942
943 switch (glslangIntermediate->getVertexOrder()) {
944 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
945 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600946 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600947 }
John Kessenich4016e382016-07-15 11:53:56 -0600948 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600949 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
950
951 if (glslangIntermediate->getPointMode())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 break;
954
955 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 switch (glslangIntermediate->getInputPrimitive()) {
958 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
959 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
960 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700961 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600962 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600963 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
John Kessenich4016e382016-07-15 11:53:56 -0600965 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600966 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600967
John Kessenich140f3df2015-06-26 16:58:36 -0600968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
969
970 switch (glslangIntermediate->getOutputPrimitive()) {
971 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
972 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
973 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600974 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600975 }
John Kessenich4016e382016-07-15 11:53:56 -0600976 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600977 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
978 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
979 break;
980
981 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600982 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600983 if (glslangIntermediate->getPixelCenterInteger())
984 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600985
John Kessenich140f3df2015-06-26 16:58:36 -0600986 if (glslangIntermediate->getOriginUpperLeft())
987 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600988 else
989 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600990
991 if (glslangIntermediate->getEarlyFragmentTests())
992 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
993
chaocc1204522017-06-30 17:14:30 -0700994 if (glslangIntermediate->getPostDepthCoverage()) {
995 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
996 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
997 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
998 }
999
John Kesseniche6903322015-10-13 16:29:02 -06001000 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001001 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1002 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001003 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001004 }
John Kessenich4016e382016-07-15 11:53:56 -06001005 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001006 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1007
1008 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1009 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001010 break;
1011
1012 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001013 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001014 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1015 glslangIntermediate->getLocalSize(1),
1016 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001017 break;
1018
1019 default:
1020 break;
1021 }
John Kessenich140f3df2015-06-26 16:58:36 -06001022}
1023
John Kessenichfca82622016-11-26 13:23:20 -07001024// Finish creating SPV, after the traversal is complete.
1025void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001026{
John Kessenich517fe7a2016-11-26 13:31:47 -07001027 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001028 builder.setBuildPoint(shaderEntry->getLastBlock());
1029 builder.leaveFunction();
1030 }
1031
John Kessenich7ba63412015-12-20 17:37:07 -07001032 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001033 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1034 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001035
qiningda397332016-03-09 19:54:03 -05001036 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001037}
1038
John Kessenichfca82622016-11-26 13:23:20 -07001039// Write the SPV into 'out'.
1040void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001041{
John Kessenichfca82622016-11-26 13:23:20 -07001042 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001043}
1044
1045//
1046// Implement the traversal functions.
1047//
1048// Return true from interior nodes to have the external traversal
1049// continue on to children. Return false if children were
1050// already processed.
1051//
1052
1053//
qining25262b32016-05-06 17:25:16 -04001054// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001055// - uniform/input reads
1056// - output writes
1057// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1058// - something simple that degenerates into the last bullet
1059//
1060void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1061{
qining75d1d802016-04-06 14:42:01 -04001062 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1063 if (symbol->getType().getQualifier().isSpecConstant())
1064 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1065
John Kessenich140f3df2015-06-26 16:58:36 -06001066 // getSymbolId() will set up all the IO decorations on the first call.
1067 // Formal function parameters were mapped during makeFunctions().
1068 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001069
1070 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1071 if (builder.isPointer(id)) {
1072 spv::StorageClass sc = builder.getStorageClass(id);
1073 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1074 iOSet.insert(id);
1075 }
1076
1077 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001078 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001079 // Prepare to generate code for the access
1080
1081 // L-value chains will be computed left to right. We're on the symbol now,
1082 // which is the left-most part of the access chain, so now is "clear" time,
1083 // followed by setting the base.
1084 builder.clearAccessChain();
1085
1086 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001087 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001088 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001089 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001090 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001091 // These are also pure R-values.
1092 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001093 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001094 builder.setAccessChainRValue(id);
1095 else
1096 builder.setAccessChainLValue(id);
1097 }
1098}
1099
1100bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1101{
John Kesseniche485c7a2017-05-31 18:50:53 -06001102 builder.setLine(node->getLoc().line);
1103
qining40887662016-04-03 22:20:42 -04001104 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1105 if (node->getType().getQualifier().isSpecConstant())
1106 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1107
John Kessenich140f3df2015-06-26 16:58:36 -06001108 // First, handle special cases
1109 switch (node->getOp()) {
1110 case glslang::EOpAssign:
1111 case glslang::EOpAddAssign:
1112 case glslang::EOpSubAssign:
1113 case glslang::EOpMulAssign:
1114 case glslang::EOpVectorTimesMatrixAssign:
1115 case glslang::EOpVectorTimesScalarAssign:
1116 case glslang::EOpMatrixTimesScalarAssign:
1117 case glslang::EOpMatrixTimesMatrixAssign:
1118 case glslang::EOpDivAssign:
1119 case glslang::EOpModAssign:
1120 case glslang::EOpAndAssign:
1121 case glslang::EOpInclusiveOrAssign:
1122 case glslang::EOpExclusiveOrAssign:
1123 case glslang::EOpLeftShiftAssign:
1124 case glslang::EOpRightShiftAssign:
1125 // A bin-op assign "a += b" means the same thing as "a = a + b"
1126 // where a is evaluated before b. For a simple assignment, GLSL
1127 // says to evaluate the left before the right. So, always, left
1128 // node then right node.
1129 {
1130 // get the left l-value, save it away
1131 builder.clearAccessChain();
1132 node->getLeft()->traverse(this);
1133 spv::Builder::AccessChain lValue = builder.getAccessChain();
1134
1135 // evaluate the right
1136 builder.clearAccessChain();
1137 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001138 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001139
1140 if (node->getOp() != glslang::EOpAssign) {
1141 // the left is also an r-value
1142 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001143 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001146 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001147 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001148 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1149 node->getType().getBasicType());
1150
1151 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001152 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001153 }
1154
1155 // store the result
1156 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001157 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001158
1159 // assignments are expressions having an rValue after they are evaluated...
1160 builder.clearAccessChain();
1161 builder.setAccessChainRValue(rValue);
1162 }
1163 return false;
1164 case glslang::EOpIndexDirect:
1165 case glslang::EOpIndexDirectStruct:
1166 {
1167 // Get the left part of the access chain.
1168 node->getLeft()->traverse(this);
1169
1170 // Add the next element in the chain
1171
David Netoa901ffe2016-06-08 14:11:40 +01001172 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001173 if (! node->getLeft()->getType().isArray() &&
1174 node->getLeft()->getType().isVector() &&
1175 node->getOp() == glslang::EOpIndexDirect) {
1176 // This is essentially a hard-coded vector swizzle of size 1,
1177 // so short circuit the access-chain stuff with a swizzle.
1178 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001179 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001180 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001181 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001182 int spvIndex = glslangIndex;
1183 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1184 node->getOp() == glslang::EOpIndexDirectStruct)
1185 {
1186 // This may be, e.g., an anonymous block-member selection, which generally need
1187 // index remapping due to hidden members in anonymous blocks.
1188 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1189 assert(remapper.size() > 0);
1190 spvIndex = remapper[glslangIndex];
1191 }
John Kessenichebb50532016-05-16 19:22:05 -06001192
David Netoa901ffe2016-06-08 14:11:40 +01001193 // normal case for indexing array or structure or block
1194 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1195
1196 // Add capabilities here for accessing PointSize and clip/cull distance.
1197 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001198 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001199 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001200 }
1201 }
1202 return false;
1203 case glslang::EOpIndexIndirect:
1204 {
1205 // Structure or array or vector indirection.
1206 // Will use native SPIR-V access-chain for struct and array indirection;
1207 // matrices are arrays of vectors, so will also work for a matrix.
1208 // Will use the access chain's 'component' for variable index into a vector.
1209
1210 // This adapter is building access chains left to right.
1211 // Set up the access chain to the left.
1212 node->getLeft()->traverse(this);
1213
1214 // save it so that computing the right side doesn't trash it
1215 spv::Builder::AccessChain partial = builder.getAccessChain();
1216
1217 // compute the next index in the chain
1218 builder.clearAccessChain();
1219 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001220 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001221
1222 // restore the saved access chain
1223 builder.setAccessChain(partial);
1224
1225 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001226 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001227 else
John Kessenichfa668da2015-09-13 14:46:30 -06001228 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001229 }
1230 return false;
1231 case glslang::EOpVectorSwizzle:
1232 {
1233 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001234 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001236 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001237 }
1238 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001239 case glslang::EOpMatrixSwizzle:
1240 logger->missingFunctionality("matrix swizzle");
1241 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001242 case glslang::EOpLogicalOr:
1243 case glslang::EOpLogicalAnd:
1244 {
1245
1246 // These may require short circuiting, but can sometimes be done as straight
1247 // binary operations. The right operand must be short circuited if it has
1248 // side effects, and should probably be if it is complex.
1249 if (isTrivial(node->getRight()->getAsTyped()))
1250 break; // handle below as a normal binary operation
1251 // otherwise, we need to do dynamic short circuiting on the right operand
1252 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1253 builder.clearAccessChain();
1254 builder.setAccessChainRValue(result);
1255 }
1256 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001257 default:
1258 break;
1259 }
1260
1261 // Assume generic binary op...
1262
John Kessenich32cfd492016-02-02 12:37:46 -07001263 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001264 builder.clearAccessChain();
1265 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001266 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001267
John Kessenich32cfd492016-02-02 12:37:46 -07001268 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001269 builder.clearAccessChain();
1270 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001271 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001272
John Kessenich32cfd492016-02-02 12:37:46 -07001273 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001274 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001275 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001276 convertGlslangToSpvType(node->getType()), left, right,
1277 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001278
John Kessenich50e57562015-12-21 21:21:11 -07001279 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001280 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001281 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001282 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001283 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001284 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001285 return false;
1286 }
John Kessenich140f3df2015-06-26 16:58:36 -06001287}
1288
1289bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1290{
John Kesseniche485c7a2017-05-31 18:50:53 -06001291 builder.setLine(node->getLoc().line);
1292
qining40887662016-04-03 22:20:42 -04001293 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1294 if (node->getType().getQualifier().isSpecConstant())
1295 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1296
John Kessenichfc51d282015-08-19 13:34:18 -06001297 spv::Id result = spv::NoResult;
1298
1299 // try texturing first
1300 result = createImageTextureFunctionCall(node);
1301 if (result != spv::NoResult) {
1302 builder.clearAccessChain();
1303 builder.setAccessChainRValue(result);
1304
1305 return false; // done with this node
1306 }
1307
1308 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001309
1310 if (node->getOp() == glslang::EOpArrayLength) {
1311 // Quite special; won't want to evaluate the operand.
1312
1313 // Normal .length() would have been constant folded by the front-end.
1314 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001315 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001316 assert(node->getOperand()->getType().isRuntimeSizedArray());
1317 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1318 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001319 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1320 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001321
1322 builder.clearAccessChain();
1323 builder.setAccessChainRValue(length);
1324
1325 return false;
1326 }
1327
John Kessenichfc51d282015-08-19 13:34:18 -06001328 // Start by evaluating the operand
1329
John Kessenich8c8505c2016-07-26 12:50:38 -06001330 // Does it need a swizzle inversion? If so, evaluation is inverted;
1331 // operate first on the swizzle base, then apply the swizzle.
1332 spv::Id invertedType = spv::NoType;
1333 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1334 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1335 invertedType = getInvertedSwizzleType(*node->getOperand());
1336
John Kessenich140f3df2015-06-26 16:58:36 -06001337 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001338 if (invertedType != spv::NoType)
1339 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1340 else
1341 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001342
Rex Xufc618912015-09-09 16:42:49 +08001343 spv::Id operand = spv::NoResult;
1344
1345 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1346 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001347 node->getOp() == glslang::EOpAtomicCounter ||
1348 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001349 operand = builder.accessChainGetLValue(); // Special case l-value operands
1350 else
John Kessenich32cfd492016-02-02 12:37:46 -07001351 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001352
John Kessenichf6640762016-08-01 19:44:00 -06001353 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001354 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001357 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001358 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001359
1360 // if not, then possibly an operation
1361 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001362 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001365 if (invertedType)
1366 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1367
John Kessenich140f3df2015-06-26 16:58:36 -06001368 builder.clearAccessChain();
1369 builder.setAccessChainRValue(result);
1370
1371 return false; // done with this node
1372 }
1373
1374 // it must be a special case, check...
1375 switch (node->getOp()) {
1376 case glslang::EOpPostIncrement:
1377 case glslang::EOpPostDecrement:
1378 case glslang::EOpPreIncrement:
1379 case glslang::EOpPreDecrement:
1380 {
1381 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001382 spv::Id one = 0;
1383 if (node->getBasicType() == glslang::EbtFloat)
1384 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001385 else if (node->getBasicType() == glslang::EbtDouble)
1386 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001387#ifdef AMD_EXTENSIONS
1388 else if (node->getBasicType() == glslang::EbtFloat16)
1389 one = builder.makeFloat16Constant(1.0F);
1390#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001391 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1392 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001393#ifdef AMD_EXTENSIONS
1394 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1395 one = builder.makeInt16Constant(1);
1396#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001397 else
1398 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 glslang::TOperator op;
1400 if (node->getOp() == glslang::EOpPreIncrement ||
1401 node->getOp() == glslang::EOpPostIncrement)
1402 op = glslang::EOpAdd;
1403 else
1404 op = glslang::EOpSub;
1405
John Kessenichf6640762016-08-01 19:44:00 -06001406 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001407 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001408 convertGlslangToSpvType(node->getType()), operand, one,
1409 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001410 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 // The result of operation is always stored, but conditionally the
1413 // consumed result. The consumed result is always an r-value.
1414 builder.accessChainStore(result);
1415 builder.clearAccessChain();
1416 if (node->getOp() == glslang::EOpPreIncrement ||
1417 node->getOp() == glslang::EOpPreDecrement)
1418 builder.setAccessChainRValue(result);
1419 else
1420 builder.setAccessChainRValue(operand);
1421 }
1422
1423 return false;
1424
1425 case glslang::EOpEmitStreamVertex:
1426 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1427 return false;
1428 case glslang::EOpEndStreamPrimitive:
1429 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1430 return false;
1431
1432 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001433 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001434 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001435 }
John Kessenich140f3df2015-06-26 16:58:36 -06001436}
1437
1438bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1439{
qining27e04a02016-04-14 16:40:20 -04001440 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1441 if (node->getType().getQualifier().isSpecConstant())
1442 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1443
John Kessenichfc51d282015-08-19 13:34:18 -06001444 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001445 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1446 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001447
1448 // try texturing
1449 result = createImageTextureFunctionCall(node);
1450 if (result != spv::NoResult) {
1451 builder.clearAccessChain();
1452 builder.setAccessChainRValue(result);
1453
1454 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001455 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001456 // "imageStore" is a special case, which has no result
1457 return false;
1458 }
John Kessenichfc51d282015-08-19 13:34:18 -06001459
John Kessenich140f3df2015-06-26 16:58:36 -06001460 glslang::TOperator binOp = glslang::EOpNull;
1461 bool reduceComparison = true;
1462 bool isMatrix = false;
1463 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001464 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465
1466 assert(node->getOp());
1467
John Kessenichf6640762016-08-01 19:44:00 -06001468 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001469
1470 switch (node->getOp()) {
1471 case glslang::EOpSequence:
1472 {
1473 if (preVisit)
1474 ++sequenceDepth;
1475 else
1476 --sequenceDepth;
1477
1478 if (sequenceDepth == 1) {
1479 // If this is the parent node of all the functions, we want to see them
1480 // early, so all call points have actual SPIR-V functions to reference.
1481 // In all cases, still let the traverser visit the children for us.
1482 makeFunctions(node->getAsAggregate()->getSequence());
1483
John Kessenich6fccb3c2016-09-19 16:01:41 -06001484 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001485 // anything else gets there, so visit out of order, doing them all now.
1486 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1487
John Kessenich6a60c2f2016-12-08 21:01:59 -07001488 // 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 -06001489 // so do them manually.
1490 visitFunctions(node->getAsAggregate()->getSequence());
1491
1492 return false;
1493 }
1494
1495 return true;
1496 }
1497 case glslang::EOpLinkerObjects:
1498 {
1499 if (visit == glslang::EvPreVisit)
1500 linkageOnly = true;
1501 else
1502 linkageOnly = false;
1503
1504 return true;
1505 }
1506 case glslang::EOpComma:
1507 {
1508 // processing from left to right naturally leaves the right-most
1509 // lying around in the access chain
1510 glslang::TIntermSequence& glslangOperands = node->getSequence();
1511 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1512 glslangOperands[i]->traverse(this);
1513
1514 return false;
1515 }
1516 case glslang::EOpFunction:
1517 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001518 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001519 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001520 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001521 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001522 } else {
1523 handleFunctionEntry(node);
1524 }
1525 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001526 if (inEntryPoint)
1527 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001528 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001529 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001530 }
1531
1532 return true;
1533 case glslang::EOpParameters:
1534 // Parameters will have been consumed by EOpFunction processing, but not
1535 // the body, so we still visited the function node's children, making this
1536 // child redundant.
1537 return false;
1538 case glslang::EOpFunctionCall:
1539 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001540 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001541 if (node->isUserDefined())
1542 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001543 // 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 -07001544 if (result) {
1545 builder.clearAccessChain();
1546 builder.setAccessChainRValue(result);
1547 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001548 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001549
1550 return false;
1551 }
1552 case glslang::EOpConstructMat2x2:
1553 case glslang::EOpConstructMat2x3:
1554 case glslang::EOpConstructMat2x4:
1555 case glslang::EOpConstructMat3x2:
1556 case glslang::EOpConstructMat3x3:
1557 case glslang::EOpConstructMat3x4:
1558 case glslang::EOpConstructMat4x2:
1559 case glslang::EOpConstructMat4x3:
1560 case glslang::EOpConstructMat4x4:
1561 case glslang::EOpConstructDMat2x2:
1562 case glslang::EOpConstructDMat2x3:
1563 case glslang::EOpConstructDMat2x4:
1564 case glslang::EOpConstructDMat3x2:
1565 case glslang::EOpConstructDMat3x3:
1566 case glslang::EOpConstructDMat3x4:
1567 case glslang::EOpConstructDMat4x2:
1568 case glslang::EOpConstructDMat4x3:
1569 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001570 case glslang::EOpConstructIMat2x2:
1571 case glslang::EOpConstructIMat2x3:
1572 case glslang::EOpConstructIMat2x4:
1573 case glslang::EOpConstructIMat3x2:
1574 case glslang::EOpConstructIMat3x3:
1575 case glslang::EOpConstructIMat3x4:
1576 case glslang::EOpConstructIMat4x2:
1577 case glslang::EOpConstructIMat4x3:
1578 case glslang::EOpConstructIMat4x4:
1579 case glslang::EOpConstructUMat2x2:
1580 case glslang::EOpConstructUMat2x3:
1581 case glslang::EOpConstructUMat2x4:
1582 case glslang::EOpConstructUMat3x2:
1583 case glslang::EOpConstructUMat3x3:
1584 case glslang::EOpConstructUMat3x4:
1585 case glslang::EOpConstructUMat4x2:
1586 case glslang::EOpConstructUMat4x3:
1587 case glslang::EOpConstructUMat4x4:
1588 case glslang::EOpConstructBMat2x2:
1589 case glslang::EOpConstructBMat2x3:
1590 case glslang::EOpConstructBMat2x4:
1591 case glslang::EOpConstructBMat3x2:
1592 case glslang::EOpConstructBMat3x3:
1593 case glslang::EOpConstructBMat3x4:
1594 case glslang::EOpConstructBMat4x2:
1595 case glslang::EOpConstructBMat4x3:
1596 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001597#ifdef AMD_EXTENSIONS
1598 case glslang::EOpConstructF16Mat2x2:
1599 case glslang::EOpConstructF16Mat2x3:
1600 case glslang::EOpConstructF16Mat2x4:
1601 case glslang::EOpConstructF16Mat3x2:
1602 case glslang::EOpConstructF16Mat3x3:
1603 case glslang::EOpConstructF16Mat3x4:
1604 case glslang::EOpConstructF16Mat4x2:
1605 case glslang::EOpConstructF16Mat4x3:
1606 case glslang::EOpConstructF16Mat4x4:
1607#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001608 isMatrix = true;
1609 // fall through
1610 case glslang::EOpConstructFloat:
1611 case glslang::EOpConstructVec2:
1612 case glslang::EOpConstructVec3:
1613 case glslang::EOpConstructVec4:
1614 case glslang::EOpConstructDouble:
1615 case glslang::EOpConstructDVec2:
1616 case glslang::EOpConstructDVec3:
1617 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001618#ifdef AMD_EXTENSIONS
1619 case glslang::EOpConstructFloat16:
1620 case glslang::EOpConstructF16Vec2:
1621 case glslang::EOpConstructF16Vec3:
1622 case glslang::EOpConstructF16Vec4:
1623#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001624 case glslang::EOpConstructBool:
1625 case glslang::EOpConstructBVec2:
1626 case glslang::EOpConstructBVec3:
1627 case glslang::EOpConstructBVec4:
1628 case glslang::EOpConstructInt:
1629 case glslang::EOpConstructIVec2:
1630 case glslang::EOpConstructIVec3:
1631 case glslang::EOpConstructIVec4:
1632 case glslang::EOpConstructUint:
1633 case glslang::EOpConstructUVec2:
1634 case glslang::EOpConstructUVec3:
1635 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001636 case glslang::EOpConstructInt64:
1637 case glslang::EOpConstructI64Vec2:
1638 case glslang::EOpConstructI64Vec3:
1639 case glslang::EOpConstructI64Vec4:
1640 case glslang::EOpConstructUint64:
1641 case glslang::EOpConstructU64Vec2:
1642 case glslang::EOpConstructU64Vec3:
1643 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001644#ifdef AMD_EXTENSIONS
1645 case glslang::EOpConstructInt16:
1646 case glslang::EOpConstructI16Vec2:
1647 case glslang::EOpConstructI16Vec3:
1648 case glslang::EOpConstructI16Vec4:
1649 case glslang::EOpConstructUint16:
1650 case glslang::EOpConstructU16Vec2:
1651 case glslang::EOpConstructU16Vec3:
1652 case glslang::EOpConstructU16Vec4:
1653#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001654 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001655 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001656 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001657 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001658 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001659 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001660 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001661 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001662 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001663 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001664 std::vector<spv::Id> constituents;
1665 for (int c = 0; c < (int)arguments.size(); ++c)
1666 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001667 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001668 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001669 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001670 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001671 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001672
1673 builder.clearAccessChain();
1674 builder.setAccessChainRValue(constructed);
1675
1676 return false;
1677 }
1678
1679 // These six are component-wise compares with component-wise results.
1680 // Forward on to createBinaryOperation(), requesting a vector result.
1681 case glslang::EOpLessThan:
1682 case glslang::EOpGreaterThan:
1683 case glslang::EOpLessThanEqual:
1684 case glslang::EOpGreaterThanEqual:
1685 case glslang::EOpVectorEqual:
1686 case glslang::EOpVectorNotEqual:
1687 {
1688 // Map the operation to a binary
1689 binOp = node->getOp();
1690 reduceComparison = false;
1691 switch (node->getOp()) {
1692 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1693 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1694 default: binOp = node->getOp(); break;
1695 }
1696
1697 break;
1698 }
1699 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001701 binOp = glslang::EOpMul;
1702 break;
1703 case glslang::EOpOuterProduct:
1704 // two vectors multiplied to make a matrix
1705 binOp = glslang::EOpOuterProduct;
1706 break;
1707 case glslang::EOpDot:
1708 {
qining25262b32016-05-06 17:25:16 -04001709 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001710 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001711 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001712 binOp = glslang::EOpMul;
1713 break;
1714 }
1715 case glslang::EOpMod:
1716 // when an aggregate, this is the floating-point mod built-in function,
1717 // which can be emitted by the one in createBinaryOperation()
1718 binOp = glslang::EOpMod;
1719 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001720 case glslang::EOpEmitVertex:
1721 case glslang::EOpEndPrimitive:
1722 case glslang::EOpBarrier:
1723 case glslang::EOpMemoryBarrier:
1724 case glslang::EOpMemoryBarrierAtomicCounter:
1725 case glslang::EOpMemoryBarrierBuffer:
1726 case glslang::EOpMemoryBarrierImage:
1727 case glslang::EOpMemoryBarrierShared:
1728 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001729 case glslang::EOpAllMemoryBarrierWithGroupSync:
1730 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1731 case glslang::EOpWorkgroupMemoryBarrier:
1732 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001733 noReturnValue = true;
1734 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1735 break;
1736
John Kessenich426394d2015-07-23 10:22:48 -06001737 case glslang::EOpAtomicAdd:
1738 case glslang::EOpAtomicMin:
1739 case glslang::EOpAtomicMax:
1740 case glslang::EOpAtomicAnd:
1741 case glslang::EOpAtomicOr:
1742 case glslang::EOpAtomicXor:
1743 case glslang::EOpAtomicExchange:
1744 case glslang::EOpAtomicCompSwap:
1745 atomic = true;
1746 break;
1747
John Kessenich0d0c6d32017-07-23 16:08:26 -06001748 case glslang::EOpAtomicCounterAdd:
1749 case glslang::EOpAtomicCounterSubtract:
1750 case glslang::EOpAtomicCounterMin:
1751 case glslang::EOpAtomicCounterMax:
1752 case glslang::EOpAtomicCounterAnd:
1753 case glslang::EOpAtomicCounterOr:
1754 case glslang::EOpAtomicCounterXor:
1755 case glslang::EOpAtomicCounterExchange:
1756 case glslang::EOpAtomicCounterCompSwap:
1757 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1758 builder.addCapability(spv::CapabilityAtomicStorageOps);
1759 atomic = true;
1760 break;
1761
John Kessenich140f3df2015-06-26 16:58:36 -06001762 default:
1763 break;
1764 }
1765
1766 //
1767 // See if it maps to a regular operation.
1768 //
John Kessenich140f3df2015-06-26 16:58:36 -06001769 if (binOp != glslang::EOpNull) {
1770 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1771 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1772 assert(left && right);
1773
1774 builder.clearAccessChain();
1775 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001776 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001777
1778 builder.clearAccessChain();
1779 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001780 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001781
John Kesseniche485c7a2017-05-31 18:50:53 -06001782 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001783 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001784 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001785 left->getType().getBasicType(), reduceComparison);
1786
1787 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001788 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001789 builder.clearAccessChain();
1790 builder.setAccessChainRValue(result);
1791
1792 return false;
1793 }
1794
John Kessenich426394d2015-07-23 10:22:48 -06001795 //
1796 // Create the list of operands.
1797 //
John Kessenich140f3df2015-06-26 16:58:36 -06001798 glslang::TIntermSequence& glslangOperands = node->getSequence();
1799 std::vector<spv::Id> operands;
1800 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001801 // special case l-value operands; there are just a few
1802 bool lvalue = false;
1803 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001804 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001805 case glslang::EOpModf:
1806 if (arg == 1)
1807 lvalue = true;
1808 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001809 case glslang::EOpInterpolateAtSample:
1810 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001811#ifdef AMD_EXTENSIONS
1812 case glslang::EOpInterpolateAtVertex:
1813#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001814 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001815 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001816
1817 // Does it need a swizzle inversion? If so, evaluation is inverted;
1818 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001819 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001820 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1821 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1822 }
Rex Xu7a26c172015-12-08 17:12:09 +08001823 break;
Rex Xud4782c12015-09-06 16:30:11 +08001824 case glslang::EOpAtomicAdd:
1825 case glslang::EOpAtomicMin:
1826 case glslang::EOpAtomicMax:
1827 case glslang::EOpAtomicAnd:
1828 case glslang::EOpAtomicOr:
1829 case glslang::EOpAtomicXor:
1830 case glslang::EOpAtomicExchange:
1831 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001832 case glslang::EOpAtomicCounterAdd:
1833 case glslang::EOpAtomicCounterSubtract:
1834 case glslang::EOpAtomicCounterMin:
1835 case glslang::EOpAtomicCounterMax:
1836 case glslang::EOpAtomicCounterAnd:
1837 case glslang::EOpAtomicCounterOr:
1838 case glslang::EOpAtomicCounterXor:
1839 case glslang::EOpAtomicCounterExchange:
1840 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001841 if (arg == 0)
1842 lvalue = true;
1843 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001844 case glslang::EOpAddCarry:
1845 case glslang::EOpSubBorrow:
1846 if (arg == 2)
1847 lvalue = true;
1848 break;
1849 case glslang::EOpUMulExtended:
1850 case glslang::EOpIMulExtended:
1851 if (arg >= 2)
1852 lvalue = true;
1853 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001854 default:
1855 break;
1856 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001857 builder.clearAccessChain();
1858 if (invertedType != spv::NoType && arg == 0)
1859 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1860 else
1861 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001862 if (lvalue)
1863 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001864 else {
1865 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001866 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001867 }
John Kessenich140f3df2015-06-26 16:58:36 -06001868 }
John Kessenich426394d2015-07-23 10:22:48 -06001869
John Kesseniche485c7a2017-05-31 18:50:53 -06001870 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001871 if (atomic) {
1872 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001873 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001874 } else {
1875 // Pass through to generic operations.
1876 switch (glslangOperands.size()) {
1877 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001878 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001879 break;
1880 case 1:
qining25262b32016-05-06 17:25:16 -04001881 result = createUnaryOperation(
1882 node->getOp(), precision,
1883 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001884 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001885 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001886 break;
1887 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001888 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001889 break;
1890 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001891 if (invertedType)
1892 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001893 }
1894
1895 if (noReturnValue)
1896 return false;
1897
1898 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001899 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001900 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001901 } else {
1902 builder.clearAccessChain();
1903 builder.setAccessChainRValue(result);
1904 return false;
1905 }
1906}
1907
John Kessenich433e9ff2017-01-26 20:31:11 -07001908// This path handles both if-then-else and ?:
1909// The if-then-else has a node type of void, while
1910// ?: has either a void or a non-void node type
1911//
1912// Leaving the result, when not void:
1913// GLSL only has r-values as the result of a :?, but
1914// if we have an l-value, that can be more efficient if it will
1915// become the base of a complex r-value expression, because the
1916// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001917bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1918{
John Kessenich433e9ff2017-01-26 20:31:11 -07001919 // See if it simple and safe to generate OpSelect instead of using control flow.
1920 // Crucially, side effects must be avoided, and there are performance trade-offs.
1921 // Return true if good idea (and safe) for OpSelect, false otherwise.
1922 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001923 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1924 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001925 return false;
1926
1927 if (node->getTrueBlock() == nullptr ||
1928 node->getFalseBlock() == nullptr)
1929 return false;
1930
1931 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1932 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1933
1934 // return true if a single operand to ? : is okay for OpSelect
1935 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001936 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001937 };
1938
1939 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1940 operandOkay(node->getFalseBlock()->getAsTyped());
1941 };
1942
1943 // Emit OpSelect for this selection.
1944 const auto handleAsOpSelect = [&]() {
1945 node->getCondition()->traverse(this);
1946 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1947 node->getTrueBlock()->traverse(this);
1948 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1949 node->getFalseBlock()->traverse(this);
1950 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1951
John Kesseniche485c7a2017-05-31 18:50:53 -06001952 builder.setLine(node->getLoc().line);
1953
John Kesseniche434ad92017-03-30 10:09:28 -06001954 // smear condition to vector, if necessary (AST is always scalar)
1955 if (builder.isVector(trueValue))
1956 condition = builder.smearScalar(spv::NoPrecision, condition,
1957 builder.makeVectorType(builder.makeBoolType(),
1958 builder.getNumComponents(trueValue)));
1959
1960 spv::Id select = builder.createTriOp(spv::OpSelect,
1961 convertGlslangToSpvType(node->getType()), condition,
1962 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001963 builder.clearAccessChain();
1964 builder.setAccessChainRValue(select);
1965 };
1966
1967 // Try for OpSelect
1968
1969 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001970 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1971 if (node->getType().getQualifier().isSpecConstant())
1972 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1973
John Kessenich433e9ff2017-01-26 20:31:11 -07001974 handleAsOpSelect();
1975 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001976 }
1977
Rex Xu57e65922017-07-04 23:23:40 +08001978 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001979 // Don't handle results as temporaries, because there will be two names
1980 // and better to leave SSA to later passes.
1981 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1982 ? spv::NoResult
1983 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1984
John Kessenich140f3df2015-06-26 16:58:36 -06001985 // emit the condition before doing anything with selection
1986 node->getCondition()->traverse(this);
1987
Rex Xu57e65922017-07-04 23:23:40 +08001988 // Selection control:
1989 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
1990
John Kessenich140f3df2015-06-26 16:58:36 -06001991 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08001992 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001993
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 // emit the "then" statement
1995 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001996 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001997 if (result != spv::NoResult)
1998 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001999 }
2000
John Kessenich433e9ff2017-01-26 20:31:11 -07002001 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002002 ifBuilder.makeBeginElse();
2003 // emit the "else" statement
2004 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002005 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002006 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002007 }
2008
John Kessenich433e9ff2017-01-26 20:31:11 -07002009 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002010 ifBuilder.makeEndIf();
2011
John Kessenich433e9ff2017-01-26 20:31:11 -07002012 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002013 // GLSL only has r-values as the result of a :?, but
2014 // if we have an l-value, that can be more efficient if it will
2015 // become the base of a complex r-value expression, because the
2016 // next layer copies r-values into memory to use the access-chain mechanism
2017 builder.clearAccessChain();
2018 builder.setAccessChainLValue(result);
2019 }
2020
2021 return false;
2022}
2023
2024bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2025{
2026 // emit and get the condition before doing anything with switch
2027 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002028 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002029
Rex Xu57e65922017-07-04 23:23:40 +08002030 // Selection control:
2031 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2032
John Kessenich140f3df2015-06-26 16:58:36 -06002033 // browse the children to sort out code segments
2034 int defaultSegment = -1;
2035 std::vector<TIntermNode*> codeSegments;
2036 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2037 std::vector<int> caseValues;
2038 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2039 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2040 TIntermNode* child = *c;
2041 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002042 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002043 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002044 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002045 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2046 } else
2047 codeSegments.push_back(child);
2048 }
2049
qining25262b32016-05-06 17:25:16 -04002050 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002051 // statements between the last case and the end of the switch statement
2052 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2053 (int)codeSegments.size() == defaultSegment)
2054 codeSegments.push_back(nullptr);
2055
2056 // make the switch statement
2057 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002058 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002059
2060 // emit all the code in the segments
2061 breakForLoop.push(false);
2062 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2063 builder.nextSwitchSegment(segmentBlocks, s);
2064 if (codeSegments[s])
2065 codeSegments[s]->traverse(this);
2066 else
2067 builder.addSwitchBreak();
2068 }
2069 breakForLoop.pop();
2070
2071 builder.endSwitch(segmentBlocks);
2072
2073 return false;
2074}
2075
2076void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2077{
2078 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002079 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002080
2081 builder.clearAccessChain();
2082 builder.setAccessChainRValue(constant);
2083}
2084
2085bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2086{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002087 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002088 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002089
2090 // Loop control:
2091 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2092
2093 // TODO: dependency length
2094
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002095 // Spec requires back edges to target header blocks, and every header block
2096 // must dominate its merge block. Make a header block first to ensure these
2097 // conditions are met. By definition, it will contain OpLoopMerge, followed
2098 // by a block-ending branch. But we don't want to put any other body/test
2099 // instructions in it, since the body/test may have arbitrary instructions,
2100 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002101 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002102 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002103 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002104 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002105 spv::Block& test = builder.makeNewBlock();
2106 builder.createBranch(&test);
2107
2108 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002109 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002110 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002111 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2112
2113 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002114 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002115 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002116 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002117 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002118 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002119
2120 builder.setBuildPoint(&blocks.continue_target);
2121 if (node->getTerminal())
2122 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002123 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002124 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002125 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002126 builder.createBranch(&blocks.body);
2127
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002128 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002129 builder.setBuildPoint(&blocks.body);
2130 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002131 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002132 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002133 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002134
2135 builder.setBuildPoint(&blocks.continue_target);
2136 if (node->getTerminal())
2137 node->getTerminal()->traverse(this);
2138 if (node->getTest()) {
2139 node->getTest()->traverse(this);
2140 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002141 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002142 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002143 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002144 // TODO: unless there was a break/return/discard instruction
2145 // somewhere in the body, this is an infinite loop, so we should
2146 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002147 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002148 }
John Kessenich140f3df2015-06-26 16:58:36 -06002149 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002150 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002151 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002152 return false;
2153}
2154
2155bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2156{
2157 if (node->getExpression())
2158 node->getExpression()->traverse(this);
2159
John Kesseniche485c7a2017-05-31 18:50:53 -06002160 builder.setLine(node->getLoc().line);
2161
John Kessenich140f3df2015-06-26 16:58:36 -06002162 switch (node->getFlowOp()) {
2163 case glslang::EOpKill:
2164 builder.makeDiscard();
2165 break;
2166 case glslang::EOpBreak:
2167 if (breakForLoop.top())
2168 builder.createLoopExit();
2169 else
2170 builder.addSwitchBreak();
2171 break;
2172 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002173 builder.createLoopContinue();
2174 break;
2175 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002176 if (node->getExpression()) {
2177 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2178 spv::Id returnId = accessChainLoad(glslangReturnType);
2179 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2180 builder.clearAccessChain();
2181 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2182 builder.setAccessChainLValue(copyId);
2183 multiTypeStore(glslangReturnType, returnId);
2184 returnId = builder.createLoad(copyId);
2185 }
2186 builder.makeReturn(false, returnId);
2187 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002188 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002189
2190 builder.clearAccessChain();
2191 break;
2192
2193 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002194 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002195 break;
2196 }
2197
2198 return false;
2199}
2200
2201spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2202{
qining25262b32016-05-06 17:25:16 -04002203 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002204 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002205 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002206 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002207 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002208 }
2209
2210 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002211 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002212 spv::Id spvType = convertGlslangToSpvType(node->getType());
2213
Rex Xuf89ad982017-04-07 23:22:33 +08002214#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002215 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2216 node->getType().containsBasicType(glslang::EbtInt16) ||
2217 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002218 if (contains16BitType) {
2219 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2220 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2221 builder.addCapability(spv::CapabilityStorageInputOutput16);
2222 } else if (storageClass == spv::StorageClassPushConstant) {
2223 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2224 builder.addCapability(spv::CapabilityStoragePushConstant16);
2225 } else if (storageClass == spv::StorageClassUniform) {
2226 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2227 builder.addCapability(spv::CapabilityStorageUniform16);
2228 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2229 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2230 }
2231 }
2232#endif
2233
John Kessenich140f3df2015-06-26 16:58:36 -06002234 const char* name = node->getName().c_str();
2235 if (glslang::IsAnonymous(name))
2236 name = "";
2237
2238 return builder.createVariable(storageClass, spvType, name);
2239}
2240
2241// Return type Id of the sampled type.
2242spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2243{
2244 switch (sampler.type) {
2245 case glslang::EbtFloat: return builder.makeFloatType(32);
2246 case glslang::EbtInt: return builder.makeIntType(32);
2247 case glslang::EbtUint: return builder.makeUintType(32);
2248 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002250 return builder.makeFloatType(32);
2251 }
2252}
2253
John Kessenich8c8505c2016-07-26 12:50:38 -06002254// If node is a swizzle operation, return the type that should be used if
2255// the swizzle base is first consumed by another operation, before the swizzle
2256// is applied.
2257spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2258{
John Kessenichecba76f2017-01-06 00:34:48 -07002259 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002260 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2261 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2262 else
2263 return spv::NoType;
2264}
2265
2266// When inverting a swizzle with a parent op, this function
2267// will apply the swizzle operation to a completed parent operation.
2268spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2269{
2270 std::vector<unsigned> swizzle;
2271 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2272 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2273}
2274
John Kessenich8c8505c2016-07-26 12:50:38 -06002275// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2276void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2277{
2278 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2279 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2280 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2281}
2282
John Kessenich3ac051e2015-12-20 11:29:16 -07002283// Convert from a glslang type to an SPV type, by calling into a
2284// recursive version of this function. This establishes the inherited
2285// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002286spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2287{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002288 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002289}
2290
2291// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002292// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002293// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002294spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002295{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002296 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002297
2298 switch (type.getBasicType()) {
2299 case glslang::EbtVoid:
2300 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002301 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002302 break;
2303 case glslang::EbtFloat:
2304 spvType = builder.makeFloatType(32);
2305 break;
2306 case glslang::EbtDouble:
2307 spvType = builder.makeFloatType(64);
2308 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002309#ifdef AMD_EXTENSIONS
2310 case glslang::EbtFloat16:
2311 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002312 spvType = builder.makeFloatType(16);
2313 break;
2314#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002315 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002316 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2317 // a 32-bit int where non-0 means true.
2318 if (explicitLayout != glslang::ElpNone)
2319 spvType = builder.makeUintType(32);
2320 else
2321 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002322 break;
2323 case glslang::EbtInt:
2324 spvType = builder.makeIntType(32);
2325 break;
2326 case glslang::EbtUint:
2327 spvType = builder.makeUintType(32);
2328 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002329 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002330 spvType = builder.makeIntType(64);
2331 break;
2332 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002333 spvType = builder.makeUintType(64);
2334 break;
Rex Xucabbb782017-03-24 13:41:14 +08002335#ifdef AMD_EXTENSIONS
2336 case glslang::EbtInt16:
2337 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2338 spvType = builder.makeIntType(16);
2339 break;
2340 case glslang::EbtUint16:
2341 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2342 spvType = builder.makeUintType(16);
2343 break;
2344#endif
John Kessenich426394d2015-07-23 10:22:48 -06002345 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002346 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002347 spvType = builder.makeUintType(32);
2348 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002349 case glslang::EbtSampler:
2350 {
2351 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002352 if (sampler.sampler) {
2353 // pure sampler
2354 spvType = builder.makeSamplerType();
2355 } else {
2356 // an image is present, make its type
2357 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2358 sampler.image ? 2 : 1, TranslateImageFormat(type));
2359 if (sampler.combined) {
2360 // already has both image and sampler, make the combined type
2361 spvType = builder.makeSampledImageType(spvType);
2362 }
John Kessenich55e7d112015-11-15 21:33:39 -07002363 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002364 }
John Kessenich140f3df2015-06-26 16:58:36 -06002365 break;
2366 case glslang::EbtStruct:
2367 case glslang::EbtBlock:
2368 {
2369 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002370 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002371
2372 // Try to share structs for different layouts, but not yet for other
2373 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002374 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002375 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002376 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002377 break;
2378
2379 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002380 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002381 memberRemapper[glslangMembers].resize(glslangMembers->size());
2382 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002383 }
2384 break;
2385 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002386 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002387 break;
2388 }
2389
2390 if (type.isMatrix())
2391 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2392 else {
2393 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2394 if (type.getVectorSize() > 1)
2395 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2396 }
2397
2398 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002399 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2400
John Kessenichc9a80832015-09-12 12:17:44 -06002401 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002402 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002403 // We need to decorate array strides for types needing explicit layout, except blocks.
2404 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002405 // Use a dummy glslang type for querying internal strides of
2406 // arrays of arrays, but using just a one-dimensional array.
2407 glslang::TType simpleArrayType(type, 0); // deference type of the array
2408 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2409 simpleArrayType.getArraySizes().dereference();
2410
2411 // Will compute the higher-order strides here, rather than making a whole
2412 // pile of types and doing repetitive recursion on their contents.
2413 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2414 }
John Kessenichf8842e52016-01-04 19:22:56 -07002415
2416 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002417 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002418 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002419 if (stride > 0)
2420 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002421 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002422 }
2423 } else {
2424 // single-dimensional array, and don't yet have stride
2425
John Kessenichf8842e52016-01-04 19:22:56 -07002426 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002427 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2428 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002429 }
John Kessenich31ed4832015-09-09 17:51:38 -06002430
John Kessenichc9a80832015-09-12 12:17:44 -06002431 // Do the outer dimension, which might not be known for a runtime-sized array
2432 if (type.isRuntimeSizedArray()) {
2433 spvType = builder.makeRuntimeArray(spvType);
2434 } else {
2435 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002436 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002437 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002438 if (stride > 0)
2439 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002440 }
2441
2442 return spvType;
2443}
2444
John Kessenich0e737842017-03-24 18:38:16 -06002445// TODO: this functionality should exist at a higher level, in creating the AST
2446//
2447// Identify interface members that don't have their required extension turned on.
2448//
2449bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2450{
2451 auto& extensions = glslangIntermediate->getRequestedExtensions();
2452
Rex Xubcf291a2017-03-29 23:01:36 +08002453 if (member.getFieldName() == "gl_ViewportMask" &&
2454 extensions.find("GL_NV_viewport_array2") == extensions.end())
2455 return true;
2456 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2457 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2458 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002459 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2460 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2461 return true;
2462 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2463 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2464 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002465 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2466 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2467 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002468
2469 return false;
2470};
2471
John Kessenich6090df02016-06-30 21:18:02 -06002472// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2473// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2474// Mutually recursive with convertGlslangToSpvType().
2475spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2476 const glslang::TTypeList* glslangMembers,
2477 glslang::TLayoutPacking explicitLayout,
2478 const glslang::TQualifier& qualifier)
2479{
2480 // Create a vector of struct types for SPIR-V to consume
2481 std::vector<spv::Id> spvMembers;
2482 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 -06002483 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2484 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2485 if (glslangMember.hiddenMember()) {
2486 ++memberDelta;
2487 if (type.getBasicType() == glslang::EbtBlock)
2488 memberRemapper[glslangMembers][i] = -1;
2489 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002490 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002491 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002492 if (filterMember(glslangMember))
2493 continue;
2494 }
John Kessenich6090df02016-06-30 21:18:02 -06002495 // modify just this child's view of the qualifier
2496 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2497 InheritQualifiers(memberQualifier, qualifier);
2498
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002499 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002500 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002501 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002502
2503 // recurse
2504 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2505 }
2506 }
2507
2508 // Make the SPIR-V type
2509 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002510 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002511 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2512
2513 // Decorate it
2514 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2515
2516 return spvType;
2517}
2518
2519void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2520 const glslang::TTypeList* glslangMembers,
2521 glslang::TLayoutPacking explicitLayout,
2522 const glslang::TQualifier& qualifier,
2523 spv::Id spvType)
2524{
2525 // Name and decorate the non-hidden members
2526 int offset = -1;
2527 int locationOffset = 0; // for use within the members of this struct
2528 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2529 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2530 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002531 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002532 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002533 if (filterMember(glslangMember))
2534 continue;
2535 }
John Kessenich6090df02016-06-30 21:18:02 -06002536
2537 // modify just this child's view of the qualifier
2538 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2539 InheritQualifiers(memberQualifier, qualifier);
2540
2541 // using -1 above to indicate a hidden member
2542 if (member >= 0) {
2543 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2544 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2545 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2546 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002547 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2548 type.getQualifier().storage == glslang::EvqVaryingOut) {
2549 if (type.getBasicType() == glslang::EbtBlock ||
2550 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002551 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2552 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2553 }
2554 }
2555 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2556
Rex Xu286ca432017-07-27 14:33:16 +08002557 if (type.getBasicType() == glslang::EbtBlock &&
2558 qualifier.storage == glslang::EvqBuffer) {
2559 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002560 std::vector<spv::Decoration> memory;
2561 TranslateMemoryDecoration(memberQualifier, memory);
2562 for (unsigned int i = 0; i < memory.size(); ++i)
2563 addMemberDecoration(spvType, member, memory[i]);
2564 }
2565
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002566 // Location assignment was already completed correctly by the front end,
2567 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002568 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002569 // ill-specified and decisions have been made to not allow this.
2570 if (! type.isArray() && memberQualifier.hasLocation())
2571 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002572
John Kessenich2f47bc92016-06-30 21:47:35 -06002573 if (qualifier.hasLocation()) // track for upcoming inheritance
2574 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2575
John Kessenich6090df02016-06-30 21:18:02 -06002576 // component, XFB, others
2577 if (glslangMember.getQualifier().hasComponent())
2578 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2579 if (glslangMember.getQualifier().hasXfbOffset())
2580 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2581 else if (explicitLayout != glslang::ElpNone) {
2582 // figure out what to do with offset, which is accumulating
2583 int nextOffset;
2584 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2585 if (offset >= 0)
2586 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2587 offset = nextOffset;
2588 }
2589
2590 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2591 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2592
2593 // built-in variable decorations
2594 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002595 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002596 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002597
2598#ifdef NV_EXTENSIONS
2599 if (builtIn == spv::BuiltInLayer) {
2600 // SPV_NV_viewport_array2 extension
2601 if (glslangMember.getQualifier().layoutViewportRelative){
2602 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2603 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2604 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2605 }
2606 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2607 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2608 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2609 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2610 }
2611 }
chaocdf3956c2017-02-14 14:52:34 -08002612 if (glslangMember.getQualifier().layoutPassthrough) {
2613 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2614 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2615 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2616 }
chaoc771d89f2017-01-13 01:10:53 -08002617#endif
John Kessenich6090df02016-06-30 21:18:02 -06002618 }
2619 }
2620
2621 // Decorate the structure
2622 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002623 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002624 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2625 builder.addCapability(spv::CapabilityGeometryStreams);
2626 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2627 }
2628 if (glslangIntermediate->getXfbMode()) {
2629 builder.addCapability(spv::CapabilityTransformFeedback);
2630 if (type.getQualifier().hasXfbStride())
2631 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2632 if (type.getQualifier().hasXfbBuffer())
2633 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2634 }
2635}
2636
John Kessenich6c292d32016-02-15 20:58:50 -07002637// Turn the expression forming the array size into an id.
2638// This is not quite trivial, because of specialization constants.
2639// Sometimes, a raw constant is turned into an Id, and sometimes
2640// a specialization constant expression is.
2641spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2642{
2643 // First, see if this is sized with a node, meaning a specialization constant:
2644 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2645 if (specNode != nullptr) {
2646 builder.clearAccessChain();
2647 specNode->traverse(this);
2648 return accessChainLoad(specNode->getAsTyped()->getType());
2649 }
qining25262b32016-05-06 17:25:16 -04002650
John Kessenich6c292d32016-02-15 20:58:50 -07002651 // Otherwise, need a compile-time (front end) size, get it:
2652 int size = arraySizes.getDimSize(dim);
2653 assert(size > 0);
2654 return builder.makeUintConstant(size);
2655}
2656
John Kessenich103bef92016-02-08 21:38:15 -07002657// Wrap the builder's accessChainLoad to:
2658// - localize handling of RelaxedPrecision
2659// - use the SPIR-V inferred type instead of another conversion of the glslang type
2660// (avoids unnecessary work and possible type punning for structures)
2661// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002662spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2663{
John Kessenich103bef92016-02-08 21:38:15 -07002664 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2665 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2666
2667 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002668 if (type.getBasicType() == glslang::EbtBool) {
2669 if (builder.isScalarType(nominalTypeId)) {
2670 // Conversion for bool
2671 spv::Id boolType = builder.makeBoolType();
2672 if (nominalTypeId != boolType)
2673 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2674 } else if (builder.isVectorType(nominalTypeId)) {
2675 // Conversion for bvec
2676 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2677 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2678 if (nominalTypeId != bvecType)
2679 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2680 }
2681 }
John Kessenich103bef92016-02-08 21:38:15 -07002682
2683 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002684}
2685
Rex Xu27253232016-02-23 17:51:09 +08002686// Wrap the builder's accessChainStore to:
2687// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002688//
2689// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002690void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2691{
2692 // Need to convert to abstract types when necessary
2693 if (type.getBasicType() == glslang::EbtBool) {
2694 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2695
2696 if (builder.isScalarType(nominalTypeId)) {
2697 // Conversion for bool
2698 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002699 if (nominalTypeId != boolType) {
2700 // keep these outside arguments, for determinant order-of-evaluation
2701 spv::Id one = builder.makeUintConstant(1);
2702 spv::Id zero = builder.makeUintConstant(0);
2703 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2704 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002705 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002706 } else if (builder.isVectorType(nominalTypeId)) {
2707 // Conversion for bvec
2708 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2709 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002710 if (nominalTypeId != bvecType) {
2711 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002712 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2713 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2714 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002715 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002716 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2717 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002718 }
2719 }
2720
2721 builder.accessChainStore(rvalue);
2722}
2723
John Kessenich4bf71552016-09-02 11:20:21 -06002724// For storing when types match at the glslang level, but not might match at the
2725// SPIR-V level.
2726//
2727// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002728// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002729// as in a member-decorated way.
2730//
2731// NOTE: This function can handle any store request; if it's not special it
2732// simplifies to a simple OpStore.
2733//
2734// Implicitly uses the existing builder.accessChain as the storage target.
2735void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2736{
John Kessenichb3e24e42016-09-11 12:33:43 -06002737 // we only do the complex path here if it's an aggregate
2738 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002739 accessChainStore(type, rValue);
2740 return;
2741 }
2742
John Kessenichb3e24e42016-09-11 12:33:43 -06002743 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002744 spv::Id rType = builder.getTypeId(rValue);
2745 spv::Id lValue = builder.accessChainGetLValue();
2746 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2747 if (lType == rType) {
2748 accessChainStore(type, rValue);
2749 return;
2750 }
2751
John Kessenichb3e24e42016-09-11 12:33:43 -06002752 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002753 // where the two types were the same type in GLSL. This requires member
2754 // by member copy, recursively.
2755
John Kessenichb3e24e42016-09-11 12:33:43 -06002756 // If an array, copy element by element.
2757 if (type.isArray()) {
2758 glslang::TType glslangElementType(type, 0);
2759 spv::Id elementRType = builder.getContainedTypeId(rType);
2760 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2761 // get the source member
2762 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002763
John Kessenichb3e24e42016-09-11 12:33:43 -06002764 // set up the target storage
2765 builder.clearAccessChain();
2766 builder.setAccessChainLValue(lValue);
2767 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002768
John Kessenichb3e24e42016-09-11 12:33:43 -06002769 // store the member
2770 multiTypeStore(glslangElementType, elementRValue);
2771 }
2772 } else {
2773 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002774
John Kessenichb3e24e42016-09-11 12:33:43 -06002775 // loop over structure members
2776 const glslang::TTypeList& members = *type.getStruct();
2777 for (int m = 0; m < (int)members.size(); ++m) {
2778 const glslang::TType& glslangMemberType = *members[m].type;
2779
2780 // get the source member
2781 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2782 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2783
2784 // set up the target storage
2785 builder.clearAccessChain();
2786 builder.setAccessChainLValue(lValue);
2787 builder.accessChainPush(builder.makeIntConstant(m));
2788
2789 // store the member
2790 multiTypeStore(glslangMemberType, memberRValue);
2791 }
John Kessenich4bf71552016-09-02 11:20:21 -06002792 }
2793}
2794
John Kessenichf85e8062015-12-19 13:57:10 -07002795// Decide whether or not this type should be
2796// decorated with offsets and strides, and if so
2797// whether std140 or std430 rules should be applied.
2798glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002799{
John Kessenichf85e8062015-12-19 13:57:10 -07002800 // has to be a block
2801 if (type.getBasicType() != glslang::EbtBlock)
2802 return glslang::ElpNone;
2803
2804 // has to be a uniform or buffer block
2805 if (type.getQualifier().storage != glslang::EvqUniform &&
2806 type.getQualifier().storage != glslang::EvqBuffer)
2807 return glslang::ElpNone;
2808
2809 // return the layout to use
2810 switch (type.getQualifier().layoutPacking) {
2811 case glslang::ElpStd140:
2812 case glslang::ElpStd430:
2813 return type.getQualifier().layoutPacking;
2814 default:
2815 return glslang::ElpNone;
2816 }
John Kessenich31ed4832015-09-09 17:51:38 -06002817}
2818
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002819// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002820int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002821{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002822 int size;
John Kessenich49987892015-12-29 17:11:44 -07002823 int stride;
2824 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002825
2826 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002827}
2828
John Kessenich49987892015-12-29 17:11:44 -07002829// 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 -07002830// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002831int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002832{
John Kessenich49987892015-12-29 17:11:44 -07002833 glslang::TType elementType;
2834 elementType.shallowCopy(matrixType);
2835 elementType.clearArraySizes();
2836
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002837 int size;
John Kessenich49987892015-12-29 17:11:44 -07002838 int stride;
2839 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2840
2841 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002842}
2843
John Kessenich5e4b1242015-08-06 22:53:06 -06002844// Given a member type of a struct, realign the current offset for it, and compute
2845// the next (not yet aligned) offset for the next member, which will get aligned
2846// on the next call.
2847// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2848// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2849// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002850void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002851 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002852{
2853 // this will get a positive value when deemed necessary
2854 nextOffset = -1;
2855
John Kessenich5e4b1242015-08-06 22:53:06 -06002856 // override anything in currentOffset with user-set offset
2857 if (memberType.getQualifier().hasOffset())
2858 currentOffset = memberType.getQualifier().layoutOffset;
2859
2860 // It could be that current linker usage in glslang updated all the layoutOffset,
2861 // in which case the following code does not matter. But, that's not quite right
2862 // once cross-compilation unit GLSL validation is done, as the original user
2863 // settings are needed in layoutOffset, and then the following will come into play.
2864
John Kessenichf85e8062015-12-19 13:57:10 -07002865 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002866 if (! memberType.getQualifier().hasOffset())
2867 currentOffset = -1;
2868
2869 return;
2870 }
2871
John Kessenichf85e8062015-12-19 13:57:10 -07002872 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002873 if (currentOffset < 0)
2874 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002875
John Kessenich5e4b1242015-08-06 22:53:06 -06002876 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2877 // but possibly not yet correctly aligned.
2878
2879 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002880 int dummyStride;
2881 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002882
2883 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002884 // TODO: make this consistent in early phases of code:
2885 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2886 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2887 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002888 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002889 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002890 int dummySize;
2891 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2892 if (componentAlignment <= 4)
2893 memberAlignment = componentAlignment;
2894 }
2895
2896 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002898
2899 // Bump up to vec4 if there is a bad straddle
2900 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2901 glslang::RoundToPow2(currentOffset, 16);
2902
John Kessenich5e4b1242015-08-06 22:53:06 -06002903 nextOffset = currentOffset + memberSize;
2904}
2905
David Netoa901ffe2016-06-08 14:11:40 +01002906void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002907{
David Netoa901ffe2016-06-08 14:11:40 +01002908 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2909 switch (glslangBuiltIn)
2910 {
2911 case glslang::EbvClipDistance:
2912 case glslang::EbvCullDistance:
2913 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002914#ifdef NV_EXTENSIONS
2915 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002916 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002917 case glslang::EbvViewportMaskNV:
2918 case glslang::EbvSecondaryPositionNV:
2919 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002920 case glslang::EbvPositionPerViewNV:
2921 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002922#endif
David Netoa901ffe2016-06-08 14:11:40 +01002923 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2924 // Alternately, we could just call this for any glslang built-in, since the
2925 // capability already guards against duplicates.
2926 TranslateBuiltInDecoration(glslangBuiltIn, false);
2927 break;
2928 default:
2929 // Capabilities were already generated when the struct was declared.
2930 break;
2931 }
John Kessenichebb50532016-05-16 19:22:05 -06002932}
2933
John Kessenich6fccb3c2016-09-19 16:01:41 -06002934bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002935{
John Kessenicheee9d532016-09-19 18:09:30 -06002936 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002937}
2938
2939// Make all the functions, skeletally, without actually visiting their bodies.
2940void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2941{
John Kessenichfad62972017-07-18 02:35:46 -06002942 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2943 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2944 if (paramPrecision != spv::NoPrecision)
2945 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002946 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002947 };
2948
John Kessenich140f3df2015-06-26 16:58:36 -06002949 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2950 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002951 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002952 continue;
2953
2954 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002955 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002956 //
qining25262b32016-05-06 17:25:16 -04002957 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002958 // function. What it is an address of varies:
2959 //
John Kessenich4bf71552016-09-02 11:20:21 -06002960 // - "in" parameters not marked as "const" can be written to without modifying the calling
2961 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002962 //
2963 // - "const in" parameters can just be the r-value, as no writes need occur.
2964 //
John Kessenich4bf71552016-09-02 11:20:21 -06002965 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2966 // 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 -06002967
2968 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002969 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002970 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2971
John Kessenichfad62972017-07-18 02:35:46 -06002972 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2973 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002974
John Kessenichfad62972017-07-18 02:35:46 -06002975 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002976 for (int p = 0; p < (int)parameters.size(); ++p) {
2977 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2978 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002979 // can we pass by reference?
2980 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002981 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002982 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002983 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002984 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002985 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002986 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2987 else
John Kessenich4bf71552016-09-02 11:20:21 -06002988 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06002989 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06002990 paramTypes.push_back(typeId);
2991 }
2992
2993 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002994 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2995 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06002996 glslFunction->getName().c_str(), paramTypes,
2997 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002998 if (implicitThis)
2999 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003000
3001 // Track function to emit/call later
3002 functionMap[glslFunction->getName().c_str()] = function;
3003
3004 // Set the parameter id's
3005 for (int p = 0; p < (int)parameters.size(); ++p) {
3006 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3007 // give a name too
3008 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3009 }
3010 }
3011}
3012
3013// Process all the initializers, while skipping the functions and link objects
3014void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3015{
3016 builder.setBuildPoint(shaderEntry->getLastBlock());
3017 for (int i = 0; i < (int)initializers.size(); ++i) {
3018 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3019 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3020
3021 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003022 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003023 initializer->traverse(this);
3024 }
3025 }
3026}
3027
3028// Process all the functions, while skipping initializers.
3029void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3030{
3031 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3032 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003033 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003034 node->traverse(this);
3035 }
3036}
3037
3038void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3039{
qining25262b32016-05-06 17:25:16 -04003040 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003041 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003042 currentFunction = functionMap[node->getName().c_str()];
3043 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003044 builder.setBuildPoint(functionBlock);
3045}
3046
Rex Xu04db3f52015-09-16 11:44:02 +08003047void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003048{
Rex Xufc618912015-09-09 16:42:49 +08003049 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003050
3051 glslang::TSampler sampler = {};
3052 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003053 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003054 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3055 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3056 }
3057
John Kessenich140f3df2015-06-26 16:58:36 -06003058 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3059 builder.clearAccessChain();
3060 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003061
3062 // Special case l-value operands
3063 bool lvalue = false;
3064 switch (node.getOp()) {
3065 case glslang::EOpImageAtomicAdd:
3066 case glslang::EOpImageAtomicMin:
3067 case glslang::EOpImageAtomicMax:
3068 case glslang::EOpImageAtomicAnd:
3069 case glslang::EOpImageAtomicOr:
3070 case glslang::EOpImageAtomicXor:
3071 case glslang::EOpImageAtomicExchange:
3072 case glslang::EOpImageAtomicCompSwap:
3073 if (i == 0)
3074 lvalue = true;
3075 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003076 case glslang::EOpSparseImageLoad:
3077 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3078 lvalue = true;
3079 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003080 case glslang::EOpSparseTexture:
3081 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3082 lvalue = true;
3083 break;
3084 case glslang::EOpSparseTextureClamp:
3085 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3086 lvalue = true;
3087 break;
3088 case glslang::EOpSparseTextureLod:
3089 case glslang::EOpSparseTextureOffset:
3090 if (i == 3)
3091 lvalue = true;
3092 break;
3093 case glslang::EOpSparseTextureFetch:
3094 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3095 lvalue = true;
3096 break;
3097 case glslang::EOpSparseTextureFetchOffset:
3098 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3099 lvalue = true;
3100 break;
3101 case glslang::EOpSparseTextureLodOffset:
3102 case glslang::EOpSparseTextureGrad:
3103 case glslang::EOpSparseTextureOffsetClamp:
3104 if (i == 4)
3105 lvalue = true;
3106 break;
3107 case glslang::EOpSparseTextureGradOffset:
3108 case glslang::EOpSparseTextureGradClamp:
3109 if (i == 5)
3110 lvalue = true;
3111 break;
3112 case glslang::EOpSparseTextureGradOffsetClamp:
3113 if (i == 6)
3114 lvalue = true;
3115 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003116 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003117 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3118 lvalue = true;
3119 break;
3120 case glslang::EOpSparseTextureGatherOffset:
3121 case glslang::EOpSparseTextureGatherOffsets:
3122 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3123 lvalue = true;
3124 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003125#ifdef AMD_EXTENSIONS
3126 case glslang::EOpSparseTextureGatherLod:
3127 if (i == 3)
3128 lvalue = true;
3129 break;
3130 case glslang::EOpSparseTextureGatherLodOffset:
3131 case glslang::EOpSparseTextureGatherLodOffsets:
3132 if (i == 4)
3133 lvalue = true;
3134 break;
3135#endif
Rex Xufc618912015-09-09 16:42:49 +08003136 default:
3137 break;
3138 }
3139
Rex Xu6b86d492015-09-16 17:48:22 +08003140 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003141 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003142 else
John Kessenich32cfd492016-02-02 12:37:46 -07003143 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003144 }
3145}
3146
John Kessenichfc51d282015-08-19 13:34:18 -06003147void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003148{
John Kessenichfc51d282015-08-19 13:34:18 -06003149 builder.clearAccessChain();
3150 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003151 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003152}
John Kessenich140f3df2015-06-26 16:58:36 -06003153
John Kessenichfc51d282015-08-19 13:34:18 -06003154spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3155{
John Kesseniche485c7a2017-05-31 18:50:53 -06003156 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003157 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003158
3159 builder.setLine(node->getLoc().line);
3160
John Kessenich8c8505c2016-07-26 12:50:38 -06003161 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003162
John Kessenichfc51d282015-08-19 13:34:18 -06003163 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003164 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3165 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3166 std::vector<spv::Id> arguments;
3167 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003168 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003169 else
3170 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003171 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003172
3173 spv::Builder::TextureParameters params = { };
3174 params.sampler = arguments[0];
3175
Rex Xu04db3f52015-09-16 11:44:02 +08003176 glslang::TCrackedTextureOp cracked;
3177 node->crackTexture(sampler, cracked);
3178
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003179 const bool isUnsignedResult =
3180 node->getType().getBasicType() == glslang::EbtUint64 ||
3181 node->getType().getBasicType() == glslang::EbtUint;
3182
John Kessenichfc51d282015-08-19 13:34:18 -06003183 // Check for queries
3184 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003185 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3186 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003187 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003188
John Kessenichfc51d282015-08-19 13:34:18 -06003189 switch (node->getOp()) {
3190 case glslang::EOpImageQuerySize:
3191 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003192 if (arguments.size() > 1) {
3193 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003194 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003195 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003196 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003197 case glslang::EOpImageQuerySamples:
3198 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003199 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003200 case glslang::EOpTextureQueryLod:
3201 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003202 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003203 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003204 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003205 case glslang::EOpSparseTexelsResident:
3206 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003207 default:
3208 assert(0);
3209 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003210 }
John Kessenich140f3df2015-06-26 16:58:36 -06003211 }
3212
Rex Xufc618912015-09-09 16:42:49 +08003213 // Check for image functions other than queries
3214 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003215 std::vector<spv::Id> operands;
3216 auto opIt = arguments.begin();
3217 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003218
3219 // Handle subpass operations
3220 // TODO: GLSL should change to have the "MS" only on the type rather than the
3221 // built-in function.
3222 if (cracked.subpass) {
3223 // add on the (0,0) coordinate
3224 spv::Id zero = builder.makeIntConstant(0);
3225 std::vector<spv::Id> comps;
3226 comps.push_back(zero);
3227 comps.push_back(zero);
3228 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3229 if (sampler.ms) {
3230 operands.push_back(spv::ImageOperandsSampleMask);
3231 operands.push_back(*(opIt++));
3232 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003233 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003234 }
3235
John Kessenich56bab042015-09-16 10:54:31 -06003236 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003237 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003238 if (sampler.ms) {
3239 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003240 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003241 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003242 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3243 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003244 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003245 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003246 if (sampler.ms) {
3247 operands.push_back(*(opIt + 1));
3248 operands.push_back(spv::ImageOperandsSampleMask);
3249 operands.push_back(*opIt);
3250 } else
3251 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003252 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003253 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3254 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003255 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003256 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3257 builder.addCapability(spv::CapabilitySparseResidency);
3258 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3259 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3260
3261 if (sampler.ms) {
3262 operands.push_back(spv::ImageOperandsSampleMask);
3263 operands.push_back(*opIt++);
3264 }
3265
3266 // Create the return type that was a special structure
3267 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003268 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003269 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3270 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3271
3272 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3273
3274 // Decode the return type
3275 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3276 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003277 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003278 // Process image atomic operations
3279
3280 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3281 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003282 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003283
John Kessenich8c8505c2016-07-26 12:50:38 -06003284 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003285 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003286
3287 std::vector<spv::Id> operands;
3288 operands.push_back(pointer);
3289 for (; opIt != arguments.end(); ++opIt)
3290 operands.push_back(*opIt);
3291
John Kessenich8c8505c2016-07-26 12:50:38 -06003292 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003293 }
3294 }
3295
3296 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003297 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003298 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3299
John Kessenichfc51d282015-08-19 13:34:18 -06003300 // check for bias argument
3301 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003302#ifdef AMD_EXTENSIONS
3303 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3304#else
Rex Xu71519fe2015-11-11 15:35:47 +08003305 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003306#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003307 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003308#ifdef AMD_EXTENSIONS
3309 if (cracked.gather)
3310 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3311#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003312 if (cracked.offset)
3313 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003314#ifdef AMD_EXTENSIONS
3315 else if (cracked.offsets)
3316 ++nonBiasArgCount;
3317#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003318 if (cracked.grad)
3319 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003320 if (cracked.lodClamp)
3321 ++nonBiasArgCount;
3322 if (sparse)
3323 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003324
3325 if ((int)arguments.size() > nonBiasArgCount)
3326 bias = true;
3327 }
3328
John Kessenicha5c33d62016-06-02 23:45:21 -06003329 // See if the sampler param should really be just the SPV image part
3330 if (cracked.fetch) {
3331 // a fetch needs to have the image extracted first
3332 if (builder.isSampledImage(params.sampler))
3333 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3334 }
3335
Rex Xu225e0fc2016-11-17 17:47:59 +08003336#ifdef AMD_EXTENSIONS
3337 if (cracked.gather) {
3338 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3339 if (bias || cracked.lod ||
3340 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3341 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003342 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003343 }
3344 }
3345#endif
3346
John Kessenichfc51d282015-08-19 13:34:18 -06003347 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003348
John Kessenichfc51d282015-08-19 13:34:18 -06003349 params.coords = arguments[1];
3350 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003351 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003352
3353 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003354 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003355 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003356 ++extraArgs;
3357 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003358 params.Dref = arguments[2];
3359 ++extraArgs;
3360 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003361 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003362 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003363 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003364 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003365 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003366 dRefComp = builder.getNumComponents(params.coords) - 1;
3367 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003368 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3369 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003370
3371 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003372 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003373 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003374 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003375 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3376 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3377 noImplicitLod = true;
3378 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003379
3380 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003381 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003382 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003383 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003384 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003385
3386 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003387 if (cracked.grad) {
3388 params.gradX = arguments[2 + extraArgs];
3389 params.gradY = arguments[3 + extraArgs];
3390 extraArgs += 2;
3391 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003392
3393 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003394 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003395 params.offset = arguments[2 + extraArgs];
3396 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003397 } else if (cracked.offsets) {
3398 params.offsets = arguments[2 + extraArgs];
3399 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003400 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003401
3402 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003403 if (cracked.lodClamp) {
3404 params.lodClamp = arguments[2 + extraArgs];
3405 ++extraArgs;
3406 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003407
3408 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003409 if (sparse) {
3410 params.texelOut = arguments[2 + extraArgs];
3411 ++extraArgs;
3412 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003413
John Kessenich76d4dfc2016-06-16 12:43:23 -06003414 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003415 if (cracked.gather && ! sampler.shadow) {
3416 // default component is 0, if missing, otherwise an argument
3417 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003418 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003419 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003420 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003421 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003422 }
3423
3424 // bias
3425 if (bias) {
3426 params.bias = arguments[2 + extraArgs];
3427 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003428 }
John Kessenichfc51d282015-08-19 13:34:18 -06003429
John Kessenich65336482016-06-16 14:06:26 -06003430 // projective component (might not to move)
3431 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3432 // are divided by the last component of P."
3433 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3434 // unused components will appear after all used components."
3435 if (cracked.proj) {
3436 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3437 int projTargetComp;
3438 switch (sampler.dim) {
3439 case glslang::Esd1D: projTargetComp = 1; break;
3440 case glslang::Esd2D: projTargetComp = 2; break;
3441 case glslang::EsdRect: projTargetComp = 2; break;
3442 default: projTargetComp = projSourceComp; break;
3443 }
3444 // copy the projective coordinate if we have to
3445 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003446 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003447 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3448 projSourceComp);
3449 params.coords = builder.createCompositeInsert(projComp, params.coords,
3450 builder.getTypeId(params.coords), projTargetComp);
3451 }
3452 }
3453
John Kessenich8c8505c2016-07-26 12:50:38 -06003454 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003455}
3456
3457spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3458{
3459 // Grab the function's pointer from the previously created function
3460 spv::Function* function = functionMap[node->getName().c_str()];
3461 if (! function)
3462 return 0;
3463
3464 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3465 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3466
3467 // See comments in makeFunctions() for details about the semantics for parameter passing.
3468 //
3469 // These imply we need a four step process:
3470 // 1. Evaluate the arguments
3471 // 2. Allocate and make copies of in, out, and inout arguments
3472 // 3. Make the call
3473 // 4. Copy back the results
3474
3475 // 1. Evaluate the arguments
3476 std::vector<spv::Builder::AccessChain> lValues;
3477 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003478 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003480 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003481 // build l-value
3482 builder.clearAccessChain();
3483 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003484 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003485 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003486 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003487 // save l-value
3488 lValues.push_back(builder.getAccessChain());
3489 } else {
3490 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003491 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003492 }
3493 }
3494
3495 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3496 // copy the original into that space.
3497 //
3498 // Also, build up the list of actual arguments to pass in for the call
3499 int lValueCount = 0;
3500 int rValueCount = 0;
3501 std::vector<spv::Id> spvArgs;
3502 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003503 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003504 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003505 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003506 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3507 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003508 builder.setAccessChain(lValues[lValueCount]);
3509 arg = builder.accessChainGetLValue();
3510 ++lValueCount;
3511 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003512 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003513 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3514 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3515 // need to copy the input into output space
3516 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003517 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003518 builder.clearAccessChain();
3519 builder.setAccessChainLValue(arg);
3520 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003521 }
3522 ++lValueCount;
3523 } else {
3524 arg = rValues[rValueCount];
3525 ++rValueCount;
3526 }
3527 spvArgs.push_back(arg);
3528 }
3529
3530 // 3. Make the call.
3531 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003532 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003533
3534 // 4. Copy back out an "out" arguments.
3535 lValueCount = 0;
3536 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003537 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003538 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3539 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3540 spv::Id copy = builder.createLoad(spvArgs[a]);
3541 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003542 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003543 }
3544 ++lValueCount;
3545 }
3546 }
3547
3548 return result;
3549}
3550
3551// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003552spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3553 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003554 spv::Id typeId, spv::Id left, spv::Id right,
3555 glslang::TBasicType typeProxy, bool reduceComparison)
3556{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003557#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003558 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003559 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3560#else
Rex Xucabbb782017-03-24 13:41:14 +08003561 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003562 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003563#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003564 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003565
3566 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003567 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003568 bool comparison = false;
3569
3570 switch (op) {
3571 case glslang::EOpAdd:
3572 case glslang::EOpAddAssign:
3573 if (isFloat)
3574 binOp = spv::OpFAdd;
3575 else
3576 binOp = spv::OpIAdd;
3577 break;
3578 case glslang::EOpSub:
3579 case glslang::EOpSubAssign:
3580 if (isFloat)
3581 binOp = spv::OpFSub;
3582 else
3583 binOp = spv::OpISub;
3584 break;
3585 case glslang::EOpMul:
3586 case glslang::EOpMulAssign:
3587 if (isFloat)
3588 binOp = spv::OpFMul;
3589 else
3590 binOp = spv::OpIMul;
3591 break;
3592 case glslang::EOpVectorTimesScalar:
3593 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003594 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003595 if (builder.isVector(right))
3596 std::swap(left, right);
3597 assert(builder.isScalar(right));
3598 needMatchingVectors = false;
3599 binOp = spv::OpVectorTimesScalar;
3600 } else
3601 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpVectorTimesMatrix:
3604 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003605 binOp = spv::OpVectorTimesMatrix;
3606 break;
3607 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003608 binOp = spv::OpMatrixTimesVector;
3609 break;
3610 case glslang::EOpMatrixTimesScalar:
3611 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003612 binOp = spv::OpMatrixTimesScalar;
3613 break;
3614 case glslang::EOpMatrixTimesMatrix:
3615 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003616 binOp = spv::OpMatrixTimesMatrix;
3617 break;
3618 case glslang::EOpOuterProduct:
3619 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003620 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003621 break;
3622
3623 case glslang::EOpDiv:
3624 case glslang::EOpDivAssign:
3625 if (isFloat)
3626 binOp = spv::OpFDiv;
3627 else if (isUnsigned)
3628 binOp = spv::OpUDiv;
3629 else
3630 binOp = spv::OpSDiv;
3631 break;
3632 case glslang::EOpMod:
3633 case glslang::EOpModAssign:
3634 if (isFloat)
3635 binOp = spv::OpFMod;
3636 else if (isUnsigned)
3637 binOp = spv::OpUMod;
3638 else
3639 binOp = spv::OpSMod;
3640 break;
3641 case glslang::EOpRightShift:
3642 case glslang::EOpRightShiftAssign:
3643 if (isUnsigned)
3644 binOp = spv::OpShiftRightLogical;
3645 else
3646 binOp = spv::OpShiftRightArithmetic;
3647 break;
3648 case glslang::EOpLeftShift:
3649 case glslang::EOpLeftShiftAssign:
3650 binOp = spv::OpShiftLeftLogical;
3651 break;
3652 case glslang::EOpAnd:
3653 case glslang::EOpAndAssign:
3654 binOp = spv::OpBitwiseAnd;
3655 break;
3656 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003657 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 binOp = spv::OpLogicalAnd;
3659 break;
3660 case glslang::EOpInclusiveOr:
3661 case glslang::EOpInclusiveOrAssign:
3662 binOp = spv::OpBitwiseOr;
3663 break;
3664 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003665 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003666 binOp = spv::OpLogicalOr;
3667 break;
3668 case glslang::EOpExclusiveOr:
3669 case glslang::EOpExclusiveOrAssign:
3670 binOp = spv::OpBitwiseXor;
3671 break;
3672 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003673 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003674 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003675 break;
3676
3677 case glslang::EOpLessThan:
3678 case glslang::EOpGreaterThan:
3679 case glslang::EOpLessThanEqual:
3680 case glslang::EOpGreaterThanEqual:
3681 case glslang::EOpEqual:
3682 case glslang::EOpNotEqual:
3683 case glslang::EOpVectorEqual:
3684 case glslang::EOpVectorNotEqual:
3685 comparison = true;
3686 break;
3687 default:
3688 break;
3689 }
3690
John Kessenich7c1aa102015-10-15 13:29:11 -06003691 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003692 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003693 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003694 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003695 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003696
3697 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003698 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003699 builder.promoteScalar(precision, left, right);
3700
qining25262b32016-05-06 17:25:16 -04003701 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3702 addDecoration(result, noContraction);
3703 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003704 }
3705
3706 if (! comparison)
3707 return 0;
3708
John Kessenich7c1aa102015-10-15 13:29:11 -06003709 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003710
John Kessenich4583b612016-08-07 19:14:22 -06003711 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3712 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003713 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003714
3715 switch (op) {
3716 case glslang::EOpLessThan:
3717 if (isFloat)
3718 binOp = spv::OpFOrdLessThan;
3719 else if (isUnsigned)
3720 binOp = spv::OpULessThan;
3721 else
3722 binOp = spv::OpSLessThan;
3723 break;
3724 case glslang::EOpGreaterThan:
3725 if (isFloat)
3726 binOp = spv::OpFOrdGreaterThan;
3727 else if (isUnsigned)
3728 binOp = spv::OpUGreaterThan;
3729 else
3730 binOp = spv::OpSGreaterThan;
3731 break;
3732 case glslang::EOpLessThanEqual:
3733 if (isFloat)
3734 binOp = spv::OpFOrdLessThanEqual;
3735 else if (isUnsigned)
3736 binOp = spv::OpULessThanEqual;
3737 else
3738 binOp = spv::OpSLessThanEqual;
3739 break;
3740 case glslang::EOpGreaterThanEqual:
3741 if (isFloat)
3742 binOp = spv::OpFOrdGreaterThanEqual;
3743 else if (isUnsigned)
3744 binOp = spv::OpUGreaterThanEqual;
3745 else
3746 binOp = spv::OpSGreaterThanEqual;
3747 break;
3748 case glslang::EOpEqual:
3749 case glslang::EOpVectorEqual:
3750 if (isFloat)
3751 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003752 else if (isBool)
3753 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 else
3755 binOp = spv::OpIEqual;
3756 break;
3757 case glslang::EOpNotEqual:
3758 case glslang::EOpVectorNotEqual:
3759 if (isFloat)
3760 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003761 else if (isBool)
3762 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003763 else
3764 binOp = spv::OpINotEqual;
3765 break;
3766 default:
3767 break;
3768 }
3769
qining25262b32016-05-06 17:25:16 -04003770 if (binOp != spv::OpNop) {
3771 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3772 addDecoration(result, noContraction);
3773 return builder.setPrecision(result, precision);
3774 }
John Kessenich140f3df2015-06-26 16:58:36 -06003775
3776 return 0;
3777}
3778
John Kessenich04bb8a02015-12-12 12:28:14 -07003779//
3780// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3781// These can be any of:
3782//
3783// matrix * scalar
3784// scalar * matrix
3785// matrix * matrix linear algebraic
3786// matrix * vector
3787// vector * matrix
3788// matrix * matrix componentwise
3789// matrix op matrix op in {+, -, /}
3790// matrix op scalar op in {+, -, /}
3791// scalar op matrix op in {+, -, /}
3792//
qining25262b32016-05-06 17:25:16 -04003793spv::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 -07003794{
3795 bool firstClass = true;
3796
3797 // First, handle first-class matrix operations (* and matrix/scalar)
3798 switch (op) {
3799 case spv::OpFDiv:
3800 if (builder.isMatrix(left) && builder.isScalar(right)) {
3801 // turn matrix / scalar into a multiply...
3802 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3803 op = spv::OpMatrixTimesScalar;
3804 } else
3805 firstClass = false;
3806 break;
3807 case spv::OpMatrixTimesScalar:
3808 if (builder.isMatrix(right))
3809 std::swap(left, right);
3810 assert(builder.isScalar(right));
3811 break;
3812 case spv::OpVectorTimesMatrix:
3813 assert(builder.isVector(left));
3814 assert(builder.isMatrix(right));
3815 break;
3816 case spv::OpMatrixTimesVector:
3817 assert(builder.isMatrix(left));
3818 assert(builder.isVector(right));
3819 break;
3820 case spv::OpMatrixTimesMatrix:
3821 assert(builder.isMatrix(left));
3822 assert(builder.isMatrix(right));
3823 break;
3824 default:
3825 firstClass = false;
3826 break;
3827 }
3828
qining25262b32016-05-06 17:25:16 -04003829 if (firstClass) {
3830 spv::Id result = builder.createBinOp(op, typeId, left, right);
3831 addDecoration(result, noContraction);
3832 return builder.setPrecision(result, precision);
3833 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003834
LoopDawg592860c2016-06-09 08:57:35 -06003835 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003836 // The result type of all of them is the same type as the (a) matrix operand.
3837 // The algorithm is to:
3838 // - break the matrix(es) into vectors
3839 // - smear any scalar to a vector
3840 // - do vector operations
3841 // - make a matrix out the vector results
3842 switch (op) {
3843 case spv::OpFAdd:
3844 case spv::OpFSub:
3845 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003846 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003847 case spv::OpFMul:
3848 {
3849 // one time set up...
3850 bool leftMat = builder.isMatrix(left);
3851 bool rightMat = builder.isMatrix(right);
3852 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3853 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3854 spv::Id scalarType = builder.getScalarTypeId(typeId);
3855 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3856 std::vector<spv::Id> results;
3857 spv::Id smearVec = spv::NoResult;
3858 if (builder.isScalar(left))
3859 smearVec = builder.smearScalar(precision, left, vecType);
3860 else if (builder.isScalar(right))
3861 smearVec = builder.smearScalar(precision, right, vecType);
3862
3863 // do each vector op
3864 for (unsigned int c = 0; c < numCols; ++c) {
3865 std::vector<unsigned int> indexes;
3866 indexes.push_back(c);
3867 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3868 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003869 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3870 addDecoration(result, noContraction);
3871 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003872 }
3873
3874 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003875 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003876 }
3877 default:
3878 assert(0);
3879 return spv::NoResult;
3880 }
3881}
3882
qining25262b32016-05-06 17:25:16 -04003883spv::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 -06003884{
3885 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003886 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003888#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003889 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003890 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3891#else
Rex Xucabbb782017-03-24 13:41:14 +08003892 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003893 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003894#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003895
3896 switch (op) {
3897 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003898 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003899 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003900 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003901 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003902 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003903 unaryOp = spv::OpSNegate;
3904 break;
3905
3906 case glslang::EOpLogicalNot:
3907 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003908 unaryOp = spv::OpLogicalNot;
3909 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003910 case glslang::EOpBitwiseNot:
3911 unaryOp = spv::OpNot;
3912 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003913
John Kessenich140f3df2015-06-26 16:58:36 -06003914 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003915 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003918 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003919 break;
3920 case glslang::EOpTranspose:
3921 unaryOp = spv::OpTranspose;
3922 break;
3923
3924 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003925 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003926 break;
3927 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003928 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003929 break;
3930 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003931 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003932 break;
3933 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003934 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003935 break;
3936 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003937 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003938 break;
3939 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003940 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003941 break;
3942 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003943 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003944 break;
3945 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003946 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003947 break;
3948
3949 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003950 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003951 break;
3952 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003953 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003954 break;
3955 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003956 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003957 break;
3958 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003959 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003960 break;
3961 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003962 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003963 break;
3964 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003965 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003966 break;
3967
3968 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003969 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003970 break;
3971 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003972 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003973 break;
3974
3975 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003976 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003977 break;
3978 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003980 break;
3981 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003982 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003983 break;
3984 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003985 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003986 break;
3987 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003988 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003989 break;
3990 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003991 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003992 break;
3993
3994 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003995 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003996 break;
3997 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003998 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003999 break;
4000 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004001 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004002 break;
4003 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004004 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004005 break;
4006 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004007 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004008 break;
4009 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004010 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004011 break;
4012
4013 case glslang::EOpIsNan:
4014 unaryOp = spv::OpIsNan;
4015 break;
4016 case glslang::EOpIsInf:
4017 unaryOp = spv::OpIsInf;
4018 break;
LoopDawg592860c2016-06-09 08:57:35 -06004019 case glslang::EOpIsFinite:
4020 unaryOp = spv::OpIsFinite;
4021 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004022
Rex Xucbc426e2015-12-15 16:03:10 +08004023 case glslang::EOpFloatBitsToInt:
4024 case glslang::EOpFloatBitsToUint:
4025 case glslang::EOpIntBitsToFloat:
4026 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004027 case glslang::EOpDoubleBitsToInt64:
4028 case glslang::EOpDoubleBitsToUint64:
4029 case glslang::EOpInt64BitsToDouble:
4030 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004031#ifdef AMD_EXTENSIONS
4032 case glslang::EOpFloat16BitsToInt16:
4033 case glslang::EOpFloat16BitsToUint16:
4034 case glslang::EOpInt16BitsToFloat16:
4035 case glslang::EOpUint16BitsToFloat16:
4036#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004037 unaryOp = spv::OpBitcast;
4038 break;
4039
John Kessenich140f3df2015-06-26 16:58:36 -06004040 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004041 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004042 break;
4043 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004044 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004045 break;
4046 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004047 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004048 break;
4049 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004058 case glslang::EOpPackSnorm4x8:
4059 libCall = spv::GLSLstd450PackSnorm4x8;
4060 break;
4061 case glslang::EOpUnpackSnorm4x8:
4062 libCall = spv::GLSLstd450UnpackSnorm4x8;
4063 break;
4064 case glslang::EOpPackUnorm4x8:
4065 libCall = spv::GLSLstd450PackUnorm4x8;
4066 break;
4067 case glslang::EOpUnpackUnorm4x8:
4068 libCall = spv::GLSLstd450UnpackUnorm4x8;
4069 break;
4070 case glslang::EOpPackDouble2x32:
4071 libCall = spv::GLSLstd450PackDouble2x32;
4072 break;
4073 case glslang::EOpUnpackDouble2x32:
4074 libCall = spv::GLSLstd450UnpackDouble2x32;
4075 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004076
Rex Xu8ff43de2016-04-22 16:51:45 +08004077 case glslang::EOpPackInt2x32:
4078 case glslang::EOpUnpackInt2x32:
4079 case glslang::EOpPackUint2x32:
4080 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004081 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004082 break;
4083
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004084#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004085 case glslang::EOpPackInt2x16:
4086 case glslang::EOpUnpackInt2x16:
4087 case glslang::EOpPackUint2x16:
4088 case glslang::EOpUnpackUint2x16:
4089 case glslang::EOpPackInt4x16:
4090 case glslang::EOpUnpackInt4x16:
4091 case glslang::EOpPackUint4x16:
4092 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004093 case glslang::EOpPackFloat2x16:
4094 case glslang::EOpUnpackFloat2x16:
4095 unaryOp = spv::OpBitcast;
4096 break;
4097#endif
4098
John Kessenich140f3df2015-06-26 16:58:36 -06004099 case glslang::EOpDPdx:
4100 unaryOp = spv::OpDPdx;
4101 break;
4102 case glslang::EOpDPdy:
4103 unaryOp = spv::OpDPdy;
4104 break;
4105 case glslang::EOpFwidth:
4106 unaryOp = spv::OpFwidth;
4107 break;
4108 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004109 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004110 unaryOp = spv::OpDPdxFine;
4111 break;
4112 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004113 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004114 unaryOp = spv::OpDPdyFine;
4115 break;
4116 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004117 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004118 unaryOp = spv::OpFwidthFine;
4119 break;
4120 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004121 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004122 unaryOp = spv::OpDPdxCoarse;
4123 break;
4124 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004125 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004126 unaryOp = spv::OpDPdyCoarse;
4127 break;
4128 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004129 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004130 unaryOp = spv::OpFwidthCoarse;
4131 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004132 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004133 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004134 libCall = spv::GLSLstd450InterpolateAtCentroid;
4135 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 case glslang::EOpAny:
4137 unaryOp = spv::OpAny;
4138 break;
4139 case glslang::EOpAll:
4140 unaryOp = spv::OpAll;
4141 break;
4142
4143 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004144 if (isFloat)
4145 libCall = spv::GLSLstd450FAbs;
4146 else
4147 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004148 break;
4149 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004150 if (isFloat)
4151 libCall = spv::GLSLstd450FSign;
4152 else
4153 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004154 break;
4155
John Kessenichfc51d282015-08-19 13:34:18 -06004156 case glslang::EOpAtomicCounterIncrement:
4157 case glslang::EOpAtomicCounterDecrement:
4158 case glslang::EOpAtomicCounter:
4159 {
4160 // Handle all of the atomics in one place, in createAtomicOperation()
4161 std::vector<spv::Id> operands;
4162 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004163 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004164 }
4165
John Kessenichfc51d282015-08-19 13:34:18 -06004166 case glslang::EOpBitFieldReverse:
4167 unaryOp = spv::OpBitReverse;
4168 break;
4169 case glslang::EOpBitCount:
4170 unaryOp = spv::OpBitCount;
4171 break;
4172 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004173 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004174 break;
4175 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004176 if (isUnsigned)
4177 libCall = spv::GLSLstd450FindUMsb;
4178 else
4179 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004180 break;
4181
Rex Xu574ab042016-04-14 16:53:07 +08004182 case glslang::EOpBallot:
4183 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004184 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004185 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004186 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004187#ifdef AMD_EXTENSIONS
4188 case glslang::EOpMinInvocations:
4189 case glslang::EOpMaxInvocations:
4190 case glslang::EOpAddInvocations:
4191 case glslang::EOpMinInvocationsNonUniform:
4192 case glslang::EOpMaxInvocationsNonUniform:
4193 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004194 case glslang::EOpMinInvocationsInclusiveScan:
4195 case glslang::EOpMaxInvocationsInclusiveScan:
4196 case glslang::EOpAddInvocationsInclusiveScan:
4197 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4198 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4199 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4200 case glslang::EOpMinInvocationsExclusiveScan:
4201 case glslang::EOpMaxInvocationsExclusiveScan:
4202 case glslang::EOpAddInvocationsExclusiveScan:
4203 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4204 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4205 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004206#endif
Rex Xu51596642016-09-21 18:56:12 +08004207 {
4208 std::vector<spv::Id> operands;
4209 operands.push_back(operand);
4210 return createInvocationsOperation(op, typeId, operands, typeProxy);
4211 }
Rex Xu9d93a232016-05-05 12:30:44 +08004212
4213#ifdef AMD_EXTENSIONS
4214 case glslang::EOpMbcnt:
4215 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4216 libCall = spv::MbcntAMD;
4217 break;
4218
4219 case glslang::EOpCubeFaceIndex:
4220 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4221 libCall = spv::CubeFaceIndexAMD;
4222 break;
4223
4224 case glslang::EOpCubeFaceCoord:
4225 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4226 libCall = spv::CubeFaceCoordAMD;
4227 break;
4228#endif
Rex Xu338b1852016-05-05 20:38:33 +08004229
John Kessenich140f3df2015-06-26 16:58:36 -06004230 default:
4231 return 0;
4232 }
4233
4234 spv::Id id;
4235 if (libCall >= 0) {
4236 std::vector<spv::Id> args;
4237 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004238 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004239 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004240 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004241 }
John Kessenich140f3df2015-06-26 16:58:36 -06004242
qining25262b32016-05-06 17:25:16 -04004243 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004244 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004245}
4246
John Kessenich7a53f762016-01-20 11:19:27 -07004247// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004248spv::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 -07004249{
4250 // Handle unary operations vector by vector.
4251 // The result type is the same type as the original type.
4252 // The algorithm is to:
4253 // - break the matrix into vectors
4254 // - apply the operation to each vector
4255 // - make a matrix out the vector results
4256
4257 // get the types sorted out
4258 int numCols = builder.getNumColumns(operand);
4259 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004260 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4261 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004262 std::vector<spv::Id> results;
4263
4264 // do each vector op
4265 for (int c = 0; c < numCols; ++c) {
4266 std::vector<unsigned int> indexes;
4267 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004268 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4269 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4270 addDecoration(destVec, noContraction);
4271 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004272 }
4273
4274 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004275 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004276}
4277
Rex Xu73e3ce72016-04-27 18:48:17 +08004278spv::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 -06004279{
4280 spv::Op convOp = spv::OpNop;
4281 spv::Id zero = 0;
4282 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004283 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004284
4285 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4286
4287 switch (op) {
4288 case glslang::EOpConvIntToBool:
4289 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004290 case glslang::EOpConvInt64ToBool:
4291 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004292#ifdef AMD_EXTENSIONS
4293 case glslang::EOpConvInt16ToBool:
4294 case glslang::EOpConvUint16ToBool:
4295#endif
4296 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4297 zero = builder.makeUint64Constant(0);
4298#ifdef AMD_EXTENSIONS
4299 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4300 zero = builder.makeUint16Constant(0);
4301#endif
4302 else
4303 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004304 zero = makeSmearedConstant(zero, vectorSize);
4305 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4306
4307 case glslang::EOpConvFloatToBool:
4308 zero = builder.makeFloatConstant(0.0F);
4309 zero = makeSmearedConstant(zero, vectorSize);
4310 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4311
4312 case glslang::EOpConvDoubleToBool:
4313 zero = builder.makeDoubleConstant(0.0);
4314 zero = makeSmearedConstant(zero, vectorSize);
4315 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4316
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004317#ifdef AMD_EXTENSIONS
4318 case glslang::EOpConvFloat16ToBool:
4319 zero = builder.makeFloat16Constant(0.0F);
4320 zero = makeSmearedConstant(zero, vectorSize);
4321 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4322#endif
4323
John Kessenich140f3df2015-06-26 16:58:36 -06004324 case glslang::EOpConvBoolToFloat:
4325 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004326 zero = builder.makeFloatConstant(0.0F);
4327 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004328 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004329
John Kessenich140f3df2015-06-26 16:58:36 -06004330 case glslang::EOpConvBoolToDouble:
4331 convOp = spv::OpSelect;
4332 zero = builder.makeDoubleConstant(0.0);
4333 one = builder.makeDoubleConstant(1.0);
4334 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004335
4336#ifdef AMD_EXTENSIONS
4337 case glslang::EOpConvBoolToFloat16:
4338 convOp = spv::OpSelect;
4339 zero = builder.makeFloat16Constant(0.0F);
4340 one = builder.makeFloat16Constant(1.0F);
4341 break;
4342#endif
4343
John Kessenich140f3df2015-06-26 16:58:36 -06004344 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004345 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004346#ifdef AMD_EXTENSIONS
4347 case glslang::EOpConvBoolToInt16:
4348#endif
4349 if (op == glslang::EOpConvBoolToInt64)
4350 zero = builder.makeInt64Constant(0);
4351#ifdef AMD_EXTENSIONS
4352 else if (op == glslang::EOpConvBoolToInt16)
4353 zero = builder.makeInt16Constant(0);
4354#endif
4355 else
4356 zero = builder.makeIntConstant(0);
4357
4358 if (op == glslang::EOpConvBoolToInt64)
4359 one = builder.makeInt64Constant(1);
4360#ifdef AMD_EXTENSIONS
4361 else if (op == glslang::EOpConvBoolToInt16)
4362 one = builder.makeInt16Constant(1);
4363#endif
4364 else
4365 one = builder.makeIntConstant(1);
4366
John Kessenich140f3df2015-06-26 16:58:36 -06004367 convOp = spv::OpSelect;
4368 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004369
John Kessenich140f3df2015-06-26 16:58:36 -06004370 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004371 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004372#ifdef AMD_EXTENSIONS
4373 case glslang::EOpConvBoolToUint16:
4374#endif
4375 if (op == glslang::EOpConvBoolToUint64)
4376 zero = builder.makeUint64Constant(0);
4377#ifdef AMD_EXTENSIONS
4378 else if (op == glslang::EOpConvBoolToUint16)
4379 zero = builder.makeUint16Constant(0);
4380#endif
4381 else
4382 zero = builder.makeUintConstant(0);
4383
4384 if (op == glslang::EOpConvBoolToUint64)
4385 one = builder.makeUint64Constant(1);
4386#ifdef AMD_EXTENSIONS
4387 else if (op == glslang::EOpConvBoolToUint16)
4388 one = builder.makeUint16Constant(1);
4389#endif
4390 else
4391 one = builder.makeUintConstant(1);
4392
John Kessenich140f3df2015-06-26 16:58:36 -06004393 convOp = spv::OpSelect;
4394 break;
4395
4396 case glslang::EOpConvIntToFloat:
4397 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004398 case glslang::EOpConvInt64ToFloat:
4399 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004400#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004401 case glslang::EOpConvInt16ToFloat:
4402 case glslang::EOpConvInt16ToDouble:
4403 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004404 case glslang::EOpConvIntToFloat16:
4405 case glslang::EOpConvInt64ToFloat16:
4406#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004407 convOp = spv::OpConvertSToF;
4408 break;
4409
4410 case glslang::EOpConvUintToFloat:
4411 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004412 case glslang::EOpConvUint64ToFloat:
4413 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004414#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004415 case glslang::EOpConvUint16ToFloat:
4416 case glslang::EOpConvUint16ToDouble:
4417 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004418 case glslang::EOpConvUintToFloat16:
4419 case glslang::EOpConvUint64ToFloat16:
4420#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004421 convOp = spv::OpConvertUToF;
4422 break;
4423
4424 case glslang::EOpConvDoubleToFloat:
4425 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004426#ifdef AMD_EXTENSIONS
4427 case glslang::EOpConvDoubleToFloat16:
4428 case glslang::EOpConvFloat16ToDouble:
4429 case glslang::EOpConvFloatToFloat16:
4430 case glslang::EOpConvFloat16ToFloat:
4431#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004432 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004433 if (builder.isMatrixType(destType))
4434 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004435 break;
4436
4437 case glslang::EOpConvFloatToInt:
4438 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004439 case glslang::EOpConvFloatToInt64:
4440 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004441#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004442 case glslang::EOpConvFloatToInt16:
4443 case glslang::EOpConvDoubleToInt16:
4444 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004445 case glslang::EOpConvFloat16ToInt:
4446 case glslang::EOpConvFloat16ToInt64:
4447#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004448 convOp = spv::OpConvertFToS;
4449 break;
4450
4451 case glslang::EOpConvUintToInt:
4452 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004453 case glslang::EOpConvUint64ToInt64:
4454 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004455#ifdef AMD_EXTENSIONS
4456 case glslang::EOpConvUint16ToInt16:
4457 case glslang::EOpConvInt16ToUint16:
4458#endif
qininge24aa5e2016-04-07 15:40:27 -04004459 if (builder.isInSpecConstCodeGenMode()) {
4460 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004461 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4462 zero = builder.makeUint64Constant(0);
4463#ifdef AMD_EXTENSIONS
4464 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4465 zero = builder.makeUint16Constant(0);
4466#endif
4467 else
4468 zero = builder.makeUintConstant(0);
4469
qining189b2032016-04-12 23:16:20 -04004470 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004471 // Use OpIAdd, instead of OpBitcast to do the conversion when
4472 // generating for OpSpecConstantOp instruction.
4473 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4474 }
4475 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004476 convOp = spv::OpBitcast;
4477 break;
4478
4479 case glslang::EOpConvFloatToUint:
4480 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004481 case glslang::EOpConvFloatToUint64:
4482 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004483#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004484 case glslang::EOpConvFloatToUint16:
4485 case glslang::EOpConvDoubleToUint16:
4486 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004487 case glslang::EOpConvFloat16ToUint:
4488 case glslang::EOpConvFloat16ToUint64:
4489#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004490 convOp = spv::OpConvertFToU;
4491 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004492
4493 case glslang::EOpConvIntToInt64:
4494 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004495#ifdef AMD_EXTENSIONS
4496 case glslang::EOpConvIntToInt16:
4497 case glslang::EOpConvInt16ToInt:
4498 case glslang::EOpConvInt64ToInt16:
4499 case glslang::EOpConvInt16ToInt64:
4500#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004501 convOp = spv::OpSConvert;
4502 break;
4503
4504 case glslang::EOpConvUintToUint64:
4505 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004506#ifdef AMD_EXTENSIONS
4507 case glslang::EOpConvUintToUint16:
4508 case glslang::EOpConvUint16ToUint:
4509 case glslang::EOpConvUint64ToUint16:
4510 case glslang::EOpConvUint16ToUint64:
4511#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004512 convOp = spv::OpUConvert;
4513 break;
4514
4515 case glslang::EOpConvIntToUint64:
4516 case glslang::EOpConvInt64ToUint:
4517 case glslang::EOpConvUint64ToInt:
4518 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004519#ifdef AMD_EXTENSIONS
4520 case glslang::EOpConvInt16ToUint:
4521 case glslang::EOpConvUintToInt16:
4522 case glslang::EOpConvInt16ToUint64:
4523 case glslang::EOpConvUint64ToInt16:
4524 case glslang::EOpConvUint16ToInt:
4525 case glslang::EOpConvIntToUint16:
4526 case glslang::EOpConvUint16ToInt64:
4527 case glslang::EOpConvInt64ToUint16:
4528#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004529 // OpSConvert/OpUConvert + OpBitCast
4530 switch (op) {
4531 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004532#ifdef AMD_EXTENSIONS
4533 case glslang::EOpConvInt16ToUint64:
4534#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004535 convOp = spv::OpSConvert;
4536 type = builder.makeIntType(64);
4537 break;
4538 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004539#ifdef AMD_EXTENSIONS
4540 case glslang::EOpConvInt16ToUint:
4541#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004542 convOp = spv::OpSConvert;
4543 type = builder.makeIntType(32);
4544 break;
4545 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004546#ifdef AMD_EXTENSIONS
4547 case glslang::EOpConvUint16ToInt:
4548#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004549 convOp = spv::OpUConvert;
4550 type = builder.makeUintType(32);
4551 break;
4552 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004553#ifdef AMD_EXTENSIONS
4554 case glslang::EOpConvUint16ToInt64:
4555#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004556 convOp = spv::OpUConvert;
4557 type = builder.makeUintType(64);
4558 break;
Rex Xucabbb782017-03-24 13:41:14 +08004559#ifdef AMD_EXTENSIONS
4560 case glslang::EOpConvUintToInt16:
4561 case glslang::EOpConvUint64ToInt16:
4562 convOp = spv::OpUConvert;
4563 type = builder.makeUintType(16);
4564 break;
4565 case glslang::EOpConvIntToUint16:
4566 case glslang::EOpConvInt64ToUint16:
4567 convOp = spv::OpSConvert;
4568 type = builder.makeIntType(16);
4569 break;
4570#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004571 default:
4572 assert(0);
4573 break;
4574 }
4575
4576 if (vectorSize > 0)
4577 type = builder.makeVectorType(type, vectorSize);
4578
4579 operand = builder.createUnaryOp(convOp, type, operand);
4580
4581 if (builder.isInSpecConstCodeGenMode()) {
4582 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004583#ifdef AMD_EXTENSIONS
4584 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4585 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4586 zero = builder.makeUint64Constant(0);
4587 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4588 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4589 zero = builder.makeUint16Constant(0);
4590 else
4591 zero = builder.makeUintConstant(0);
4592#else
4593 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4594 zero = builder.makeUint64Constant(0);
4595 else
4596 zero = builder.makeUintConstant(0);
4597#endif
4598
Rex Xu8ff43de2016-04-22 16:51:45 +08004599 zero = makeSmearedConstant(zero, vectorSize);
4600 // Use OpIAdd, instead of OpBitcast to do the conversion when
4601 // generating for OpSpecConstantOp instruction.
4602 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4603 }
4604 // For normal run-time conversion instruction, use OpBitcast.
4605 convOp = spv::OpBitcast;
4606 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004607 default:
4608 break;
4609 }
4610
4611 spv::Id result = 0;
4612 if (convOp == spv::OpNop)
4613 return result;
4614
4615 if (convOp == spv::OpSelect) {
4616 zero = makeSmearedConstant(zero, vectorSize);
4617 one = makeSmearedConstant(one, vectorSize);
4618 result = builder.createTriOp(convOp, destType, operand, one, zero);
4619 } else
4620 result = builder.createUnaryOp(convOp, destType, operand);
4621
John Kessenich32cfd492016-02-02 12:37:46 -07004622 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004623}
4624
4625spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4626{
4627 if (vectorSize == 0)
4628 return constant;
4629
4630 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4631 std::vector<spv::Id> components;
4632 for (int c = 0; c < vectorSize; ++c)
4633 components.push_back(constant);
4634 return builder.makeCompositeConstant(vectorTypeId, components);
4635}
4636
John Kessenich426394d2015-07-23 10:22:48 -06004637// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004638spv::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 -06004639{
4640 spv::Op opCode = spv::OpNop;
4641
4642 switch (op) {
4643 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004644 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004645 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004646 opCode = spv::OpAtomicIAdd;
4647 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004648 case glslang::EOpAtomicCounterSubtract:
4649 opCode = spv::OpAtomicISub;
4650 break;
John Kessenich426394d2015-07-23 10:22:48 -06004651 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004652 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004653 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004654 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004655 break;
4656 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004657 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004658 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004659 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004660 break;
4661 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004662 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004663 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004664 opCode = spv::OpAtomicAnd;
4665 break;
4666 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004667 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004668 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004669 opCode = spv::OpAtomicOr;
4670 break;
4671 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004672 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004673 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004674 opCode = spv::OpAtomicXor;
4675 break;
4676 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004677 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004678 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004679 opCode = spv::OpAtomicExchange;
4680 break;
4681 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004682 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004683 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004684 opCode = spv::OpAtomicCompareExchange;
4685 break;
4686 case glslang::EOpAtomicCounterIncrement:
4687 opCode = spv::OpAtomicIIncrement;
4688 break;
4689 case glslang::EOpAtomicCounterDecrement:
4690 opCode = spv::OpAtomicIDecrement;
4691 break;
4692 case glslang::EOpAtomicCounter:
4693 opCode = spv::OpAtomicLoad;
4694 break;
4695 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004696 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004697 break;
4698 }
4699
4700 // Sort out the operands
4701 // - mapping from glslang -> SPV
4702 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004703 // - compare-exchange swaps the value and comparator
4704 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004705 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4706 auto opIt = operands.begin(); // walk the glslang operands
4707 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004708 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4709 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4710 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004711 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4712 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004713 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004714 spvAtomicOperands.push_back(*(opIt + 1));
4715 spvAtomicOperands.push_back(*opIt);
4716 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004717 }
John Kessenich426394d2015-07-23 10:22:48 -06004718
John Kessenich3e60a6f2015-09-14 22:45:16 -06004719 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004720 for (; opIt != operands.end(); ++opIt)
4721 spvAtomicOperands.push_back(*opIt);
4722
4723 return builder.createOp(opCode, typeId, spvAtomicOperands);
4724}
4725
John Kessenich91cef522016-05-05 16:45:40 -06004726// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004727spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004728{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004729#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004730 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004731 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004732#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004733
Rex Xu51596642016-09-21 18:56:12 +08004734 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004735 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004736 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4737
chaocf200da82016-12-20 12:44:35 -08004738 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4739 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004740 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4741 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004742 } else if (op == glslang::EOpAnyInvocation ||
4743 op == glslang::EOpAllInvocations ||
4744 op == glslang::EOpAllInvocationsEqual) {
4745 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4746 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004747 } else {
4748 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004749#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004750 if (op == glslang::EOpMinInvocationsNonUniform ||
4751 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004752 op == glslang::EOpAddInvocationsNonUniform ||
4753 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4754 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4755 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4756 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4757 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4758 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004759 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004760#endif
Rex Xu51596642016-09-21 18:56:12 +08004761
4762 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004763#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004764 switch (op) {
4765 case glslang::EOpMinInvocations:
4766 case glslang::EOpMaxInvocations:
4767 case glslang::EOpAddInvocations:
4768 case glslang::EOpMinInvocationsNonUniform:
4769 case glslang::EOpMaxInvocationsNonUniform:
4770 case glslang::EOpAddInvocationsNonUniform:
4771 groupOperation = spv::GroupOperationReduce;
4772 spvGroupOperands.push_back(groupOperation);
4773 break;
4774 case glslang::EOpMinInvocationsInclusiveScan:
4775 case glslang::EOpMaxInvocationsInclusiveScan:
4776 case glslang::EOpAddInvocationsInclusiveScan:
4777 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4778 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4779 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4780 groupOperation = spv::GroupOperationInclusiveScan;
4781 spvGroupOperands.push_back(groupOperation);
4782 break;
4783 case glslang::EOpMinInvocationsExclusiveScan:
4784 case glslang::EOpMaxInvocationsExclusiveScan:
4785 case glslang::EOpAddInvocationsExclusiveScan:
4786 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4787 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4788 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4789 groupOperation = spv::GroupOperationExclusiveScan;
4790 spvGroupOperands.push_back(groupOperation);
4791 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004792 default:
4793 break;
Rex Xu430ef402016-10-14 17:22:23 +08004794 }
Rex Xu9d93a232016-05-05 12:30:44 +08004795#endif
Rex Xu51596642016-09-21 18:56:12 +08004796 }
4797
4798 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4799 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004800
4801 switch (op) {
4802 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004803 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004804 break;
John Kessenich91cef522016-05-05 16:45:40 -06004805 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004806 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004807 break;
John Kessenich91cef522016-05-05 16:45:40 -06004808 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004809 opCode = spv::OpSubgroupAllEqualKHR;
4810 break;
Rex Xu51596642016-09-21 18:56:12 +08004811 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004812 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004813 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004814 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004815 break;
4816 case glslang::EOpReadFirstInvocation:
4817 opCode = spv::OpSubgroupFirstInvocationKHR;
4818 break;
4819 case glslang::EOpBallot:
4820 {
4821 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4822 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4823 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4824 //
4825 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4826 //
4827 spv::Id uintType = builder.makeUintType(32);
4828 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4829 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4830
4831 std::vector<spv::Id> components;
4832 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4833 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4834
4835 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4836 return builder.createUnaryOp(spv::OpBitcast, typeId,
4837 builder.createCompositeConstruct(uvec2Type, components));
4838 }
4839
Rex Xu9d93a232016-05-05 12:30:44 +08004840#ifdef AMD_EXTENSIONS
4841 case glslang::EOpMinInvocations:
4842 case glslang::EOpMaxInvocations:
4843 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004844 case glslang::EOpMinInvocationsInclusiveScan:
4845 case glslang::EOpMaxInvocationsInclusiveScan:
4846 case glslang::EOpAddInvocationsInclusiveScan:
4847 case glslang::EOpMinInvocationsExclusiveScan:
4848 case glslang::EOpMaxInvocationsExclusiveScan:
4849 case glslang::EOpAddInvocationsExclusiveScan:
4850 if (op == glslang::EOpMinInvocations ||
4851 op == glslang::EOpMinInvocationsInclusiveScan ||
4852 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004853 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004854 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004855 else {
4856 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004857 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004858 else
Rex Xu51596642016-09-21 18:56:12 +08004859 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004860 }
Rex Xu430ef402016-10-14 17:22:23 +08004861 } else if (op == glslang::EOpMaxInvocations ||
4862 op == glslang::EOpMaxInvocationsInclusiveScan ||
4863 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004864 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004865 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004866 else {
4867 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004868 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004869 else
Rex Xu51596642016-09-21 18:56:12 +08004870 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004871 }
4872 } else {
4873 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004874 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004875 else
Rex Xu51596642016-09-21 18:56:12 +08004876 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004877 }
4878
Rex Xu2bbbe062016-08-23 15:41:05 +08004879 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004880 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004881
4882 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004883 case glslang::EOpMinInvocationsNonUniform:
4884 case glslang::EOpMaxInvocationsNonUniform:
4885 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004886 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4887 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4888 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4889 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4890 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4891 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4892 if (op == glslang::EOpMinInvocationsNonUniform ||
4893 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4894 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004895 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004896 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004897 else {
4898 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004899 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004900 else
Rex Xu51596642016-09-21 18:56:12 +08004901 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004902 }
4903 }
Rex Xu430ef402016-10-14 17:22:23 +08004904 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4905 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4906 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004907 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004908 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004909 else {
4910 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004911 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004912 else
Rex Xu51596642016-09-21 18:56:12 +08004913 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004914 }
4915 }
4916 else {
4917 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004918 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004919 else
Rex Xu51596642016-09-21 18:56:12 +08004920 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004921 }
4922
Rex Xu2bbbe062016-08-23 15:41:05 +08004923 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004924 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004925
4926 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004927#endif
John Kessenich91cef522016-05-05 16:45:40 -06004928 default:
4929 logger->missingFunctionality("invocation operation");
4930 return spv::NoResult;
4931 }
Rex Xu51596642016-09-21 18:56:12 +08004932
4933 assert(opCode != spv::OpNop);
4934 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004935}
4936
Rex Xu2bbbe062016-08-23 15:41:05 +08004937// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004938spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004939{
Rex Xub7072052016-09-26 15:53:40 +08004940#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004941 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4942 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004943 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004944 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004945 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4946 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4947 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004948#else
4949 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4950 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004951 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4952 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004953#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004954
4955 // Handle group invocation operations scalar by scalar.
4956 // The result type is the same type as the original type.
4957 // The algorithm is to:
4958 // - break the vector into scalars
4959 // - apply the operation to each scalar
4960 // - make a vector out the scalar results
4961
4962 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004963 int numComponents = builder.getNumComponents(operands[0]);
4964 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004965 std::vector<spv::Id> results;
4966
4967 // do each scalar op
4968 for (int comp = 0; comp < numComponents; ++comp) {
4969 std::vector<unsigned int> indexes;
4970 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004971 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004972 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004973 if (op == spv::OpSubgroupReadInvocationKHR) {
4974 spvGroupOperands.push_back(scalar);
4975 spvGroupOperands.push_back(operands[1]);
4976 } else if (op == spv::OpGroupBroadcast) {
4977 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004978 spvGroupOperands.push_back(scalar);
4979 spvGroupOperands.push_back(operands[1]);
4980 } else {
chaocf200da82016-12-20 12:44:35 -08004981 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004982 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004983 spvGroupOperands.push_back(scalar);
4984 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004985
Rex Xub7072052016-09-26 15:53:40 +08004986 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004987 }
4988
4989 // put the pieces together
4990 return builder.createCompositeConstruct(typeId, results);
4991}
Rex Xu2bbbe062016-08-23 15:41:05 +08004992
John Kessenich5e4b1242015-08-06 22:53:06 -06004993spv::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 -06004994{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004995#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004996 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004997 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4998#else
Rex Xucabbb782017-03-24 13:41:14 +08004999 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005000 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005001#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005002
John Kessenich140f3df2015-06-26 16:58:36 -06005003 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005004 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005005 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005006 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005007 spv::Id typeId0 = 0;
5008 if (consumedOperands > 0)
5009 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005010 spv::Id typeId1 = 0;
5011 if (consumedOperands > 1)
5012 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005013 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005014
5015 switch (op) {
5016 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005017 if (isFloat)
5018 libCall = spv::GLSLstd450FMin;
5019 else if (isUnsigned)
5020 libCall = spv::GLSLstd450UMin;
5021 else
5022 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005023 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005024 break;
5025 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005026 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005027 break;
5028 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005029 if (isFloat)
5030 libCall = spv::GLSLstd450FMax;
5031 else if (isUnsigned)
5032 libCall = spv::GLSLstd450UMax;
5033 else
5034 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005035 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005036 break;
5037 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005038 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005039 break;
5040 case glslang::EOpDot:
5041 opCode = spv::OpDot;
5042 break;
5043 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005044 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005045 break;
5046
5047 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005048 if (isFloat)
5049 libCall = spv::GLSLstd450FClamp;
5050 else if (isUnsigned)
5051 libCall = spv::GLSLstd450UClamp;
5052 else
5053 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005054 builder.promoteScalar(precision, operands.front(), operands[1]);
5055 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005056 break;
5057 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005058 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5059 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005060 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005061 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005062 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005063 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005064 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005065 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005066 break;
5067 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005068 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005069 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005070 break;
5071 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005072 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005073 builder.promoteScalar(precision, operands[0], operands[2]);
5074 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005075 break;
5076
5077 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005078 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005079 break;
5080 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005081 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005082 break;
5083 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005084 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005085 break;
5086 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005087 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005088 break;
5089 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005090 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005091 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005092 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005093 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005094 libCall = spv::GLSLstd450InterpolateAtSample;
5095 break;
5096 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005097 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005098 libCall = spv::GLSLstd450InterpolateAtOffset;
5099 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005100 case glslang::EOpAddCarry:
5101 opCode = spv::OpIAddCarry;
5102 typeId = builder.makeStructResultType(typeId0, typeId0);
5103 consumedOperands = 2;
5104 break;
5105 case glslang::EOpSubBorrow:
5106 opCode = spv::OpISubBorrow;
5107 typeId = builder.makeStructResultType(typeId0, typeId0);
5108 consumedOperands = 2;
5109 break;
5110 case glslang::EOpUMulExtended:
5111 opCode = spv::OpUMulExtended;
5112 typeId = builder.makeStructResultType(typeId0, typeId0);
5113 consumedOperands = 2;
5114 break;
5115 case glslang::EOpIMulExtended:
5116 opCode = spv::OpSMulExtended;
5117 typeId = builder.makeStructResultType(typeId0, typeId0);
5118 consumedOperands = 2;
5119 break;
5120 case glslang::EOpBitfieldExtract:
5121 if (isUnsigned)
5122 opCode = spv::OpBitFieldUExtract;
5123 else
5124 opCode = spv::OpBitFieldSExtract;
5125 break;
5126 case glslang::EOpBitfieldInsert:
5127 opCode = spv::OpBitFieldInsert;
5128 break;
5129
5130 case glslang::EOpFma:
5131 libCall = spv::GLSLstd450Fma;
5132 break;
5133 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005134 {
5135 libCall = spv::GLSLstd450FrexpStruct;
5136 assert(builder.isPointerType(typeId1));
5137 typeId1 = builder.getContainedTypeId(typeId1);
5138#ifdef AMD_EXTENSIONS
5139 int width = builder.getScalarTypeWidth(typeId1);
5140#else
5141 int width = 32;
5142#endif
5143 if (builder.getNumComponents(operands[0]) == 1)
5144 frexpIntType = builder.makeIntegerType(width, true);
5145 else
5146 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5147 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5148 consumedOperands = 1;
5149 }
John Kessenich55e7d112015-11-15 21:33:39 -07005150 break;
5151 case glslang::EOpLdexp:
5152 libCall = spv::GLSLstd450Ldexp;
5153 break;
5154
Rex Xu574ab042016-04-14 16:53:07 +08005155 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005156 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005157
Rex Xu9d93a232016-05-05 12:30:44 +08005158#ifdef AMD_EXTENSIONS
5159 case glslang::EOpSwizzleInvocations:
5160 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5161 libCall = spv::SwizzleInvocationsAMD;
5162 break;
5163 case glslang::EOpSwizzleInvocationsMasked:
5164 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5165 libCall = spv::SwizzleInvocationsMaskedAMD;
5166 break;
5167 case glslang::EOpWriteInvocation:
5168 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5169 libCall = spv::WriteInvocationAMD;
5170 break;
5171
5172 case glslang::EOpMin3:
5173 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5174 if (isFloat)
5175 libCall = spv::FMin3AMD;
5176 else {
5177 if (isUnsigned)
5178 libCall = spv::UMin3AMD;
5179 else
5180 libCall = spv::SMin3AMD;
5181 }
5182 break;
5183 case glslang::EOpMax3:
5184 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5185 if (isFloat)
5186 libCall = spv::FMax3AMD;
5187 else {
5188 if (isUnsigned)
5189 libCall = spv::UMax3AMD;
5190 else
5191 libCall = spv::SMax3AMD;
5192 }
5193 break;
5194 case glslang::EOpMid3:
5195 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5196 if (isFloat)
5197 libCall = spv::FMid3AMD;
5198 else {
5199 if (isUnsigned)
5200 libCall = spv::UMid3AMD;
5201 else
5202 libCall = spv::SMid3AMD;
5203 }
5204 break;
5205
5206 case glslang::EOpInterpolateAtVertex:
5207 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5208 libCall = spv::InterpolateAtVertexAMD;
5209 break;
5210#endif
5211
John Kessenich140f3df2015-06-26 16:58:36 -06005212 default:
5213 return 0;
5214 }
5215
5216 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005217 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005218 // Use an extended instruction from the standard library.
5219 // Construct the call arguments, without modifying the original operands vector.
5220 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5221 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005222 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005223 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005224 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005225 case 0:
5226 // should all be handled by visitAggregate and createNoArgOperation
5227 assert(0);
5228 return 0;
5229 case 1:
5230 // should all be handled by createUnaryOperation
5231 assert(0);
5232 return 0;
5233 case 2:
5234 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5235 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005236 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005237 // anything 3 or over doesn't have l-value operands, so all should be consumed
5238 assert(consumedOperands == operands.size());
5239 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005240 break;
5241 }
5242 }
5243
John Kessenich55e7d112015-11-15 21:33:39 -07005244 // Decode the return types that were structures
5245 switch (op) {
5246 case glslang::EOpAddCarry:
5247 case glslang::EOpSubBorrow:
5248 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5249 id = builder.createCompositeExtract(id, typeId0, 0);
5250 break;
5251 case glslang::EOpUMulExtended:
5252 case glslang::EOpIMulExtended:
5253 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5254 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5255 break;
5256 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005257 {
5258 assert(operands.size() == 2);
5259 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5260 // "exp" is floating-point type (from HLSL intrinsic)
5261 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5262 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5263 builder.createStore(member1, operands[1]);
5264 } else
5265 // "exp" is integer type (from GLSL built-in function)
5266 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5267 id = builder.createCompositeExtract(id, typeId0, 0);
5268 }
John Kessenich55e7d112015-11-15 21:33:39 -07005269 break;
5270 default:
5271 break;
5272 }
5273
John Kessenich32cfd492016-02-02 12:37:46 -07005274 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005275}
5276
Rex Xu9d93a232016-05-05 12:30:44 +08005277// Intrinsics with no arguments (or no return value, and no precision).
5278spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005279{
5280 // TODO: get the barrier operands correct
5281
5282 switch (op) {
5283 case glslang::EOpEmitVertex:
5284 builder.createNoResultOp(spv::OpEmitVertex);
5285 return 0;
5286 case glslang::EOpEndPrimitive:
5287 builder.createNoResultOp(spv::OpEndPrimitive);
5288 return 0;
5289 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005290 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005291 return 0;
5292 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005293 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005294 return 0;
5295 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005296 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005297 return 0;
5298 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005299 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005300 return 0;
5301 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005302 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005303 return 0;
5304 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005305 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005306 return 0;
5307 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005308 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005309 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005310 case glslang::EOpAllMemoryBarrierWithGroupSync:
5311 // Control barrier with non-"None" semantic is also a memory barrier.
5312 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5313 return 0;
5314 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5315 // Control barrier with non-"None" semantic is also a memory barrier.
5316 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5317 return 0;
5318 case glslang::EOpWorkgroupMemoryBarrier:
5319 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5320 return 0;
5321 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5322 // Control barrier with non-"None" semantic is also a memory barrier.
5323 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5324 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005325#ifdef AMD_EXTENSIONS
5326 case glslang::EOpTime:
5327 {
5328 std::vector<spv::Id> args; // Dummy arguments
5329 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5330 return builder.setPrecision(id, precision);
5331 }
5332#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005333 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005334 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005335 return 0;
5336 }
5337}
5338
5339spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5340{
John Kessenich2f273362015-07-18 22:34:27 -06005341 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005342 spv::Id id;
5343 if (symbolValues.end() != iter) {
5344 id = iter->second;
5345 return id;
5346 }
5347
5348 // it was not found, create it
5349 id = createSpvVariable(symbol);
5350 symbolValues[symbol->getId()] = id;
5351
Rex Xuc884b4a2016-06-29 15:03:44 +08005352 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005353 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005354 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005355 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005356 if (symbol->getType().getQualifier().hasSpecConstantId())
5357 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005358 if (symbol->getQualifier().hasIndex())
5359 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5360 if (symbol->getQualifier().hasComponent())
5361 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5362 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005363 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005364 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005365 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005366 if (symbol->getQualifier().hasXfbBuffer())
5367 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5368 if (symbol->getQualifier().hasXfbOffset())
5369 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5370 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005371 // atomic counters use this:
5372 if (symbol->getQualifier().hasOffset())
5373 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005374 }
5375
scygan2c864272016-05-18 18:09:17 +02005376 if (symbol->getQualifier().hasLocation())
5377 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005378 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005379 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005380 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005381 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005382 }
John Kessenich140f3df2015-06-26 16:58:36 -06005383 if (symbol->getQualifier().hasSet())
5384 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005385 else if (IsDescriptorResource(symbol->getType())) {
5386 // default to 0
5387 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5388 }
John Kessenich140f3df2015-06-26 16:58:36 -06005389 if (symbol->getQualifier().hasBinding())
5390 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005391 if (symbol->getQualifier().hasAttachment())
5392 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005393 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005394 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005395 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005396 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005397 if (symbol->getQualifier().hasXfbBuffer())
5398 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5399 }
5400
Rex Xu1da878f2016-02-21 20:59:01 +08005401 if (symbol->getType().isImage()) {
5402 std::vector<spv::Decoration> memory;
5403 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5404 for (unsigned int i = 0; i < memory.size(); ++i)
5405 addDecoration(id, memory[i]);
5406 }
5407
John Kessenich140f3df2015-06-26 16:58:36 -06005408 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005409 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005410 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005411 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005412
John Kessenichecba76f2017-01-06 00:34:48 -07005413#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005414 if (builtIn == spv::BuiltInSampleMask) {
5415 spv::Decoration decoration;
5416 // GL_NV_sample_mask_override_coverage extension
5417 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005418 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005419 else
5420 decoration = (spv::Decoration)spv::DecorationMax;
5421 addDecoration(id, decoration);
5422 if (decoration != spv::DecorationMax) {
5423 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5424 }
5425 }
chaoc771d89f2017-01-13 01:10:53 -08005426 else if (builtIn == spv::BuiltInLayer) {
5427 // SPV_NV_viewport_array2 extension
5428 if (symbol->getQualifier().layoutViewportRelative)
5429 {
5430 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5431 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5432 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5433 }
5434 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5435 {
5436 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5437 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5438 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5439 }
5440 }
5441
chaoc6e5acae2016-12-20 13:28:52 -08005442 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005443 addDecoration(id, spv::DecorationPassthroughNV);
5444 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005445 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5446 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005447#endif
5448
John Kessenich140f3df2015-06-26 16:58:36 -06005449 return id;
5450}
5451
John Kessenich55e7d112015-11-15 21:33:39 -07005452// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005453void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5454{
John Kessenich4016e382016-07-15 11:53:56 -06005455 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005456 builder.addDecoration(id, dec);
5457}
5458
John Kessenich55e7d112015-11-15 21:33:39 -07005459// If 'dec' is valid, add a one-operand decoration to an object
5460void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5461{
John Kessenich4016e382016-07-15 11:53:56 -06005462 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005463 builder.addDecoration(id, dec, value);
5464}
5465
5466// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005467void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5468{
John Kessenich4016e382016-07-15 11:53:56 -06005469 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005470 builder.addMemberDecoration(id, (unsigned)member, dec);
5471}
5472
John Kessenich92187592016-02-01 13:45:25 -07005473// If 'dec' is valid, add a one-operand decoration to a struct member
5474void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5475{
John Kessenich4016e382016-07-15 11:53:56 -06005476 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005477 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5478}
5479
John Kessenich55e7d112015-11-15 21:33:39 -07005480// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005481// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005482//
5483// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5484//
5485// Recursively walk the nodes. The nodes form a tree whose leaves are
5486// regular constants, which themselves are trees that createSpvConstant()
5487// recursively walks. So, this function walks the "top" of the tree:
5488// - emit specialization constant-building instructions for specConstant
5489// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005490spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005491{
John Kessenich7cc0e282016-03-20 00:46:02 -06005492 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005493
qining4f4bb812016-04-03 23:55:17 -04005494 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005495 if (! node.getQualifier().specConstant) {
5496 // hand off to the non-spec-constant path
5497 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5498 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005499 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005500 nextConst, false);
5501 }
5502
5503 // We now know we have a specialization constant to build
5504
John Kessenichd94c0032016-05-30 19:29:40 -06005505 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005506 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5507 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5508 std::vector<spv::Id> dimConstId;
5509 for (int dim = 0; dim < 3; ++dim) {
5510 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5511 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5512 if (specConst)
5513 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5514 }
5515 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5516 }
5517
5518 // An AST node labelled as specialization constant should be a symbol node.
5519 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5520 if (auto* sn = node.getAsSymbolNode()) {
5521 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005522 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5523 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5524 // will set the builder into spec constant op instruction generating mode.
5525 sub_tree->traverse(this);
5526 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005527 } else if (auto* const_union_array = &sn->getConstArray()){
5528 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005529 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5530 builder.addName(id, sn->getName().c_str());
5531 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005532 }
5533 }
qining4f4bb812016-04-03 23:55:17 -04005534
5535 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5536 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005537 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005538 exit(1);
5539 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005540}
5541
John Kessenich140f3df2015-06-26 16:58:36 -06005542// Use 'consts' as the flattened glslang source of scalar constants to recursively
5543// build the aggregate SPIR-V constant.
5544//
5545// If there are not enough elements present in 'consts', 0 will be substituted;
5546// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5547//
qining08408382016-03-21 09:51:37 -04005548spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005549{
5550 // vector of constants for SPIR-V
5551 std::vector<spv::Id> spvConsts;
5552
5553 // Type is used for struct and array constants
5554 spv::Id typeId = convertGlslangToSpvType(glslangType);
5555
5556 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005557 glslang::TType elementType(glslangType, 0);
5558 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005559 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005560 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005561 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005562 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005563 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005564 } else if (glslangType.getStruct()) {
5565 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5566 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005567 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005568 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005569 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5570 bool zero = nextConst >= consts.size();
5571 switch (glslangType.getBasicType()) {
5572 case glslang::EbtInt:
5573 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5574 break;
5575 case glslang::EbtUint:
5576 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5577 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005578 case glslang::EbtInt64:
5579 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5580 break;
5581 case glslang::EbtUint64:
5582 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5583 break;
Rex Xucabbb782017-03-24 13:41:14 +08005584#ifdef AMD_EXTENSIONS
5585 case glslang::EbtInt16:
5586 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5587 break;
5588 case glslang::EbtUint16:
5589 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5590 break;
5591#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005592 case glslang::EbtFloat:
5593 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5594 break;
5595 case glslang::EbtDouble:
5596 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5597 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005598#ifdef AMD_EXTENSIONS
5599 case glslang::EbtFloat16:
5600 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5601 break;
5602#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005603 case glslang::EbtBool:
5604 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5605 break;
5606 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005607 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005608 break;
5609 }
5610 ++nextConst;
5611 }
5612 } else {
5613 // we have a non-aggregate (scalar) constant
5614 bool zero = nextConst >= consts.size();
5615 spv::Id scalar = 0;
5616 switch (glslangType.getBasicType()) {
5617 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005618 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005619 break;
5620 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005621 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005622 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005623 case glslang::EbtInt64:
5624 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5625 break;
5626 case glslang::EbtUint64:
5627 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5628 break;
Rex Xucabbb782017-03-24 13:41:14 +08005629#ifdef AMD_EXTENSIONS
5630 case glslang::EbtInt16:
5631 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5632 break;
5633 case glslang::EbtUint16:
5634 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5635 break;
5636#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005637 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005638 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005639 break;
5640 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005641 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005642 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005643#ifdef AMD_EXTENSIONS
5644 case glslang::EbtFloat16:
5645 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5646 break;
5647#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005648 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005649 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005650 break;
5651 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005652 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005653 break;
5654 }
5655 ++nextConst;
5656 return scalar;
5657 }
5658
5659 return builder.makeCompositeConstant(typeId, spvConsts);
5660}
5661
John Kessenich7c1aa102015-10-15 13:29:11 -06005662// Return true if the node is a constant or symbol whose reading has no
5663// non-trivial observable cost or effect.
5664bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5665{
5666 // don't know what this is
5667 if (node == nullptr)
5668 return false;
5669
5670 // a constant is safe
5671 if (node->getAsConstantUnion() != nullptr)
5672 return true;
5673
5674 // not a symbol means non-trivial
5675 if (node->getAsSymbolNode() == nullptr)
5676 return false;
5677
5678 // a symbol, depends on what's being read
5679 switch (node->getType().getQualifier().storage) {
5680 case glslang::EvqTemporary:
5681 case glslang::EvqGlobal:
5682 case glslang::EvqIn:
5683 case glslang::EvqInOut:
5684 case glslang::EvqConst:
5685 case glslang::EvqConstReadOnly:
5686 case glslang::EvqUniform:
5687 return true;
5688 default:
5689 return false;
5690 }
qining25262b32016-05-06 17:25:16 -04005691}
John Kessenich7c1aa102015-10-15 13:29:11 -06005692
5693// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005694// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005695// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005696// Return true if trivial.
5697bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5698{
5699 if (node == nullptr)
5700 return false;
5701
John Kessenich84cc15f2017-05-24 16:44:47 -06005702 // count non scalars as trivial, as well as anything coming from HLSL
5703 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005704 return true;
5705
John Kessenich7c1aa102015-10-15 13:29:11 -06005706 // symbols and constants are trivial
5707 if (isTrivialLeaf(node))
5708 return true;
5709
5710 // otherwise, it needs to be a simple operation or one or two leaf nodes
5711
5712 // not a simple operation
5713 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5714 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5715 if (binaryNode == nullptr && unaryNode == nullptr)
5716 return false;
5717
5718 // not on leaf nodes
5719 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5720 return false;
5721
5722 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5723 return false;
5724 }
5725
5726 switch (node->getAsOperator()->getOp()) {
5727 case glslang::EOpLogicalNot:
5728 case glslang::EOpConvIntToBool:
5729 case glslang::EOpConvUintToBool:
5730 case glslang::EOpConvFloatToBool:
5731 case glslang::EOpConvDoubleToBool:
5732 case glslang::EOpEqual:
5733 case glslang::EOpNotEqual:
5734 case glslang::EOpLessThan:
5735 case glslang::EOpGreaterThan:
5736 case glslang::EOpLessThanEqual:
5737 case glslang::EOpGreaterThanEqual:
5738 case glslang::EOpIndexDirect:
5739 case glslang::EOpIndexDirectStruct:
5740 case glslang::EOpLogicalXor:
5741 case glslang::EOpAny:
5742 case glslang::EOpAll:
5743 return true;
5744 default:
5745 return false;
5746 }
5747}
5748
5749// Emit short-circuiting code, where 'right' is never evaluated unless
5750// the left side is true (for &&) or false (for ||).
5751spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5752{
5753 spv::Id boolTypeId = builder.makeBoolType();
5754
5755 // emit left operand
5756 builder.clearAccessChain();
5757 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005758 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005759
5760 // Operands to accumulate OpPhi operands
5761 std::vector<spv::Id> phiOperands;
5762 // accumulate left operand's phi information
5763 phiOperands.push_back(leftId);
5764 phiOperands.push_back(builder.getBuildPoint()->getId());
5765
5766 // Make the two kinds of operation symmetric with a "!"
5767 // || => emit "if (! left) result = right"
5768 // && => emit "if ( left) result = right"
5769 //
5770 // TODO: this runtime "not" for || could be avoided by adding functionality
5771 // to 'builder' to have an "else" without an "then"
5772 if (op == glslang::EOpLogicalOr)
5773 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5774
5775 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005776 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005777
5778 // emit right operand as the "then" part of the "if"
5779 builder.clearAccessChain();
5780 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005781 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005782
5783 // accumulate left operand's phi information
5784 phiOperands.push_back(rightId);
5785 phiOperands.push_back(builder.getBuildPoint()->getId());
5786
5787 // finish the "if"
5788 ifBuilder.makeEndIf();
5789
5790 // phi together the two results
5791 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5792}
5793
Rex Xu9d93a232016-05-05 12:30:44 +08005794// Return type Id of the imported set of extended instructions corresponds to the name.
5795// Import this set if it has not been imported yet.
5796spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5797{
5798 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5799 return extBuiltinMap[name];
5800 else {
Rex Xu51596642016-09-21 18:56:12 +08005801 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005802 spv::Id extBuiltins = builder.import(name);
5803 extBuiltinMap[name] = extBuiltins;
5804 return extBuiltins;
5805 }
5806}
5807
John Kessenich140f3df2015-06-26 16:58:36 -06005808}; // end anonymous namespace
5809
5810namespace glslang {
5811
John Kessenich68d78fd2015-07-12 19:28:10 -06005812void GetSpirvVersion(std::string& version)
5813{
John Kessenich9e55f632015-07-15 10:03:39 -06005814 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005815 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005816 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005817 version = buf;
5818}
5819
John Kessenich140f3df2015-06-26 16:58:36 -06005820// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005821void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005822{
5823 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005824 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005825 if (out.fail())
5826 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005827 for (int i = 0; i < (int)spirv.size(); ++i) {
5828 unsigned int word = spirv[i];
5829 out.write((const char*)&word, 4);
5830 }
5831 out.close();
5832}
5833
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005834// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005835void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005836{
5837 std::ofstream out;
5838 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005839 if (out.fail())
5840 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005841 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005842 if (varName != nullptr) {
5843 out << "\t #pragma once" << std::endl;
5844 out << "const uint32_t " << varName << "[] = {" << std::endl;
5845 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005846 const int WORDS_PER_LINE = 8;
5847 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5848 out << "\t";
5849 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5850 const unsigned int word = spirv[i + j];
5851 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5852 if (i + j + 1 < (int)spirv.size()) {
5853 out << ",";
5854 }
5855 }
5856 out << std::endl;
5857 }
Flavio15017db2017-02-15 14:29:33 -08005858 if (varName != nullptr) {
5859 out << "};";
5860 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005861 out.close();
5862}
5863
John Kessenich140f3df2015-06-26 16:58:36 -06005864//
5865// Set up the glslang traversal
5866//
John Kessenich121853f2017-05-31 17:11:16 -06005867void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005868{
Lei Zhang17535f72016-05-04 15:55:59 -04005869 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005870 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005871}
5872
John Kessenich121853f2017-05-31 17:11:16 -06005873void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5874 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005875{
John Kessenich140f3df2015-06-26 16:58:36 -06005876 TIntermNode* root = intermediate.getTreeRoot();
5877
5878 if (root == 0)
5879 return;
5880
John Kessenich121853f2017-05-31 17:11:16 -06005881 glslang::SpvOptions defaultOptions;
5882 if (options == nullptr)
5883 options = &defaultOptions;
5884
John Kessenich140f3df2015-06-26 16:58:36 -06005885 glslang::GetThreadPoolAllocator().push();
5886
John Kessenich121853f2017-05-31 17:11:16 -06005887 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005888 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005889 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005890 it.dumpSpv(spirv);
5891
5892 glslang::GetThreadPoolAllocator().pop();
5893}
5894
5895}; // end namespace glslang