blob: bd2446307a0473990ddc9a015269b9635352f90a [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);
Rex Xu5e317ff2017-03-16 23:02:39 +0800458 if (glslangIntermediate->getStage() == EShLangVertex ||
459 glslangIntermediate->getStage() == EShLangTessControl ||
460 glslangIntermediate->getStage() == EShLangTessEvaluation) {
461
John Kessenichb41bff62017-08-11 13:07:17 -0600462 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
463 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800464 }
Rex Xu5e317ff2017-03-16 23:02:39 +0800465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 return spv::BuiltInViewportIndex;
467
John Kessenich5e801132016-02-15 11:09:46 -0700468 case glslang::EbvSampleId:
469 builder.addCapability(spv::CapabilitySampleRateShading);
470 return spv::BuiltInSampleId;
471
472 case glslang::EbvSamplePosition:
473 builder.addCapability(spv::CapabilitySampleRateShading);
474 return spv::BuiltInSamplePosition;
475
476 case glslang::EbvSampleMask:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleMask;
479
John Kessenich78a45572016-07-08 14:05:15 -0600480 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800481 if (!memberDeclaration) {
482 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800483 if (glslangIntermediate->getStage() == EShLangVertex ||
484 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800485 glslangIntermediate->getStage() == EShLangTessEvaluation) {
486
John Kessenichb41bff62017-08-11 13:07:17 -0600487 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
488 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
chaoc771d89f2017-01-13 01:10:53 -0800489 }
Rex Xu5e317ff2017-03-16 23:02:39 +0800490 }
491
John Kessenich78a45572016-07-08 14:05:15 -0600492 return spv::BuiltInLayer;
493
John Kessenich140f3df2015-06-26 16:58:36 -0600494 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvVertexId: return spv::BuiltInVertexId;
496 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700497 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
498 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800499
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800501 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
502 builder.addCapability(spv::CapabilityDrawParameters);
503 return spv::BuiltInBaseVertex;
504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200514
515 case glslang::EbvPrimitiveId:
516 if (glslangIntermediate->getStage() == EShLangFragment)
517 builder.addCapability(spv::CapabilityGeometry);
518 return spv::BuiltInPrimitiveId;
519
Rex Xu37cdcee2017-06-29 17:46:34 +0800520 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800521 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
522 builder.addCapability(spv::CapabilityStencilExportEXT);
523 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
527 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
528 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
529 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
530 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
531 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
532 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600533 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
534 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
535 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
536 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
537 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
538 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
539 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
540 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800541
Rex Xu574ab042016-04-14 16:53:07 +0800542 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800544 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
545 return spv::BuiltInSubgroupSize;
546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupLocalInvocationId;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupEqMaskKHR;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupGeMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGtMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupLeMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLtMaskKHR;
576
Rex Xu9d93a232016-05-05 12:30:44 +0800577#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800578 case glslang::EbvBaryCoordNoPersp:
579 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
580 return spv::BuiltInBaryCoordNoPerspAMD;
581
582 case glslang::EbvBaryCoordNoPerspCentroid:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
585
586 case glslang::EbvBaryCoordNoPerspSample:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspSampleAMD;
589
590 case glslang::EbvBaryCoordSmooth:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordSmoothAMD;
593
594 case glslang::EbvBaryCoordSmoothCentroid:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothCentroidAMD;
597
598 case glslang::EbvBaryCoordSmoothSample:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothSampleAMD;
601
602 case glslang::EbvBaryCoordPullModel:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800605#endif
chaoc771d89f2017-01-13 01:10:53 -0800606
John Kessenich6c8aaac2017-02-27 01:20:51 -0700607 case glslang::EbvDeviceIndex:
608 builder.addExtension(spv::E_SPV_KHR_device_group);
609 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700610 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700611
612 case glslang::EbvViewIndex:
613 builder.addExtension(spv::E_SPV_KHR_multiview);
614 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700615 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700616
chaoc771d89f2017-01-13 01:10:53 -0800617#ifdef NV_EXTENSIONS
618 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800619 if (!memberDeclaration) {
620 builder.addExtension(spv::E_SPV_NV_viewport_array2);
621 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
622 }
chaoc771d89f2017-01-13 01:10:53 -0800623 return spv::BuiltInViewportMaskNV;
624 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800625 if (!memberDeclaration) {
626 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
627 builder.addCapability(spv::CapabilityShaderStereoViewNV);
628 }
chaoc771d89f2017-01-13 01:10:53 -0800629 return spv::BuiltInSecondaryPositionNV;
630 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800631 if (!memberDeclaration) {
632 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
633 builder.addCapability(spv::CapabilityShaderStereoViewNV);
634 }
chaoc771d89f2017-01-13 01:10:53 -0800635 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800636 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800637 if (!memberDeclaration) {
638 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
639 builder.addCapability(spv::CapabilityPerViewAttributesNV);
640 }
chaocdf3956c2017-02-14 14:52:34 -0800641 return spv::BuiltInPositionPerViewNV;
642 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800643 if (!memberDeclaration) {
644 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
645 builder.addCapability(spv::CapabilityPerViewAttributesNV);
646 }
chaocdf3956c2017-02-14 14:52:34 -0800647 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800648#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800649 default:
650 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600651 }
652}
653
Rex Xufc618912015-09-09 16:42:49 +0800654// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700655spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800656{
657 assert(type.getBasicType() == glslang::EbtSampler);
658
John Kessenich5d0fa972016-02-15 11:57:00 -0700659 // Check for capabilities
660 switch (type.getQualifier().layoutFormat) {
661 case glslang::ElfRg32f:
662 case glslang::ElfRg16f:
663 case glslang::ElfR11fG11fB10f:
664 case glslang::ElfR16f:
665 case glslang::ElfRgba16:
666 case glslang::ElfRgb10A2:
667 case glslang::ElfRg16:
668 case glslang::ElfRg8:
669 case glslang::ElfR16:
670 case glslang::ElfR8:
671 case glslang::ElfRgba16Snorm:
672 case glslang::ElfRg16Snorm:
673 case glslang::ElfRg8Snorm:
674 case glslang::ElfR16Snorm:
675 case glslang::ElfR8Snorm:
676
677 case glslang::ElfRg32i:
678 case glslang::ElfRg16i:
679 case glslang::ElfRg8i:
680 case glslang::ElfR16i:
681 case glslang::ElfR8i:
682
683 case glslang::ElfRgb10a2ui:
684 case glslang::ElfRg32ui:
685 case glslang::ElfRg16ui:
686 case glslang::ElfRg8ui:
687 case glslang::ElfR16ui:
688 case glslang::ElfR8ui:
689 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
690 break;
691
692 default:
693 break;
694 }
695
696 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800697 switch (type.getQualifier().layoutFormat) {
698 case glslang::ElfNone: return spv::ImageFormatUnknown;
699 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
700 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
701 case glslang::ElfR32f: return spv::ImageFormatR32f;
702 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
703 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
704 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
705 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
706 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
707 case glslang::ElfR16f: return spv::ImageFormatR16f;
708 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
709 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
710 case glslang::ElfRg16: return spv::ImageFormatRg16;
711 case glslang::ElfRg8: return spv::ImageFormatRg8;
712 case glslang::ElfR16: return spv::ImageFormatR16;
713 case glslang::ElfR8: return spv::ImageFormatR8;
714 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
715 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
716 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
717 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
718 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
719 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
720 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
721 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
722 case glslang::ElfR32i: return spv::ImageFormatR32i;
723 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
724 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
725 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
726 case glslang::ElfR16i: return spv::ImageFormatR16i;
727 case glslang::ElfR8i: return spv::ImageFormatR8i;
728 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
729 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
730 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
731 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
732 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
733 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
734 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
735 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
736 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
737 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600738 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800739 }
740}
741
Rex Xu57e65922017-07-04 23:23:40 +0800742spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
743{
744 switch (selectionControl) {
745 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
746 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
747 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
748 default: return spv::SelectionControlMaskNone;
749 }
750}
751
steve-lunargf1709e72017-05-02 20:14:50 -0600752spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
753{
754 switch (loopControl) {
755 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
756 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
757 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
758 // TODO: DependencyInfinite
759 // TODO: DependencyLength
760 default: return spv::LoopControlMaskNone;
761 }
762}
763
John Kessenicha5c5fb62017-05-05 05:09:58 -0600764// Translate glslang type to SPIR-V storage class.
765spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
766{
767 if (type.getQualifier().isPipeInput())
768 return spv::StorageClassInput;
769 else if (type.getQualifier().isPipeOutput())
770 return spv::StorageClassOutput;
771 else if (type.getBasicType() == glslang::EbtAtomicUint)
772 return spv::StorageClassAtomicCounter;
773 else if (type.containsOpaque())
774 return spv::StorageClassUniformConstant;
775 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
776 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
777 return spv::StorageClassStorageBuffer;
778 } else if (type.getQualifier().isUniformOrBuffer()) {
779 if (type.getQualifier().layoutPushConstant)
780 return spv::StorageClassPushConstant;
781 if (type.getBasicType() == glslang::EbtBlock)
782 return spv::StorageClassUniform;
783 else
784 return spv::StorageClassUniformConstant;
785 } else {
786 switch (type.getQualifier().storage) {
787 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
788 case glslang::EvqGlobal: return spv::StorageClassPrivate;
789 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
790 case glslang::EvqTemporary: return spv::StorageClassFunction;
791 default:
792 assert(0);
793 return spv::StorageClassFunction;
794 }
795 }
796}
797
qining25262b32016-05-06 17:25:16 -0400798// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700799// descriptor set.
800bool IsDescriptorResource(const glslang::TType& type)
801{
John Kessenichf7497e22016-03-08 21:36:22 -0700802 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700803 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700804 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700805
806 // non block...
807 // basically samplerXXX/subpass/sampler/texture are all included
808 // if they are the global-scope-class, not the function parameter
809 // (or local, if they ever exist) class.
810 if (type.getBasicType() == glslang::EbtSampler)
811 return type.getQualifier().isUniformOrBuffer();
812
813 // None of the above.
814 return false;
815}
816
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
818{
819 if (child.layoutMatrix == glslang::ElmNone)
820 child.layoutMatrix = parent.layoutMatrix;
821
822 if (parent.invariant)
823 child.invariant = true;
824 if (parent.nopersp)
825 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800826#ifdef AMD_EXTENSIONS
827 if (parent.explicitInterp)
828 child.explicitInterp = true;
829#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700830 if (parent.flat)
831 child.flat = true;
832 if (parent.centroid)
833 child.centroid = true;
834 if (parent.patch)
835 child.patch = true;
836 if (parent.sample)
837 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800838 if (parent.coherent)
839 child.coherent = true;
840 if (parent.volatil)
841 child.volatil = true;
842 if (parent.restrict)
843 child.restrict = true;
844 if (parent.readonly)
845 child.readonly = true;
846 if (parent.writeonly)
847 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700848}
849
John Kessenichf2b7f332016-09-01 17:05:23 -0600850bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851{
John Kessenich7b9fa252016-01-21 18:56:57 -0700852 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600853 // - struct members might inherit from a struct declaration
854 // (note that non-block structs don't explicitly inherit,
855 // only implicitly, meaning no decoration involved)
856 // - affect decorations on the struct members
857 // (note smooth does not, and expecting something like volatile
858 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700859 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600860 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700861}
862
John Kessenich140f3df2015-06-26 16:58:36 -0600863//
864// Implement the TGlslangToSpvTraverser class.
865//
866
John Kessenich121853f2017-05-31 17:11:16 -0600867TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
868 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
869 : TIntermTraverser(true, false, true),
870 options(options),
871 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600872 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400873 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700874 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600875 glslangIntermediate(glslangIntermediate)
876{
877 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
878
879 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600880 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
881 glslangIntermediate->getVersion());
882
John Kessenich121853f2017-05-31 17:11:16 -0600883 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600884 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600885 builder.setSourceFile(glslangIntermediate->getSourceFile());
886
887 // Set the source shader's text. If for SPV version 1.0, include
888 // a preamble in comments stating the OpModuleProcessed instructions.
889 // Otherwise, emit those as actual instructions.
890 std::string text;
891 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
892 for (int p = 0; p < (int)processes.size(); ++p) {
893 if (glslangIntermediate->getSpv().spv < 0x00010100) {
894 text.append("// OpModuleProcessed ");
895 text.append(processes[p]);
896 text.append("\n");
897 } else
898 builder.addModuleProcessed(processes[p]);
899 }
900 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
901 text.append("#line 1\n");
902 text.append(glslangIntermediate->getSourceText());
903 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600904 }
John Kessenich140f3df2015-06-26 16:58:36 -0600905 stdBuiltins = builder.import("GLSL.std.450");
906 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600907 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
908 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600909
910 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600911 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
912 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600913 builder.addSourceExtension(it->c_str());
914
915 // Add the top-level modes for this shader.
916
John Kessenich92187592016-02-01 13:45:25 -0700917 if (glslangIntermediate->getXfbMode()) {
918 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600919 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700920 }
John Kessenich140f3df2015-06-26 16:58:36 -0600921
922 unsigned int mode;
923 switch (glslangIntermediate->getStage()) {
924 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600925 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600926 break;
927
steve-lunarge7412492017-03-23 11:56:07 -0600928 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600929 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600930 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600931
steve-lunarge7412492017-03-23 11:56:07 -0600932 glslang::TLayoutGeometry primitive;
933
934 if (glslangIntermediate->getStage() == EShLangTessControl) {
935 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
936 primitive = glslangIntermediate->getOutputPrimitive();
937 } else {
938 primitive = glslangIntermediate->getInputPrimitive();
939 }
940
941 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700942 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
943 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
944 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600945 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600946 }
John Kessenich4016e382016-07-15 11:53:56 -0600947 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600948 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
949
John Kesseniche6903322015-10-13 16:29:02 -0600950 switch (glslangIntermediate->getVertexSpacing()) {
951 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
952 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
953 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600954 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600955 }
John Kessenich4016e382016-07-15 11:53:56 -0600956 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600957 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
958
959 switch (glslangIntermediate->getVertexOrder()) {
960 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
961 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600962 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600963 }
John Kessenich4016e382016-07-15 11:53:56 -0600964 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600965 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
966
967 if (glslangIntermediate->getPointMode())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600969 break;
970
971 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600972 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600973 switch (glslangIntermediate->getInputPrimitive()) {
974 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
975 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
976 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700977 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600978 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600979 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600980 }
John Kessenich4016e382016-07-15 11:53:56 -0600981 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600982 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600983
John Kessenich140f3df2015-06-26 16:58:36 -0600984 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
985
986 switch (glslangIntermediate->getOutputPrimitive()) {
987 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
988 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
989 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600990 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600991 }
John Kessenich4016e382016-07-15 11:53:56 -0600992 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600993 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
994 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
995 break;
996
997 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600998 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600999 if (glslangIntermediate->getPixelCenterInteger())
1000 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001001
John Kessenich140f3df2015-06-26 16:58:36 -06001002 if (glslangIntermediate->getOriginUpperLeft())
1003 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001004 else
1005 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001006
1007 if (glslangIntermediate->getEarlyFragmentTests())
1008 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1009
chaocc1204522017-06-30 17:14:30 -07001010 if (glslangIntermediate->getPostDepthCoverage()) {
1011 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1012 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1013 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1014 }
1015
John Kesseniche6903322015-10-13 16:29:02 -06001016 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001017 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1018 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001019 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001020 }
John Kessenich4016e382016-07-15 11:53:56 -06001021 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001022 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1023
1024 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1025 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001026 break;
1027
1028 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001029 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001030 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1031 glslangIntermediate->getLocalSize(1),
1032 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001033 break;
1034
1035 default:
1036 break;
1037 }
John Kessenich140f3df2015-06-26 16:58:36 -06001038}
1039
John Kessenichfca82622016-11-26 13:23:20 -07001040// Finish creating SPV, after the traversal is complete.
1041void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001042{
John Kessenich517fe7a2016-11-26 13:31:47 -07001043 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001044 builder.setBuildPoint(shaderEntry->getLastBlock());
1045 builder.leaveFunction();
1046 }
1047
John Kessenich7ba63412015-12-20 17:37:07 -07001048 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001049 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1050 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001051
qiningda397332016-03-09 19:54:03 -05001052 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001053}
1054
John Kessenichfca82622016-11-26 13:23:20 -07001055// Write the SPV into 'out'.
1056void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001057{
John Kessenichfca82622016-11-26 13:23:20 -07001058 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001059}
1060
1061//
1062// Implement the traversal functions.
1063//
1064// Return true from interior nodes to have the external traversal
1065// continue on to children. Return false if children were
1066// already processed.
1067//
1068
1069//
qining25262b32016-05-06 17:25:16 -04001070// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001071// - uniform/input reads
1072// - output writes
1073// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1074// - something simple that degenerates into the last bullet
1075//
1076void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1077{
qining75d1d802016-04-06 14:42:01 -04001078 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1079 if (symbol->getType().getQualifier().isSpecConstant())
1080 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1081
John Kessenich140f3df2015-06-26 16:58:36 -06001082 // getSymbolId() will set up all the IO decorations on the first call.
1083 // Formal function parameters were mapped during makeFunctions().
1084 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001085
1086 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1087 if (builder.isPointer(id)) {
1088 spv::StorageClass sc = builder.getStorageClass(id);
1089 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1090 iOSet.insert(id);
1091 }
1092
1093 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001094 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001095 // Prepare to generate code for the access
1096
1097 // L-value chains will be computed left to right. We're on the symbol now,
1098 // which is the left-most part of the access chain, so now is "clear" time,
1099 // followed by setting the base.
1100 builder.clearAccessChain();
1101
1102 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001103 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001104 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001105 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001106 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001107 // These are also pure R-values.
1108 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001109 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001110 builder.setAccessChainRValue(id);
1111 else
1112 builder.setAccessChainLValue(id);
1113 }
1114}
1115
1116bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1117{
John Kesseniche485c7a2017-05-31 18:50:53 -06001118 builder.setLine(node->getLoc().line);
1119
qining40887662016-04-03 22:20:42 -04001120 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1121 if (node->getType().getQualifier().isSpecConstant())
1122 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1123
John Kessenich140f3df2015-06-26 16:58:36 -06001124 // First, handle special cases
1125 switch (node->getOp()) {
1126 case glslang::EOpAssign:
1127 case glslang::EOpAddAssign:
1128 case glslang::EOpSubAssign:
1129 case glslang::EOpMulAssign:
1130 case glslang::EOpVectorTimesMatrixAssign:
1131 case glslang::EOpVectorTimesScalarAssign:
1132 case glslang::EOpMatrixTimesScalarAssign:
1133 case glslang::EOpMatrixTimesMatrixAssign:
1134 case glslang::EOpDivAssign:
1135 case glslang::EOpModAssign:
1136 case glslang::EOpAndAssign:
1137 case glslang::EOpInclusiveOrAssign:
1138 case glslang::EOpExclusiveOrAssign:
1139 case glslang::EOpLeftShiftAssign:
1140 case glslang::EOpRightShiftAssign:
1141 // A bin-op assign "a += b" means the same thing as "a = a + b"
1142 // where a is evaluated before b. For a simple assignment, GLSL
1143 // says to evaluate the left before the right. So, always, left
1144 // node then right node.
1145 {
1146 // get the left l-value, save it away
1147 builder.clearAccessChain();
1148 node->getLeft()->traverse(this);
1149 spv::Builder::AccessChain lValue = builder.getAccessChain();
1150
1151 // evaluate the right
1152 builder.clearAccessChain();
1153 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001154 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 if (node->getOp() != glslang::EOpAssign) {
1157 // the left is also an r-value
1158 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001159 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001160
1161 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001162 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001163 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001164 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1165 node->getType().getBasicType());
1166
1167 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001168 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001169 }
1170
1171 // store the result
1172 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001173 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 // assignments are expressions having an rValue after they are evaluated...
1176 builder.clearAccessChain();
1177 builder.setAccessChainRValue(rValue);
1178 }
1179 return false;
1180 case glslang::EOpIndexDirect:
1181 case glslang::EOpIndexDirectStruct:
1182 {
1183 // Get the left part of the access chain.
1184 node->getLeft()->traverse(this);
1185
1186 // Add the next element in the chain
1187
David Netoa901ffe2016-06-08 14:11:40 +01001188 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001189 if (! node->getLeft()->getType().isArray() &&
1190 node->getLeft()->getType().isVector() &&
1191 node->getOp() == glslang::EOpIndexDirect) {
1192 // This is essentially a hard-coded vector swizzle of size 1,
1193 // so short circuit the access-chain stuff with a swizzle.
1194 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001195 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001196 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001197 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001198 int spvIndex = glslangIndex;
1199 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1200 node->getOp() == glslang::EOpIndexDirectStruct)
1201 {
1202 // This may be, e.g., an anonymous block-member selection, which generally need
1203 // index remapping due to hidden members in anonymous blocks.
1204 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1205 assert(remapper.size() > 0);
1206 spvIndex = remapper[glslangIndex];
1207 }
John Kessenichebb50532016-05-16 19:22:05 -06001208
David Netoa901ffe2016-06-08 14:11:40 +01001209 // normal case for indexing array or structure or block
1210 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1211
1212 // Add capabilities here for accessing PointSize and clip/cull distance.
1213 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001214 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001215 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001216 }
1217 }
1218 return false;
1219 case glslang::EOpIndexIndirect:
1220 {
1221 // Structure or array or vector indirection.
1222 // Will use native SPIR-V access-chain for struct and array indirection;
1223 // matrices are arrays of vectors, so will also work for a matrix.
1224 // Will use the access chain's 'component' for variable index into a vector.
1225
1226 // This adapter is building access chains left to right.
1227 // Set up the access chain to the left.
1228 node->getLeft()->traverse(this);
1229
1230 // save it so that computing the right side doesn't trash it
1231 spv::Builder::AccessChain partial = builder.getAccessChain();
1232
1233 // compute the next index in the chain
1234 builder.clearAccessChain();
1235 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001236 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001237
1238 // restore the saved access chain
1239 builder.setAccessChain(partial);
1240
1241 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001242 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001243 else
John Kessenichfa668da2015-09-13 14:46:30 -06001244 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001245 }
1246 return false;
1247 case glslang::EOpVectorSwizzle:
1248 {
1249 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001250 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001251 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001252 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
1254 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001255 case glslang::EOpMatrixSwizzle:
1256 logger->missingFunctionality("matrix swizzle");
1257 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001258 case glslang::EOpLogicalOr:
1259 case glslang::EOpLogicalAnd:
1260 {
1261
1262 // These may require short circuiting, but can sometimes be done as straight
1263 // binary operations. The right operand must be short circuited if it has
1264 // side effects, and should probably be if it is complex.
1265 if (isTrivial(node->getRight()->getAsTyped()))
1266 break; // handle below as a normal binary operation
1267 // otherwise, we need to do dynamic short circuiting on the right operand
1268 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1269 builder.clearAccessChain();
1270 builder.setAccessChainRValue(result);
1271 }
1272 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001273 default:
1274 break;
1275 }
1276
1277 // Assume generic binary op...
1278
John Kessenich32cfd492016-02-02 12:37:46 -07001279 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001280 builder.clearAccessChain();
1281 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001282 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001283
John Kessenich32cfd492016-02-02 12:37:46 -07001284 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001285 builder.clearAccessChain();
1286 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001287 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001288
John Kessenich32cfd492016-02-02 12:37:46 -07001289 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001290 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001291 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001292 convertGlslangToSpvType(node->getType()), left, right,
1293 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001294
John Kessenich50e57562015-12-21 21:21:11 -07001295 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001296 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001297 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001298 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001299 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001300 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001301 return false;
1302 }
John Kessenich140f3df2015-06-26 16:58:36 -06001303}
1304
1305bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1306{
John Kesseniche485c7a2017-05-31 18:50:53 -06001307 builder.setLine(node->getLoc().line);
1308
qining40887662016-04-03 22:20:42 -04001309 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1310 if (node->getType().getQualifier().isSpecConstant())
1311 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1312
John Kessenichfc51d282015-08-19 13:34:18 -06001313 spv::Id result = spv::NoResult;
1314
1315 // try texturing first
1316 result = createImageTextureFunctionCall(node);
1317 if (result != spv::NoResult) {
1318 builder.clearAccessChain();
1319 builder.setAccessChainRValue(result);
1320
1321 return false; // done with this node
1322 }
1323
1324 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001325
1326 if (node->getOp() == glslang::EOpArrayLength) {
1327 // Quite special; won't want to evaluate the operand.
1328
1329 // Normal .length() would have been constant folded by the front-end.
1330 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001331 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001332 assert(node->getOperand()->getType().isRuntimeSizedArray());
1333 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1334 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001335 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1336 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001337
1338 builder.clearAccessChain();
1339 builder.setAccessChainRValue(length);
1340
1341 return false;
1342 }
1343
John Kessenichfc51d282015-08-19 13:34:18 -06001344 // Start by evaluating the operand
1345
John Kessenich8c8505c2016-07-26 12:50:38 -06001346 // Does it need a swizzle inversion? If so, evaluation is inverted;
1347 // operate first on the swizzle base, then apply the swizzle.
1348 spv::Id invertedType = spv::NoType;
1349 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1350 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1351 invertedType = getInvertedSwizzleType(*node->getOperand());
1352
John Kessenich140f3df2015-06-26 16:58:36 -06001353 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001354 if (invertedType != spv::NoType)
1355 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1356 else
1357 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001358
Rex Xufc618912015-09-09 16:42:49 +08001359 spv::Id operand = spv::NoResult;
1360
1361 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1362 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001363 node->getOp() == glslang::EOpAtomicCounter ||
1364 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001365 operand = builder.accessChainGetLValue(); // Special case l-value operands
1366 else
John Kessenich32cfd492016-02-02 12:37:46 -07001367 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001368
John Kessenichf6640762016-08-01 19:44:00 -06001369 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001370 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001371
1372 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001373 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001374 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001375
1376 // if not, then possibly an operation
1377 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001378 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001379
1380 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001381 if (invertedType)
1382 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1383
John Kessenich140f3df2015-06-26 16:58:36 -06001384 builder.clearAccessChain();
1385 builder.setAccessChainRValue(result);
1386
1387 return false; // done with this node
1388 }
1389
1390 // it must be a special case, check...
1391 switch (node->getOp()) {
1392 case glslang::EOpPostIncrement:
1393 case glslang::EOpPostDecrement:
1394 case glslang::EOpPreIncrement:
1395 case glslang::EOpPreDecrement:
1396 {
1397 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001398 spv::Id one = 0;
1399 if (node->getBasicType() == glslang::EbtFloat)
1400 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001401 else if (node->getBasicType() == glslang::EbtDouble)
1402 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001403#ifdef AMD_EXTENSIONS
1404 else if (node->getBasicType() == glslang::EbtFloat16)
1405 one = builder.makeFloat16Constant(1.0F);
1406#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001407 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1408 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001409#ifdef AMD_EXTENSIONS
1410 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1411 one = builder.makeInt16Constant(1);
1412#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001413 else
1414 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 glslang::TOperator op;
1416 if (node->getOp() == glslang::EOpPreIncrement ||
1417 node->getOp() == glslang::EOpPostIncrement)
1418 op = glslang::EOpAdd;
1419 else
1420 op = glslang::EOpSub;
1421
John Kessenichf6640762016-08-01 19:44:00 -06001422 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001423 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001424 convertGlslangToSpvType(node->getType()), operand, one,
1425 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001426 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 // The result of operation is always stored, but conditionally the
1429 // consumed result. The consumed result is always an r-value.
1430 builder.accessChainStore(result);
1431 builder.clearAccessChain();
1432 if (node->getOp() == glslang::EOpPreIncrement ||
1433 node->getOp() == glslang::EOpPreDecrement)
1434 builder.setAccessChainRValue(result);
1435 else
1436 builder.setAccessChainRValue(operand);
1437 }
1438
1439 return false;
1440
1441 case glslang::EOpEmitStreamVertex:
1442 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1443 return false;
1444 case glslang::EOpEndStreamPrimitive:
1445 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1446 return false;
1447
1448 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001449 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001450 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001451 }
John Kessenich140f3df2015-06-26 16:58:36 -06001452}
1453
1454bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1455{
qining27e04a02016-04-14 16:40:20 -04001456 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1457 if (node->getType().getQualifier().isSpecConstant())
1458 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1459
John Kessenichfc51d282015-08-19 13:34:18 -06001460 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001461 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1462 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001463
1464 // try texturing
1465 result = createImageTextureFunctionCall(node);
1466 if (result != spv::NoResult) {
1467 builder.clearAccessChain();
1468 builder.setAccessChainRValue(result);
1469
1470 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001471#ifdef AMD_EXTENSIONS
1472 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1473#else
John Kessenich56bab042015-09-16 10:54:31 -06001474 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001475#endif
Rex Xufc618912015-09-09 16:42:49 +08001476 // "imageStore" is a special case, which has no result
1477 return false;
1478 }
John Kessenichfc51d282015-08-19 13:34:18 -06001479
John Kessenich140f3df2015-06-26 16:58:36 -06001480 glslang::TOperator binOp = glslang::EOpNull;
1481 bool reduceComparison = true;
1482 bool isMatrix = false;
1483 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001484 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001485
1486 assert(node->getOp());
1487
John Kessenichf6640762016-08-01 19:44:00 -06001488 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001489
1490 switch (node->getOp()) {
1491 case glslang::EOpSequence:
1492 {
1493 if (preVisit)
1494 ++sequenceDepth;
1495 else
1496 --sequenceDepth;
1497
1498 if (sequenceDepth == 1) {
1499 // If this is the parent node of all the functions, we want to see them
1500 // early, so all call points have actual SPIR-V functions to reference.
1501 // In all cases, still let the traverser visit the children for us.
1502 makeFunctions(node->getAsAggregate()->getSequence());
1503
John Kessenich6fccb3c2016-09-19 16:01:41 -06001504 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001505 // anything else gets there, so visit out of order, doing them all now.
1506 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1507
John Kessenich6a60c2f2016-12-08 21:01:59 -07001508 // 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 -06001509 // so do them manually.
1510 visitFunctions(node->getAsAggregate()->getSequence());
1511
1512 return false;
1513 }
1514
1515 return true;
1516 }
1517 case glslang::EOpLinkerObjects:
1518 {
1519 if (visit == glslang::EvPreVisit)
1520 linkageOnly = true;
1521 else
1522 linkageOnly = false;
1523
1524 return true;
1525 }
1526 case glslang::EOpComma:
1527 {
1528 // processing from left to right naturally leaves the right-most
1529 // lying around in the access chain
1530 glslang::TIntermSequence& glslangOperands = node->getSequence();
1531 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1532 glslangOperands[i]->traverse(this);
1533
1534 return false;
1535 }
1536 case glslang::EOpFunction:
1537 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001538 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001539 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001540 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001541 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001542 } else {
1543 handleFunctionEntry(node);
1544 }
1545 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001546 if (inEntryPoint)
1547 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001548 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001549 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001550 }
1551
1552 return true;
1553 case glslang::EOpParameters:
1554 // Parameters will have been consumed by EOpFunction processing, but not
1555 // the body, so we still visited the function node's children, making this
1556 // child redundant.
1557 return false;
1558 case glslang::EOpFunctionCall:
1559 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001560 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 if (node->isUserDefined())
1562 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001563 // 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 -07001564 if (result) {
1565 builder.clearAccessChain();
1566 builder.setAccessChainRValue(result);
1567 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001568 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001569
1570 return false;
1571 }
1572 case glslang::EOpConstructMat2x2:
1573 case glslang::EOpConstructMat2x3:
1574 case glslang::EOpConstructMat2x4:
1575 case glslang::EOpConstructMat3x2:
1576 case glslang::EOpConstructMat3x3:
1577 case glslang::EOpConstructMat3x4:
1578 case glslang::EOpConstructMat4x2:
1579 case glslang::EOpConstructMat4x3:
1580 case glslang::EOpConstructMat4x4:
1581 case glslang::EOpConstructDMat2x2:
1582 case glslang::EOpConstructDMat2x3:
1583 case glslang::EOpConstructDMat2x4:
1584 case glslang::EOpConstructDMat3x2:
1585 case glslang::EOpConstructDMat3x3:
1586 case glslang::EOpConstructDMat3x4:
1587 case glslang::EOpConstructDMat4x2:
1588 case glslang::EOpConstructDMat4x3:
1589 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001590 case glslang::EOpConstructIMat2x2:
1591 case glslang::EOpConstructIMat2x3:
1592 case glslang::EOpConstructIMat2x4:
1593 case glslang::EOpConstructIMat3x2:
1594 case glslang::EOpConstructIMat3x3:
1595 case glslang::EOpConstructIMat3x4:
1596 case glslang::EOpConstructIMat4x2:
1597 case glslang::EOpConstructIMat4x3:
1598 case glslang::EOpConstructIMat4x4:
1599 case glslang::EOpConstructUMat2x2:
1600 case glslang::EOpConstructUMat2x3:
1601 case glslang::EOpConstructUMat2x4:
1602 case glslang::EOpConstructUMat3x2:
1603 case glslang::EOpConstructUMat3x3:
1604 case glslang::EOpConstructUMat3x4:
1605 case glslang::EOpConstructUMat4x2:
1606 case glslang::EOpConstructUMat4x3:
1607 case glslang::EOpConstructUMat4x4:
1608 case glslang::EOpConstructBMat2x2:
1609 case glslang::EOpConstructBMat2x3:
1610 case glslang::EOpConstructBMat2x4:
1611 case glslang::EOpConstructBMat3x2:
1612 case glslang::EOpConstructBMat3x3:
1613 case glslang::EOpConstructBMat3x4:
1614 case glslang::EOpConstructBMat4x2:
1615 case glslang::EOpConstructBMat4x3:
1616 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001617#ifdef AMD_EXTENSIONS
1618 case glslang::EOpConstructF16Mat2x2:
1619 case glslang::EOpConstructF16Mat2x3:
1620 case glslang::EOpConstructF16Mat2x4:
1621 case glslang::EOpConstructF16Mat3x2:
1622 case glslang::EOpConstructF16Mat3x3:
1623 case glslang::EOpConstructF16Mat3x4:
1624 case glslang::EOpConstructF16Mat4x2:
1625 case glslang::EOpConstructF16Mat4x3:
1626 case glslang::EOpConstructF16Mat4x4:
1627#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001628 isMatrix = true;
1629 // fall through
1630 case glslang::EOpConstructFloat:
1631 case glslang::EOpConstructVec2:
1632 case glslang::EOpConstructVec3:
1633 case glslang::EOpConstructVec4:
1634 case glslang::EOpConstructDouble:
1635 case glslang::EOpConstructDVec2:
1636 case glslang::EOpConstructDVec3:
1637 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001638#ifdef AMD_EXTENSIONS
1639 case glslang::EOpConstructFloat16:
1640 case glslang::EOpConstructF16Vec2:
1641 case glslang::EOpConstructF16Vec3:
1642 case glslang::EOpConstructF16Vec4:
1643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001644 case glslang::EOpConstructBool:
1645 case glslang::EOpConstructBVec2:
1646 case glslang::EOpConstructBVec3:
1647 case glslang::EOpConstructBVec4:
1648 case glslang::EOpConstructInt:
1649 case glslang::EOpConstructIVec2:
1650 case glslang::EOpConstructIVec3:
1651 case glslang::EOpConstructIVec4:
1652 case glslang::EOpConstructUint:
1653 case glslang::EOpConstructUVec2:
1654 case glslang::EOpConstructUVec3:
1655 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001656 case glslang::EOpConstructInt64:
1657 case glslang::EOpConstructI64Vec2:
1658 case glslang::EOpConstructI64Vec3:
1659 case glslang::EOpConstructI64Vec4:
1660 case glslang::EOpConstructUint64:
1661 case glslang::EOpConstructU64Vec2:
1662 case glslang::EOpConstructU64Vec3:
1663 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001664#ifdef AMD_EXTENSIONS
1665 case glslang::EOpConstructInt16:
1666 case glslang::EOpConstructI16Vec2:
1667 case glslang::EOpConstructI16Vec3:
1668 case glslang::EOpConstructI16Vec4:
1669 case glslang::EOpConstructUint16:
1670 case glslang::EOpConstructU16Vec2:
1671 case glslang::EOpConstructU16Vec3:
1672 case glslang::EOpConstructU16Vec4:
1673#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001674 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001675 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001676 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001677 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001678 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001679 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001680 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001681 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001682 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001683 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001684 std::vector<spv::Id> constituents;
1685 for (int c = 0; c < (int)arguments.size(); ++c)
1686 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001687 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001688 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001689 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001690 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001691 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001692
1693 builder.clearAccessChain();
1694 builder.setAccessChainRValue(constructed);
1695
1696 return false;
1697 }
1698
1699 // These six are component-wise compares with component-wise results.
1700 // Forward on to createBinaryOperation(), requesting a vector result.
1701 case glslang::EOpLessThan:
1702 case glslang::EOpGreaterThan:
1703 case glslang::EOpLessThanEqual:
1704 case glslang::EOpGreaterThanEqual:
1705 case glslang::EOpVectorEqual:
1706 case glslang::EOpVectorNotEqual:
1707 {
1708 // Map the operation to a binary
1709 binOp = node->getOp();
1710 reduceComparison = false;
1711 switch (node->getOp()) {
1712 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1713 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1714 default: binOp = node->getOp(); break;
1715 }
1716
1717 break;
1718 }
1719 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001720 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001721 binOp = glslang::EOpMul;
1722 break;
1723 case glslang::EOpOuterProduct:
1724 // two vectors multiplied to make a matrix
1725 binOp = glslang::EOpOuterProduct;
1726 break;
1727 case glslang::EOpDot:
1728 {
qining25262b32016-05-06 17:25:16 -04001729 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001730 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001731 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001732 binOp = glslang::EOpMul;
1733 break;
1734 }
1735 case glslang::EOpMod:
1736 // when an aggregate, this is the floating-point mod built-in function,
1737 // which can be emitted by the one in createBinaryOperation()
1738 binOp = glslang::EOpMod;
1739 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001740 case glslang::EOpEmitVertex:
1741 case glslang::EOpEndPrimitive:
1742 case glslang::EOpBarrier:
1743 case glslang::EOpMemoryBarrier:
1744 case glslang::EOpMemoryBarrierAtomicCounter:
1745 case glslang::EOpMemoryBarrierBuffer:
1746 case glslang::EOpMemoryBarrierImage:
1747 case glslang::EOpMemoryBarrierShared:
1748 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001749 case glslang::EOpAllMemoryBarrierWithGroupSync:
1750 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1751 case glslang::EOpWorkgroupMemoryBarrier:
1752 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001753 noReturnValue = true;
1754 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1755 break;
1756
John Kessenich426394d2015-07-23 10:22:48 -06001757 case glslang::EOpAtomicAdd:
1758 case glslang::EOpAtomicMin:
1759 case glslang::EOpAtomicMax:
1760 case glslang::EOpAtomicAnd:
1761 case glslang::EOpAtomicOr:
1762 case glslang::EOpAtomicXor:
1763 case glslang::EOpAtomicExchange:
1764 case glslang::EOpAtomicCompSwap:
1765 atomic = true;
1766 break;
1767
John Kessenich0d0c6d32017-07-23 16:08:26 -06001768 case glslang::EOpAtomicCounterAdd:
1769 case glslang::EOpAtomicCounterSubtract:
1770 case glslang::EOpAtomicCounterMin:
1771 case glslang::EOpAtomicCounterMax:
1772 case glslang::EOpAtomicCounterAnd:
1773 case glslang::EOpAtomicCounterOr:
1774 case glslang::EOpAtomicCounterXor:
1775 case glslang::EOpAtomicCounterExchange:
1776 case glslang::EOpAtomicCounterCompSwap:
1777 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1778 builder.addCapability(spv::CapabilityAtomicStorageOps);
1779 atomic = true;
1780 break;
1781
John Kessenich140f3df2015-06-26 16:58:36 -06001782 default:
1783 break;
1784 }
1785
1786 //
1787 // See if it maps to a regular operation.
1788 //
John Kessenich140f3df2015-06-26 16:58:36 -06001789 if (binOp != glslang::EOpNull) {
1790 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1791 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1792 assert(left && right);
1793
1794 builder.clearAccessChain();
1795 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001796 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001797
1798 builder.clearAccessChain();
1799 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001800 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001801
John Kesseniche485c7a2017-05-31 18:50:53 -06001802 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001803 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001804 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001805 left->getType().getBasicType(), reduceComparison);
1806
1807 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001808 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001809 builder.clearAccessChain();
1810 builder.setAccessChainRValue(result);
1811
1812 return false;
1813 }
1814
John Kessenich426394d2015-07-23 10:22:48 -06001815 //
1816 // Create the list of operands.
1817 //
John Kessenich140f3df2015-06-26 16:58:36 -06001818 glslang::TIntermSequence& glslangOperands = node->getSequence();
1819 std::vector<spv::Id> operands;
1820 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001821 // special case l-value operands; there are just a few
1822 bool lvalue = false;
1823 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001824 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001825 case glslang::EOpModf:
1826 if (arg == 1)
1827 lvalue = true;
1828 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001829 case glslang::EOpInterpolateAtSample:
1830 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001831#ifdef AMD_EXTENSIONS
1832 case glslang::EOpInterpolateAtVertex:
1833#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001834 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001835 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001836
1837 // Does it need a swizzle inversion? If so, evaluation is inverted;
1838 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001839 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001840 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1841 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1842 }
Rex Xu7a26c172015-12-08 17:12:09 +08001843 break;
Rex Xud4782c12015-09-06 16:30:11 +08001844 case glslang::EOpAtomicAdd:
1845 case glslang::EOpAtomicMin:
1846 case glslang::EOpAtomicMax:
1847 case glslang::EOpAtomicAnd:
1848 case glslang::EOpAtomicOr:
1849 case glslang::EOpAtomicXor:
1850 case glslang::EOpAtomicExchange:
1851 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001852 case glslang::EOpAtomicCounterAdd:
1853 case glslang::EOpAtomicCounterSubtract:
1854 case glslang::EOpAtomicCounterMin:
1855 case glslang::EOpAtomicCounterMax:
1856 case glslang::EOpAtomicCounterAnd:
1857 case glslang::EOpAtomicCounterOr:
1858 case glslang::EOpAtomicCounterXor:
1859 case glslang::EOpAtomicCounterExchange:
1860 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001861 if (arg == 0)
1862 lvalue = true;
1863 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001864 case glslang::EOpAddCarry:
1865 case glslang::EOpSubBorrow:
1866 if (arg == 2)
1867 lvalue = true;
1868 break;
1869 case glslang::EOpUMulExtended:
1870 case glslang::EOpIMulExtended:
1871 if (arg >= 2)
1872 lvalue = true;
1873 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001874 default:
1875 break;
1876 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001877 builder.clearAccessChain();
1878 if (invertedType != spv::NoType && arg == 0)
1879 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1880 else
1881 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001882 if (lvalue)
1883 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001884 else {
1885 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001886 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001887 }
John Kessenich140f3df2015-06-26 16:58:36 -06001888 }
John Kessenich426394d2015-07-23 10:22:48 -06001889
John Kesseniche485c7a2017-05-31 18:50:53 -06001890 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001891 if (atomic) {
1892 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001893 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001894 } else {
1895 // Pass through to generic operations.
1896 switch (glslangOperands.size()) {
1897 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001898 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001899 break;
1900 case 1:
qining25262b32016-05-06 17:25:16 -04001901 result = createUnaryOperation(
1902 node->getOp(), precision,
1903 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001904 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001905 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001906 break;
1907 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001908 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001909 break;
1910 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 if (invertedType)
1912 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001913 }
1914
1915 if (noReturnValue)
1916 return false;
1917
1918 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001919 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001920 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001921 } else {
1922 builder.clearAccessChain();
1923 builder.setAccessChainRValue(result);
1924 return false;
1925 }
1926}
1927
John Kessenich433e9ff2017-01-26 20:31:11 -07001928// This path handles both if-then-else and ?:
1929// The if-then-else has a node type of void, while
1930// ?: has either a void or a non-void node type
1931//
1932// Leaving the result, when not void:
1933// GLSL only has r-values as the result of a :?, but
1934// if we have an l-value, that can be more efficient if it will
1935// become the base of a complex r-value expression, because the
1936// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001937bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1938{
John Kessenich433e9ff2017-01-26 20:31:11 -07001939 // See if it simple and safe to generate OpSelect instead of using control flow.
1940 // Crucially, side effects must be avoided, and there are performance trade-offs.
1941 // Return true if good idea (and safe) for OpSelect, false otherwise.
1942 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001943 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1944 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001945 return false;
1946
1947 if (node->getTrueBlock() == nullptr ||
1948 node->getFalseBlock() == nullptr)
1949 return false;
1950
1951 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1952 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1953
1954 // return true if a single operand to ? : is okay for OpSelect
1955 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001956 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001957 };
1958
1959 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1960 operandOkay(node->getFalseBlock()->getAsTyped());
1961 };
1962
1963 // Emit OpSelect for this selection.
1964 const auto handleAsOpSelect = [&]() {
1965 node->getCondition()->traverse(this);
1966 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1967 node->getTrueBlock()->traverse(this);
1968 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1969 node->getFalseBlock()->traverse(this);
1970 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1971
John Kesseniche485c7a2017-05-31 18:50:53 -06001972 builder.setLine(node->getLoc().line);
1973
John Kesseniche434ad92017-03-30 10:09:28 -06001974 // smear condition to vector, if necessary (AST is always scalar)
1975 if (builder.isVector(trueValue))
1976 condition = builder.smearScalar(spv::NoPrecision, condition,
1977 builder.makeVectorType(builder.makeBoolType(),
1978 builder.getNumComponents(trueValue)));
1979
1980 spv::Id select = builder.createTriOp(spv::OpSelect,
1981 convertGlslangToSpvType(node->getType()), condition,
1982 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001983 builder.clearAccessChain();
1984 builder.setAccessChainRValue(select);
1985 };
1986
1987 // Try for OpSelect
1988
1989 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001990 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1991 if (node->getType().getQualifier().isSpecConstant())
1992 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1993
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 handleAsOpSelect();
1995 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001996 }
1997
Rex Xu57e65922017-07-04 23:23:40 +08001998 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001999 // Don't handle results as temporaries, because there will be two names
2000 // and better to leave SSA to later passes.
2001 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2002 ? spv::NoResult
2003 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2004
John Kessenich140f3df2015-06-26 16:58:36 -06002005 // emit the condition before doing anything with selection
2006 node->getCondition()->traverse(this);
2007
Rex Xu57e65922017-07-04 23:23:40 +08002008 // Selection control:
2009 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2010
John Kessenich140f3df2015-06-26 16:58:36 -06002011 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002012 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002013
John Kessenich433e9ff2017-01-26 20:31:11 -07002014 // emit the "then" statement
2015 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002016 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002017 if (result != spv::NoResult)
2018 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002019 }
2020
John Kessenich433e9ff2017-01-26 20:31:11 -07002021 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002022 ifBuilder.makeBeginElse();
2023 // emit the "else" statement
2024 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002025 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002026 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002027 }
2028
John Kessenich433e9ff2017-01-26 20:31:11 -07002029 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002030 ifBuilder.makeEndIf();
2031
John Kessenich433e9ff2017-01-26 20:31:11 -07002032 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002033 // GLSL only has r-values as the result of a :?, but
2034 // if we have an l-value, that can be more efficient if it will
2035 // become the base of a complex r-value expression, because the
2036 // next layer copies r-values into memory to use the access-chain mechanism
2037 builder.clearAccessChain();
2038 builder.setAccessChainLValue(result);
2039 }
2040
2041 return false;
2042}
2043
2044bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2045{
2046 // emit and get the condition before doing anything with switch
2047 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002048 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002049
Rex Xu57e65922017-07-04 23:23:40 +08002050 // Selection control:
2051 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2052
John Kessenich140f3df2015-06-26 16:58:36 -06002053 // browse the children to sort out code segments
2054 int defaultSegment = -1;
2055 std::vector<TIntermNode*> codeSegments;
2056 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2057 std::vector<int> caseValues;
2058 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2059 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2060 TIntermNode* child = *c;
2061 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002062 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002063 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002064 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002065 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2066 } else
2067 codeSegments.push_back(child);
2068 }
2069
qining25262b32016-05-06 17:25:16 -04002070 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002071 // statements between the last case and the end of the switch statement
2072 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2073 (int)codeSegments.size() == defaultSegment)
2074 codeSegments.push_back(nullptr);
2075
2076 // make the switch statement
2077 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002078 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002079
2080 // emit all the code in the segments
2081 breakForLoop.push(false);
2082 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2083 builder.nextSwitchSegment(segmentBlocks, s);
2084 if (codeSegments[s])
2085 codeSegments[s]->traverse(this);
2086 else
2087 builder.addSwitchBreak();
2088 }
2089 breakForLoop.pop();
2090
2091 builder.endSwitch(segmentBlocks);
2092
2093 return false;
2094}
2095
2096void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2097{
2098 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002099 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002100
2101 builder.clearAccessChain();
2102 builder.setAccessChainRValue(constant);
2103}
2104
2105bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2106{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002107 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002108 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002109
2110 // Loop control:
2111 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2112
2113 // TODO: dependency length
2114
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002115 // Spec requires back edges to target header blocks, and every header block
2116 // must dominate its merge block. Make a header block first to ensure these
2117 // conditions are met. By definition, it will contain OpLoopMerge, followed
2118 // by a block-ending branch. But we don't want to put any other body/test
2119 // instructions in it, since the body/test may have arbitrary instructions,
2120 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002121 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002122 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002123 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002124 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002125 spv::Block& test = builder.makeNewBlock();
2126 builder.createBranch(&test);
2127
2128 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002129 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002130 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002131 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2132
2133 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002134 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002135 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002136 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002137 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002138 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002139
2140 builder.setBuildPoint(&blocks.continue_target);
2141 if (node->getTerminal())
2142 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002143 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002144 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002145 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002146 builder.createBranch(&blocks.body);
2147
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002148 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002149 builder.setBuildPoint(&blocks.body);
2150 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002151 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002152 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002153 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154
2155 builder.setBuildPoint(&blocks.continue_target);
2156 if (node->getTerminal())
2157 node->getTerminal()->traverse(this);
2158 if (node->getTest()) {
2159 node->getTest()->traverse(this);
2160 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002161 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002162 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002163 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002164 // TODO: unless there was a break/return/discard instruction
2165 // somewhere in the body, this is an infinite loop, so we should
2166 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002167 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002168 }
John Kessenich140f3df2015-06-26 16:58:36 -06002169 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002170 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002171 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002172 return false;
2173}
2174
2175bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2176{
2177 if (node->getExpression())
2178 node->getExpression()->traverse(this);
2179
John Kesseniche485c7a2017-05-31 18:50:53 -06002180 builder.setLine(node->getLoc().line);
2181
John Kessenich140f3df2015-06-26 16:58:36 -06002182 switch (node->getFlowOp()) {
2183 case glslang::EOpKill:
2184 builder.makeDiscard();
2185 break;
2186 case glslang::EOpBreak:
2187 if (breakForLoop.top())
2188 builder.createLoopExit();
2189 else
2190 builder.addSwitchBreak();
2191 break;
2192 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002193 builder.createLoopContinue();
2194 break;
2195 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002196 if (node->getExpression()) {
2197 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2198 spv::Id returnId = accessChainLoad(glslangReturnType);
2199 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2200 builder.clearAccessChain();
2201 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2202 builder.setAccessChainLValue(copyId);
2203 multiTypeStore(glslangReturnType, returnId);
2204 returnId = builder.createLoad(copyId);
2205 }
2206 builder.makeReturn(false, returnId);
2207 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002208 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002209
2210 builder.clearAccessChain();
2211 break;
2212
2213 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002214 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002215 break;
2216 }
2217
2218 return false;
2219}
2220
2221spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2222{
qining25262b32016-05-06 17:25:16 -04002223 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002224 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002225 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002226 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002227 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002228 }
2229
2230 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002231 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002232 spv::Id spvType = convertGlslangToSpvType(node->getType());
2233
Rex Xuf89ad982017-04-07 23:22:33 +08002234#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002235 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2236 node->getType().containsBasicType(glslang::EbtInt16) ||
2237 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002238 if (contains16BitType) {
2239 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2240 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2241 builder.addCapability(spv::CapabilityStorageInputOutput16);
2242 } else if (storageClass == spv::StorageClassPushConstant) {
2243 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2244 builder.addCapability(spv::CapabilityStoragePushConstant16);
2245 } else if (storageClass == spv::StorageClassUniform) {
2246 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2247 builder.addCapability(spv::CapabilityStorageUniform16);
2248 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2249 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2250 }
2251 }
2252#endif
2253
John Kessenich140f3df2015-06-26 16:58:36 -06002254 const char* name = node->getName().c_str();
2255 if (glslang::IsAnonymous(name))
2256 name = "";
2257
2258 return builder.createVariable(storageClass, spvType, name);
2259}
2260
2261// Return type Id of the sampled type.
2262spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2263{
2264 switch (sampler.type) {
2265 case glslang::EbtFloat: return builder.makeFloatType(32);
2266 case glslang::EbtInt: return builder.makeIntType(32);
2267 case glslang::EbtUint: return builder.makeUintType(32);
2268 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002269 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002270 return builder.makeFloatType(32);
2271 }
2272}
2273
John Kessenich8c8505c2016-07-26 12:50:38 -06002274// If node is a swizzle operation, return the type that should be used if
2275// the swizzle base is first consumed by another operation, before the swizzle
2276// is applied.
2277spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2278{
John Kessenichecba76f2017-01-06 00:34:48 -07002279 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002280 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2281 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2282 else
2283 return spv::NoType;
2284}
2285
2286// When inverting a swizzle with a parent op, this function
2287// will apply the swizzle operation to a completed parent operation.
2288spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2289{
2290 std::vector<unsigned> swizzle;
2291 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2292 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2293}
2294
John Kessenich8c8505c2016-07-26 12:50:38 -06002295// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2296void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2297{
2298 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2299 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2300 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2301}
2302
John Kessenich3ac051e2015-12-20 11:29:16 -07002303// Convert from a glslang type to an SPV type, by calling into a
2304// recursive version of this function. This establishes the inherited
2305// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002306spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2307{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002308 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002309}
2310
2311// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002312// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002313// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002314spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002315{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002316 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002317
2318 switch (type.getBasicType()) {
2319 case glslang::EbtVoid:
2320 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002321 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002322 break;
2323 case glslang::EbtFloat:
2324 spvType = builder.makeFloatType(32);
2325 break;
2326 case glslang::EbtDouble:
2327 spvType = builder.makeFloatType(64);
2328 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002329#ifdef AMD_EXTENSIONS
2330 case glslang::EbtFloat16:
2331 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002332 spvType = builder.makeFloatType(16);
2333 break;
2334#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002335 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002336 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2337 // a 32-bit int where non-0 means true.
2338 if (explicitLayout != glslang::ElpNone)
2339 spvType = builder.makeUintType(32);
2340 else
2341 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343 case glslang::EbtInt:
2344 spvType = builder.makeIntType(32);
2345 break;
2346 case glslang::EbtUint:
2347 spvType = builder.makeUintType(32);
2348 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002349 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002350 spvType = builder.makeIntType(64);
2351 break;
2352 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002353 spvType = builder.makeUintType(64);
2354 break;
Rex Xucabbb782017-03-24 13:41:14 +08002355#ifdef AMD_EXTENSIONS
2356 case glslang::EbtInt16:
2357 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2358 spvType = builder.makeIntType(16);
2359 break;
2360 case glslang::EbtUint16:
2361 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2362 spvType = builder.makeUintType(16);
2363 break;
2364#endif
John Kessenich426394d2015-07-23 10:22:48 -06002365 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002366 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002367 spvType = builder.makeUintType(32);
2368 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002369 case glslang::EbtSampler:
2370 {
2371 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002372 if (sampler.sampler) {
2373 // pure sampler
2374 spvType = builder.makeSamplerType();
2375 } else {
2376 // an image is present, make its type
2377 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2378 sampler.image ? 2 : 1, TranslateImageFormat(type));
2379 if (sampler.combined) {
2380 // already has both image and sampler, make the combined type
2381 spvType = builder.makeSampledImageType(spvType);
2382 }
John Kessenich55e7d112015-11-15 21:33:39 -07002383 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002384 }
John Kessenich140f3df2015-06-26 16:58:36 -06002385 break;
2386 case glslang::EbtStruct:
2387 case glslang::EbtBlock:
2388 {
2389 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002390 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002391
2392 // Try to share structs for different layouts, but not yet for other
2393 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002394 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002395 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002396 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398
2399 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002400 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002401 memberRemapper[glslangMembers].resize(glslangMembers->size());
2402 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002403 }
2404 break;
2405 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002406 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 break;
2408 }
2409
2410 if (type.isMatrix())
2411 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2412 else {
2413 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2414 if (type.getVectorSize() > 1)
2415 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2416 }
2417
2418 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002419 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2420
John Kessenichc9a80832015-09-12 12:17:44 -06002421 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002422 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002423 // We need to decorate array strides for types needing explicit layout, except blocks.
2424 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002425 // Use a dummy glslang type for querying internal strides of
2426 // arrays of arrays, but using just a one-dimensional array.
2427 glslang::TType simpleArrayType(type, 0); // deference type of the array
2428 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2429 simpleArrayType.getArraySizes().dereference();
2430
2431 // Will compute the higher-order strides here, rather than making a whole
2432 // pile of types and doing repetitive recursion on their contents.
2433 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2434 }
John Kessenichf8842e52016-01-04 19:22:56 -07002435
2436 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002437 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002438 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 if (stride > 0)
2440 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002441 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 }
2443 } else {
2444 // single-dimensional array, and don't yet have stride
2445
John Kessenichf8842e52016-01-04 19:22:56 -07002446 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002447 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2448 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002449 }
John Kessenich31ed4832015-09-09 17:51:38 -06002450
John Kessenichc9a80832015-09-12 12:17:44 -06002451 // Do the outer dimension, which might not be known for a runtime-sized array
2452 if (type.isRuntimeSizedArray()) {
2453 spvType = builder.makeRuntimeArray(spvType);
2454 } else {
2455 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002456 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002457 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 if (stride > 0)
2459 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002460 }
2461
2462 return spvType;
2463}
2464
John Kessenich0e737842017-03-24 18:38:16 -06002465// TODO: this functionality should exist at a higher level, in creating the AST
2466//
2467// Identify interface members that don't have their required extension turned on.
2468//
2469bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2470{
2471 auto& extensions = glslangIntermediate->getRequestedExtensions();
2472
Rex Xubcf291a2017-03-29 23:01:36 +08002473 if (member.getFieldName() == "gl_ViewportMask" &&
2474 extensions.find("GL_NV_viewport_array2") == extensions.end())
2475 return true;
2476 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2477 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2478 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002479 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2480 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2481 return true;
2482 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2483 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2484 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002485 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2486 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2487 return true;
John Kessenichd6be6da2017-08-17 23:49:39 -06002488 if ((member.getFieldName() == "gl_ViewportIndex" || member.getFieldName() == "gl_Layer") &&
2489 extensions.find(glslang::E_GL_ARB_shader_viewport_layer_array) == extensions.end() &&
John Kessenich786e8792017-08-19 15:54:49 -06002490 extensions.find("GL_NV_viewport_array2") == extensions.end())
John Kessenichd6be6da2017-08-17 23:49:39 -06002491 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002492
2493 return false;
2494};
2495
John Kessenich6090df02016-06-30 21:18:02 -06002496// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2497// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2498// Mutually recursive with convertGlslangToSpvType().
2499spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2500 const glslang::TTypeList* glslangMembers,
2501 glslang::TLayoutPacking explicitLayout,
2502 const glslang::TQualifier& qualifier)
2503{
2504 // Create a vector of struct types for SPIR-V to consume
2505 std::vector<spv::Id> spvMembers;
2506 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 -06002507 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2508 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2509 if (glslangMember.hiddenMember()) {
2510 ++memberDelta;
2511 if (type.getBasicType() == glslang::EbtBlock)
2512 memberRemapper[glslangMembers][i] = -1;
2513 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002514 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002515 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002516 if (filterMember(glslangMember))
2517 continue;
2518 }
John Kessenich6090df02016-06-30 21:18:02 -06002519 // modify just this child's view of the qualifier
2520 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2521 InheritQualifiers(memberQualifier, qualifier);
2522
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002523 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002524 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002525 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002526
2527 // recurse
2528 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2529 }
2530 }
2531
2532 // Make the SPIR-V type
2533 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002534 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002535 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2536
2537 // Decorate it
2538 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2539
2540 return spvType;
2541}
2542
2543void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2544 const glslang::TTypeList* glslangMembers,
2545 glslang::TLayoutPacking explicitLayout,
2546 const glslang::TQualifier& qualifier,
2547 spv::Id spvType)
2548{
2549 // Name and decorate the non-hidden members
2550 int offset = -1;
2551 int locationOffset = 0; // for use within the members of this struct
2552 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2553 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2554 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002555 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002556 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002557 if (filterMember(glslangMember))
2558 continue;
2559 }
John Kessenich6090df02016-06-30 21:18:02 -06002560
2561 // modify just this child's view of the qualifier
2562 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2563 InheritQualifiers(memberQualifier, qualifier);
2564
2565 // using -1 above to indicate a hidden member
2566 if (member >= 0) {
2567 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2568 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2569 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2570 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002571 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2572 type.getQualifier().storage == glslang::EvqVaryingOut) {
2573 if (type.getBasicType() == glslang::EbtBlock ||
2574 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002575 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2576 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2577 }
2578 }
2579 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2580
Rex Xu286ca432017-07-27 14:33:16 +08002581 if (type.getBasicType() == glslang::EbtBlock &&
2582 qualifier.storage == glslang::EvqBuffer) {
2583 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002584 std::vector<spv::Decoration> memory;
2585 TranslateMemoryDecoration(memberQualifier, memory);
2586 for (unsigned int i = 0; i < memory.size(); ++i)
2587 addMemberDecoration(spvType, member, memory[i]);
2588 }
2589
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002590 // Location assignment was already completed correctly by the front end,
2591 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002592 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002593 // ill-specified and decisions have been made to not allow this.
2594 if (! type.isArray() && memberQualifier.hasLocation())
2595 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002596
John Kessenich2f47bc92016-06-30 21:47:35 -06002597 if (qualifier.hasLocation()) // track for upcoming inheritance
2598 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2599
John Kessenich6090df02016-06-30 21:18:02 -06002600 // component, XFB, others
2601 if (glslangMember.getQualifier().hasComponent())
2602 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2603 if (glslangMember.getQualifier().hasXfbOffset())
2604 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2605 else if (explicitLayout != glslang::ElpNone) {
2606 // figure out what to do with offset, which is accumulating
2607 int nextOffset;
2608 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2609 if (offset >= 0)
2610 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2611 offset = nextOffset;
2612 }
2613
2614 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2615 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2616
2617 // built-in variable decorations
2618 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002619 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002620 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002621
2622#ifdef NV_EXTENSIONS
2623 if (builtIn == spv::BuiltInLayer) {
2624 // SPV_NV_viewport_array2 extension
2625 if (glslangMember.getQualifier().layoutViewportRelative){
2626 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2627 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2628 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2629 }
2630 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2631 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2632 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2633 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2634 }
2635 }
chaocdf3956c2017-02-14 14:52:34 -08002636 if (glslangMember.getQualifier().layoutPassthrough) {
2637 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2638 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2639 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2640 }
chaoc771d89f2017-01-13 01:10:53 -08002641#endif
John Kessenich6090df02016-06-30 21:18:02 -06002642 }
2643 }
2644
2645 // Decorate the structure
2646 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002647 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002648 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2649 builder.addCapability(spv::CapabilityGeometryStreams);
2650 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2651 }
2652 if (glslangIntermediate->getXfbMode()) {
2653 builder.addCapability(spv::CapabilityTransformFeedback);
2654 if (type.getQualifier().hasXfbStride())
2655 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2656 if (type.getQualifier().hasXfbBuffer())
2657 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2658 }
2659}
2660
John Kessenich6c292d32016-02-15 20:58:50 -07002661// Turn the expression forming the array size into an id.
2662// This is not quite trivial, because of specialization constants.
2663// Sometimes, a raw constant is turned into an Id, and sometimes
2664// a specialization constant expression is.
2665spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2666{
2667 // First, see if this is sized with a node, meaning a specialization constant:
2668 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2669 if (specNode != nullptr) {
2670 builder.clearAccessChain();
2671 specNode->traverse(this);
2672 return accessChainLoad(specNode->getAsTyped()->getType());
2673 }
qining25262b32016-05-06 17:25:16 -04002674
John Kessenich6c292d32016-02-15 20:58:50 -07002675 // Otherwise, need a compile-time (front end) size, get it:
2676 int size = arraySizes.getDimSize(dim);
2677 assert(size > 0);
2678 return builder.makeUintConstant(size);
2679}
2680
John Kessenich103bef92016-02-08 21:38:15 -07002681// Wrap the builder's accessChainLoad to:
2682// - localize handling of RelaxedPrecision
2683// - use the SPIR-V inferred type instead of another conversion of the glslang type
2684// (avoids unnecessary work and possible type punning for structures)
2685// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002686spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2687{
John Kessenich103bef92016-02-08 21:38:15 -07002688 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2689 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2690
2691 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002692 if (type.getBasicType() == glslang::EbtBool) {
2693 if (builder.isScalarType(nominalTypeId)) {
2694 // Conversion for bool
2695 spv::Id boolType = builder.makeBoolType();
2696 if (nominalTypeId != boolType)
2697 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2698 } else if (builder.isVectorType(nominalTypeId)) {
2699 // Conversion for bvec
2700 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2701 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2702 if (nominalTypeId != bvecType)
2703 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2704 }
2705 }
John Kessenich103bef92016-02-08 21:38:15 -07002706
2707 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002708}
2709
Rex Xu27253232016-02-23 17:51:09 +08002710// Wrap the builder's accessChainStore to:
2711// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002712//
2713// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002714void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2715{
2716 // Need to convert to abstract types when necessary
2717 if (type.getBasicType() == glslang::EbtBool) {
2718 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2719
2720 if (builder.isScalarType(nominalTypeId)) {
2721 // Conversion for bool
2722 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002723 if (nominalTypeId != boolType) {
2724 // keep these outside arguments, for determinant order-of-evaluation
2725 spv::Id one = builder.makeUintConstant(1);
2726 spv::Id zero = builder.makeUintConstant(0);
2727 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2728 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002729 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002730 } else if (builder.isVectorType(nominalTypeId)) {
2731 // Conversion for bvec
2732 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2733 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002734 if (nominalTypeId != bvecType) {
2735 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002736 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2737 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2738 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002739 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002740 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2741 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002742 }
2743 }
2744
2745 builder.accessChainStore(rvalue);
2746}
2747
John Kessenich4bf71552016-09-02 11:20:21 -06002748// For storing when types match at the glslang level, but not might match at the
2749// SPIR-V level.
2750//
2751// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002752// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002753// as in a member-decorated way.
2754//
2755// NOTE: This function can handle any store request; if it's not special it
2756// simplifies to a simple OpStore.
2757//
2758// Implicitly uses the existing builder.accessChain as the storage target.
2759void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2760{
John Kessenichb3e24e42016-09-11 12:33:43 -06002761 // we only do the complex path here if it's an aggregate
2762 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002763 accessChainStore(type, rValue);
2764 return;
2765 }
2766
John Kessenichb3e24e42016-09-11 12:33:43 -06002767 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002768 spv::Id rType = builder.getTypeId(rValue);
2769 spv::Id lValue = builder.accessChainGetLValue();
2770 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2771 if (lType == rType) {
2772 accessChainStore(type, rValue);
2773 return;
2774 }
2775
John Kessenichb3e24e42016-09-11 12:33:43 -06002776 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002777 // where the two types were the same type in GLSL. This requires member
2778 // by member copy, recursively.
2779
John Kessenichb3e24e42016-09-11 12:33:43 -06002780 // If an array, copy element by element.
2781 if (type.isArray()) {
2782 glslang::TType glslangElementType(type, 0);
2783 spv::Id elementRType = builder.getContainedTypeId(rType);
2784 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2785 // get the source member
2786 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002787
John Kessenichb3e24e42016-09-11 12:33:43 -06002788 // set up the target storage
2789 builder.clearAccessChain();
2790 builder.setAccessChainLValue(lValue);
2791 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002792
John Kessenichb3e24e42016-09-11 12:33:43 -06002793 // store the member
2794 multiTypeStore(glslangElementType, elementRValue);
2795 }
2796 } else {
2797 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002798
John Kessenichb3e24e42016-09-11 12:33:43 -06002799 // loop over structure members
2800 const glslang::TTypeList& members = *type.getStruct();
2801 for (int m = 0; m < (int)members.size(); ++m) {
2802 const glslang::TType& glslangMemberType = *members[m].type;
2803
2804 // get the source member
2805 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2806 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2807
2808 // set up the target storage
2809 builder.clearAccessChain();
2810 builder.setAccessChainLValue(lValue);
2811 builder.accessChainPush(builder.makeIntConstant(m));
2812
2813 // store the member
2814 multiTypeStore(glslangMemberType, memberRValue);
2815 }
John Kessenich4bf71552016-09-02 11:20:21 -06002816 }
2817}
2818
John Kessenichf85e8062015-12-19 13:57:10 -07002819// Decide whether or not this type should be
2820// decorated with offsets and strides, and if so
2821// whether std140 or std430 rules should be applied.
2822glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002823{
John Kessenichf85e8062015-12-19 13:57:10 -07002824 // has to be a block
2825 if (type.getBasicType() != glslang::EbtBlock)
2826 return glslang::ElpNone;
2827
2828 // has to be a uniform or buffer block
2829 if (type.getQualifier().storage != glslang::EvqUniform &&
2830 type.getQualifier().storage != glslang::EvqBuffer)
2831 return glslang::ElpNone;
2832
2833 // return the layout to use
2834 switch (type.getQualifier().layoutPacking) {
2835 case glslang::ElpStd140:
2836 case glslang::ElpStd430:
2837 return type.getQualifier().layoutPacking;
2838 default:
2839 return glslang::ElpNone;
2840 }
John Kessenich31ed4832015-09-09 17:51:38 -06002841}
2842
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002843// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002844int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002845{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002846 int size;
John Kessenich49987892015-12-29 17:11:44 -07002847 int stride;
2848 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002849
2850 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002851}
2852
John Kessenich49987892015-12-29 17:11:44 -07002853// 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 -07002854// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002855int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002856{
John Kessenich49987892015-12-29 17:11:44 -07002857 glslang::TType elementType;
2858 elementType.shallowCopy(matrixType);
2859 elementType.clearArraySizes();
2860
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002861 int size;
John Kessenich49987892015-12-29 17:11:44 -07002862 int stride;
2863 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2864
2865 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002866}
2867
John Kessenich5e4b1242015-08-06 22:53:06 -06002868// Given a member type of a struct, realign the current offset for it, and compute
2869// the next (not yet aligned) offset for the next member, which will get aligned
2870// on the next call.
2871// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2872// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2873// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002874void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002875 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002876{
2877 // this will get a positive value when deemed necessary
2878 nextOffset = -1;
2879
John Kessenich5e4b1242015-08-06 22:53:06 -06002880 // override anything in currentOffset with user-set offset
2881 if (memberType.getQualifier().hasOffset())
2882 currentOffset = memberType.getQualifier().layoutOffset;
2883
2884 // It could be that current linker usage in glslang updated all the layoutOffset,
2885 // in which case the following code does not matter. But, that's not quite right
2886 // once cross-compilation unit GLSL validation is done, as the original user
2887 // settings are needed in layoutOffset, and then the following will come into play.
2888
John Kessenichf85e8062015-12-19 13:57:10 -07002889 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 if (! memberType.getQualifier().hasOffset())
2891 currentOffset = -1;
2892
2893 return;
2894 }
2895
John Kessenichf85e8062015-12-19 13:57:10 -07002896 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 if (currentOffset < 0)
2898 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002899
John Kessenich5e4b1242015-08-06 22:53:06 -06002900 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2901 // but possibly not yet correctly aligned.
2902
2903 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002904 int dummyStride;
2905 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002906
2907 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002908 // TODO: make this consistent in early phases of code:
2909 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2910 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2911 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002912 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002913 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002914 int dummySize;
2915 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2916 if (componentAlignment <= 4)
2917 memberAlignment = componentAlignment;
2918 }
2919
2920 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002922
2923 // Bump up to vec4 if there is a bad straddle
2924 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2925 glslang::RoundToPow2(currentOffset, 16);
2926
John Kessenich5e4b1242015-08-06 22:53:06 -06002927 nextOffset = currentOffset + memberSize;
2928}
2929
David Netoa901ffe2016-06-08 14:11:40 +01002930void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002931{
David Netoa901ffe2016-06-08 14:11:40 +01002932 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2933 switch (glslangBuiltIn)
2934 {
2935 case glslang::EbvClipDistance:
2936 case glslang::EbvCullDistance:
2937 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002938#ifdef NV_EXTENSIONS
2939 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002940 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002941 case glslang::EbvViewportMaskNV:
2942 case glslang::EbvSecondaryPositionNV:
2943 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002944 case glslang::EbvPositionPerViewNV:
2945 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002946#endif
David Netoa901ffe2016-06-08 14:11:40 +01002947 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2948 // Alternately, we could just call this for any glslang built-in, since the
2949 // capability already guards against duplicates.
2950 TranslateBuiltInDecoration(glslangBuiltIn, false);
2951 break;
2952 default:
2953 // Capabilities were already generated when the struct was declared.
2954 break;
2955 }
John Kessenichebb50532016-05-16 19:22:05 -06002956}
2957
John Kessenich6fccb3c2016-09-19 16:01:41 -06002958bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002959{
John Kessenicheee9d532016-09-19 18:09:30 -06002960 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002961}
2962
2963// Make all the functions, skeletally, without actually visiting their bodies.
2964void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2965{
John Kessenichfad62972017-07-18 02:35:46 -06002966 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2967 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2968 if (paramPrecision != spv::NoPrecision)
2969 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002970 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002971 };
2972
John Kessenich140f3df2015-06-26 16:58:36 -06002973 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2974 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002975 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002976 continue;
2977
2978 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002979 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002980 //
qining25262b32016-05-06 17:25:16 -04002981 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002982 // function. What it is an address of varies:
2983 //
John Kessenich4bf71552016-09-02 11:20:21 -06002984 // - "in" parameters not marked as "const" can be written to without modifying the calling
2985 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002986 //
2987 // - "const in" parameters can just be the r-value, as no writes need occur.
2988 //
John Kessenich4bf71552016-09-02 11:20:21 -06002989 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2990 // 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 -06002991
2992 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002993 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002994 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2995
John Kessenichfad62972017-07-18 02:35:46 -06002996 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2997 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002998
John Kessenichfad62972017-07-18 02:35:46 -06002999 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003000 for (int p = 0; p < (int)parameters.size(); ++p) {
3001 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3002 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06003003 // can we pass by reference?
3004 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06003005 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06003006 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06003007 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06003008 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07003009 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003010 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3011 else
John Kessenich4bf71552016-09-02 11:20:21 -06003012 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003013 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003014 paramTypes.push_back(typeId);
3015 }
3016
3017 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003018 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3019 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003020 glslFunction->getName().c_str(), paramTypes,
3021 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003022 if (implicitThis)
3023 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003024
3025 // Track function to emit/call later
3026 functionMap[glslFunction->getName().c_str()] = function;
3027
3028 // Set the parameter id's
3029 for (int p = 0; p < (int)parameters.size(); ++p) {
3030 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3031 // give a name too
3032 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3033 }
3034 }
3035}
3036
3037// Process all the initializers, while skipping the functions and link objects
3038void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3039{
3040 builder.setBuildPoint(shaderEntry->getLastBlock());
3041 for (int i = 0; i < (int)initializers.size(); ++i) {
3042 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3043 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3044
3045 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003046 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003047 initializer->traverse(this);
3048 }
3049 }
3050}
3051
3052// Process all the functions, while skipping initializers.
3053void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3054{
3055 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3056 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003057 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003058 node->traverse(this);
3059 }
3060}
3061
3062void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3063{
qining25262b32016-05-06 17:25:16 -04003064 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003065 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003066 currentFunction = functionMap[node->getName().c_str()];
3067 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003068 builder.setBuildPoint(functionBlock);
3069}
3070
Rex Xu04db3f52015-09-16 11:44:02 +08003071void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003072{
Rex Xufc618912015-09-09 16:42:49 +08003073 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003074
3075 glslang::TSampler sampler = {};
3076 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003077 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003078 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3079 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3080 }
3081
John Kessenich140f3df2015-06-26 16:58:36 -06003082 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3083 builder.clearAccessChain();
3084 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003085
3086 // Special case l-value operands
3087 bool lvalue = false;
3088 switch (node.getOp()) {
3089 case glslang::EOpImageAtomicAdd:
3090 case glslang::EOpImageAtomicMin:
3091 case glslang::EOpImageAtomicMax:
3092 case glslang::EOpImageAtomicAnd:
3093 case glslang::EOpImageAtomicOr:
3094 case glslang::EOpImageAtomicXor:
3095 case glslang::EOpImageAtomicExchange:
3096 case glslang::EOpImageAtomicCompSwap:
3097 if (i == 0)
3098 lvalue = true;
3099 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003100 case glslang::EOpSparseImageLoad:
3101 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3102 lvalue = true;
3103 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003104 case glslang::EOpSparseTexture:
3105 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3106 lvalue = true;
3107 break;
3108 case glslang::EOpSparseTextureClamp:
3109 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3110 lvalue = true;
3111 break;
3112 case glslang::EOpSparseTextureLod:
3113 case glslang::EOpSparseTextureOffset:
3114 if (i == 3)
3115 lvalue = true;
3116 break;
3117 case glslang::EOpSparseTextureFetch:
3118 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3119 lvalue = true;
3120 break;
3121 case glslang::EOpSparseTextureFetchOffset:
3122 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3123 lvalue = true;
3124 break;
3125 case glslang::EOpSparseTextureLodOffset:
3126 case glslang::EOpSparseTextureGrad:
3127 case glslang::EOpSparseTextureOffsetClamp:
3128 if (i == 4)
3129 lvalue = true;
3130 break;
3131 case glslang::EOpSparseTextureGradOffset:
3132 case glslang::EOpSparseTextureGradClamp:
3133 if (i == 5)
3134 lvalue = true;
3135 break;
3136 case glslang::EOpSparseTextureGradOffsetClamp:
3137 if (i == 6)
3138 lvalue = true;
3139 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003140 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003141 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3142 lvalue = true;
3143 break;
3144 case glslang::EOpSparseTextureGatherOffset:
3145 case glslang::EOpSparseTextureGatherOffsets:
3146 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3147 lvalue = true;
3148 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003149#ifdef AMD_EXTENSIONS
3150 case glslang::EOpSparseTextureGatherLod:
3151 if (i == 3)
3152 lvalue = true;
3153 break;
3154 case glslang::EOpSparseTextureGatherLodOffset:
3155 case glslang::EOpSparseTextureGatherLodOffsets:
3156 if (i == 4)
3157 lvalue = true;
3158 break;
Rex Xu129799a2017-07-05 17:23:28 +08003159 case glslang::EOpSparseImageLoadLod:
3160 if (i == 3)
3161 lvalue = true;
3162 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003163#endif
Rex Xufc618912015-09-09 16:42:49 +08003164 default:
3165 break;
3166 }
3167
Rex Xu6b86d492015-09-16 17:48:22 +08003168 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003169 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003170 else
John Kessenich32cfd492016-02-02 12:37:46 -07003171 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003172 }
3173}
3174
John Kessenichfc51d282015-08-19 13:34:18 -06003175void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003176{
John Kessenichfc51d282015-08-19 13:34:18 -06003177 builder.clearAccessChain();
3178 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003179 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003180}
John Kessenich140f3df2015-06-26 16:58:36 -06003181
John Kessenichfc51d282015-08-19 13:34:18 -06003182spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3183{
John Kesseniche485c7a2017-05-31 18:50:53 -06003184 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003185 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003186
3187 builder.setLine(node->getLoc().line);
3188
John Kessenich8c8505c2016-07-26 12:50:38 -06003189 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003190
John Kessenichfc51d282015-08-19 13:34:18 -06003191 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003192 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3193 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3194 std::vector<spv::Id> arguments;
3195 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003196 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003197 else
3198 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003199 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003200
3201 spv::Builder::TextureParameters params = { };
3202 params.sampler = arguments[0];
3203
Rex Xu04db3f52015-09-16 11:44:02 +08003204 glslang::TCrackedTextureOp cracked;
3205 node->crackTexture(sampler, cracked);
3206
amhagan05506bb2017-06-13 16:53:02 -04003207 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003208
John Kessenichfc51d282015-08-19 13:34:18 -06003209 // Check for queries
3210 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003211 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3212 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003213 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003214
John Kessenichfc51d282015-08-19 13:34:18 -06003215 switch (node->getOp()) {
3216 case glslang::EOpImageQuerySize:
3217 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003218 if (arguments.size() > 1) {
3219 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003220 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003221 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003222 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003223 case glslang::EOpImageQuerySamples:
3224 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003225 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003226 case glslang::EOpTextureQueryLod:
3227 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003228 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003229 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003230 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003231 case glslang::EOpSparseTexelsResident:
3232 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003233 default:
3234 assert(0);
3235 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003236 }
John Kessenich140f3df2015-06-26 16:58:36 -06003237 }
3238
Rex Xufc618912015-09-09 16:42:49 +08003239 // Check for image functions other than queries
3240 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003241 std::vector<spv::Id> operands;
3242 auto opIt = arguments.begin();
3243 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003244
3245 // Handle subpass operations
3246 // TODO: GLSL should change to have the "MS" only on the type rather than the
3247 // built-in function.
3248 if (cracked.subpass) {
3249 // add on the (0,0) coordinate
3250 spv::Id zero = builder.makeIntConstant(0);
3251 std::vector<spv::Id> comps;
3252 comps.push_back(zero);
3253 comps.push_back(zero);
3254 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3255 if (sampler.ms) {
3256 operands.push_back(spv::ImageOperandsSampleMask);
3257 operands.push_back(*(opIt++));
3258 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003259 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003260 }
3261
John Kessenich56bab042015-09-16 10:54:31 -06003262 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003263#ifdef AMD_EXTENSIONS
3264 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3265#else
John Kessenich56bab042015-09-16 10:54:31 -06003266 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003267#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003268 if (sampler.ms) {
3269 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003270 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003271#ifdef AMD_EXTENSIONS
3272 } else if (cracked.lod) {
3273 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3274 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3275
3276 operands.push_back(spv::ImageOperandsLodMask);
3277 operands.push_back(*opIt);
3278#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003279 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003280 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3281 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003282 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003283#ifdef AMD_EXTENSIONS
3284 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3285#else
John Kessenich56bab042015-09-16 10:54:31 -06003286 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003287#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003288 if (sampler.ms) {
3289 operands.push_back(*(opIt + 1));
3290 operands.push_back(spv::ImageOperandsSampleMask);
3291 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003292#ifdef AMD_EXTENSIONS
3293 } else if (cracked.lod) {
3294 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3295 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3296
3297 operands.push_back(*(opIt + 1));
3298 operands.push_back(spv::ImageOperandsLodMask);
3299 operands.push_back(*opIt);
3300#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003301 } else
3302 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003303 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003304 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3305 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003306 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003307#ifdef AMD_EXTENSIONS
3308 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3309#else
Rex Xu5eafa472016-02-19 22:24:03 +08003310 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003311#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003312 builder.addCapability(spv::CapabilitySparseResidency);
3313 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3314 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3315
3316 if (sampler.ms) {
3317 operands.push_back(spv::ImageOperandsSampleMask);
3318 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003319#ifdef AMD_EXTENSIONS
3320 } else if (cracked.lod) {
3321 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3322 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3323
3324 operands.push_back(spv::ImageOperandsLodMask);
3325 operands.push_back(*opIt++);
3326#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003327 }
3328
3329 // Create the return type that was a special structure
3330 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003331 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003332 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3333 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3334
3335 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3336
3337 // Decode the return type
3338 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3339 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003340 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003341 // Process image atomic operations
3342
3343 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3344 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003345 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003346
John Kessenich8c8505c2016-07-26 12:50:38 -06003347 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003348 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003349
3350 std::vector<spv::Id> operands;
3351 operands.push_back(pointer);
3352 for (; opIt != arguments.end(); ++opIt)
3353 operands.push_back(*opIt);
3354
John Kessenich8c8505c2016-07-26 12:50:38 -06003355 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003356 }
3357 }
3358
amhagan05506bb2017-06-13 16:53:02 -04003359#ifdef AMD_EXTENSIONS
3360 // Check for fragment mask functions other than queries
3361 if (cracked.fragMask) {
3362 assert(sampler.ms);
3363
3364 auto opIt = arguments.begin();
3365 std::vector<spv::Id> operands;
3366
3367 // Extract the image if necessary
3368 if (builder.isSampledImage(params.sampler))
3369 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3370
3371 operands.push_back(params.sampler);
3372 ++opIt;
3373
3374 if (sampler.isSubpass()) {
3375 // add on the (0,0) coordinate
3376 spv::Id zero = builder.makeIntConstant(0);
3377 std::vector<spv::Id> comps;
3378 comps.push_back(zero);
3379 comps.push_back(zero);
3380 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3381 }
3382
3383 for (; opIt != arguments.end(); ++opIt)
3384 operands.push_back(*opIt);
3385
3386 spv::Op fragMaskOp = spv::OpNop;
3387 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3388 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3389 else if (node->getOp() == glslang::EOpFragmentFetch)
3390 fragMaskOp = spv::OpFragmentFetchAMD;
3391
3392 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3393 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3394 return builder.createOp(fragMaskOp, resultType(), operands);
3395 }
3396#endif
3397
Rex Xufc618912015-09-09 16:42:49 +08003398 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003399 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003400 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3401
John Kessenichfc51d282015-08-19 13:34:18 -06003402 // check for bias argument
3403 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003404#ifdef AMD_EXTENSIONS
3405 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3406#else
Rex Xu71519fe2015-11-11 15:35:47 +08003407 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003408#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003409 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003410#ifdef AMD_EXTENSIONS
3411 if (cracked.gather)
3412 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3413#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003414 if (cracked.offset)
3415 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003416#ifdef AMD_EXTENSIONS
3417 else if (cracked.offsets)
3418 ++nonBiasArgCount;
3419#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003420 if (cracked.grad)
3421 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003422 if (cracked.lodClamp)
3423 ++nonBiasArgCount;
3424 if (sparse)
3425 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003426
3427 if ((int)arguments.size() > nonBiasArgCount)
3428 bias = true;
3429 }
3430
John Kessenicha5c33d62016-06-02 23:45:21 -06003431 // See if the sampler param should really be just the SPV image part
3432 if (cracked.fetch) {
3433 // a fetch needs to have the image extracted first
3434 if (builder.isSampledImage(params.sampler))
3435 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3436 }
3437
Rex Xu225e0fc2016-11-17 17:47:59 +08003438#ifdef AMD_EXTENSIONS
3439 if (cracked.gather) {
3440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3441 if (bias || cracked.lod ||
3442 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3443 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003444 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003445 }
3446 }
3447#endif
3448
John Kessenichfc51d282015-08-19 13:34:18 -06003449 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003450
John Kessenichfc51d282015-08-19 13:34:18 -06003451 params.coords = arguments[1];
3452 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003453 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003454
3455 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003456 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003457 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003458 ++extraArgs;
3459 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003460 params.Dref = arguments[2];
3461 ++extraArgs;
3462 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003463 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003464 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003465 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003466 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003467 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003468 dRefComp = builder.getNumComponents(params.coords) - 1;
3469 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003470 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3471 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003472
3473 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003474 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003475 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003476 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003477 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3478 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3479 noImplicitLod = true;
3480 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003481
3482 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003483 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003484 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003485 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003486 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003487
3488 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003489 if (cracked.grad) {
3490 params.gradX = arguments[2 + extraArgs];
3491 params.gradY = arguments[3 + extraArgs];
3492 extraArgs += 2;
3493 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003494
3495 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003496 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003497 params.offset = arguments[2 + extraArgs];
3498 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003499 } else if (cracked.offsets) {
3500 params.offsets = arguments[2 + extraArgs];
3501 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003502 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003503
3504 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003505 if (cracked.lodClamp) {
3506 params.lodClamp = arguments[2 + extraArgs];
3507 ++extraArgs;
3508 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003509
3510 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003511 if (sparse) {
3512 params.texelOut = arguments[2 + extraArgs];
3513 ++extraArgs;
3514 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003515
John Kessenich76d4dfc2016-06-16 12:43:23 -06003516 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003517 if (cracked.gather && ! sampler.shadow) {
3518 // default component is 0, if missing, otherwise an argument
3519 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003520 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003521 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003522 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003523 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003524 }
3525
3526 // bias
3527 if (bias) {
3528 params.bias = arguments[2 + extraArgs];
3529 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003530 }
John Kessenichfc51d282015-08-19 13:34:18 -06003531
John Kessenich65336482016-06-16 14:06:26 -06003532 // projective component (might not to move)
3533 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3534 // are divided by the last component of P."
3535 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3536 // unused components will appear after all used components."
3537 if (cracked.proj) {
3538 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3539 int projTargetComp;
3540 switch (sampler.dim) {
3541 case glslang::Esd1D: projTargetComp = 1; break;
3542 case glslang::Esd2D: projTargetComp = 2; break;
3543 case glslang::EsdRect: projTargetComp = 2; break;
3544 default: projTargetComp = projSourceComp; break;
3545 }
3546 // copy the projective coordinate if we have to
3547 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003548 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003549 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3550 projSourceComp);
3551 params.coords = builder.createCompositeInsert(projComp, params.coords,
3552 builder.getTypeId(params.coords), projTargetComp);
3553 }
3554 }
3555
John Kessenich8c8505c2016-07-26 12:50:38 -06003556 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003557}
3558
3559spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3560{
3561 // Grab the function's pointer from the previously created function
3562 spv::Function* function = functionMap[node->getName().c_str()];
3563 if (! function)
3564 return 0;
3565
3566 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3567 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3568
LoopDawg76117922017-09-06 14:59:06 -06003569 // Encapsulate lvalue logic, used in two places below, for safety.
3570 const auto isLValue = [](int qualifier, const glslang::TType& paramType) -> bool {
3571 return qualifier != glslang::EvqConstReadOnly || paramType.containsOpaque();
3572 };
3573
John Kessenich140f3df2015-06-26 16:58:36 -06003574 // See comments in makeFunctions() for details about the semantics for parameter passing.
3575 //
3576 // These imply we need a four step process:
3577 // 1. Evaluate the arguments
3578 // 2. Allocate and make copies of in, out, and inout arguments
3579 // 3. Make the call
3580 // 4. Copy back the results
3581
3582 // 1. Evaluate the arguments
3583 std::vector<spv::Builder::AccessChain> lValues;
3584 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003585 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003586 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003587 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003588 // build l-value
3589 builder.clearAccessChain();
3590 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003591 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003592 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
LoopDawg76117922017-09-06 14:59:06 -06003593 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003594 // save l-value
3595 lValues.push_back(builder.getAccessChain());
3596 } else {
3597 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003598 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003599 }
3600 }
3601
3602 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3603 // copy the original into that space.
3604 //
3605 // Also, build up the list of actual arguments to pass in for the call
3606 int lValueCount = 0;
3607 int rValueCount = 0;
3608 std::vector<spv::Id> spvArgs;
3609 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003610 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003611 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003612 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003613 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3614 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003615 builder.setAccessChain(lValues[lValueCount]);
3616 arg = builder.accessChainGetLValue();
3617 ++lValueCount;
LoopDawg76117922017-09-06 14:59:06 -06003618 } else if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003619 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003620 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3621 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3622 // need to copy the input into output space
3623 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003624 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003625 builder.clearAccessChain();
3626 builder.setAccessChainLValue(arg);
3627 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003628 }
3629 ++lValueCount;
3630 } else {
3631 arg = rValues[rValueCount];
3632 ++rValueCount;
3633 }
3634 spvArgs.push_back(arg);
3635 }
3636
3637 // 3. Make the call.
3638 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003639 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003640
3641 // 4. Copy back out an "out" arguments.
3642 lValueCount = 0;
3643 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003644 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
LoopDawg76117922017-09-06 14:59:06 -06003645 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003646 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3647 spv::Id copy = builder.createLoad(spvArgs[a]);
3648 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003649 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003650 }
3651 ++lValueCount;
3652 }
3653 }
3654
3655 return result;
3656}
3657
3658// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003659spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3660 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003661 spv::Id typeId, spv::Id left, spv::Id right,
3662 glslang::TBasicType typeProxy, bool reduceComparison)
3663{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003664#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003665 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003666 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3667#else
Rex Xucabbb782017-03-24 13:41:14 +08003668 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003669 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003670#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003671 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003672
3673 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003674 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003675 bool comparison = false;
3676
3677 switch (op) {
3678 case glslang::EOpAdd:
3679 case glslang::EOpAddAssign:
3680 if (isFloat)
3681 binOp = spv::OpFAdd;
3682 else
3683 binOp = spv::OpIAdd;
3684 break;
3685 case glslang::EOpSub:
3686 case glslang::EOpSubAssign:
3687 if (isFloat)
3688 binOp = spv::OpFSub;
3689 else
3690 binOp = spv::OpISub;
3691 break;
3692 case glslang::EOpMul:
3693 case glslang::EOpMulAssign:
3694 if (isFloat)
3695 binOp = spv::OpFMul;
3696 else
3697 binOp = spv::OpIMul;
3698 break;
3699 case glslang::EOpVectorTimesScalar:
3700 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003701 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003702 if (builder.isVector(right))
3703 std::swap(left, right);
3704 assert(builder.isScalar(right));
3705 needMatchingVectors = false;
3706 binOp = spv::OpVectorTimesScalar;
3707 } else
3708 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EOpVectorTimesMatrix:
3711 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003712 binOp = spv::OpVectorTimesMatrix;
3713 break;
3714 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003715 binOp = spv::OpMatrixTimesVector;
3716 break;
3717 case glslang::EOpMatrixTimesScalar:
3718 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003719 binOp = spv::OpMatrixTimesScalar;
3720 break;
3721 case glslang::EOpMatrixTimesMatrix:
3722 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003723 binOp = spv::OpMatrixTimesMatrix;
3724 break;
3725 case glslang::EOpOuterProduct:
3726 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003727 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729
3730 case glslang::EOpDiv:
3731 case glslang::EOpDivAssign:
3732 if (isFloat)
3733 binOp = spv::OpFDiv;
3734 else if (isUnsigned)
3735 binOp = spv::OpUDiv;
3736 else
3737 binOp = spv::OpSDiv;
3738 break;
3739 case glslang::EOpMod:
3740 case glslang::EOpModAssign:
3741 if (isFloat)
3742 binOp = spv::OpFMod;
3743 else if (isUnsigned)
3744 binOp = spv::OpUMod;
3745 else
3746 binOp = spv::OpSMod;
3747 break;
3748 case glslang::EOpRightShift:
3749 case glslang::EOpRightShiftAssign:
3750 if (isUnsigned)
3751 binOp = spv::OpShiftRightLogical;
3752 else
3753 binOp = spv::OpShiftRightArithmetic;
3754 break;
3755 case glslang::EOpLeftShift:
3756 case glslang::EOpLeftShiftAssign:
3757 binOp = spv::OpShiftLeftLogical;
3758 break;
3759 case glslang::EOpAnd:
3760 case glslang::EOpAndAssign:
3761 binOp = spv::OpBitwiseAnd;
3762 break;
3763 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003764 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 binOp = spv::OpLogicalAnd;
3766 break;
3767 case glslang::EOpInclusiveOr:
3768 case glslang::EOpInclusiveOrAssign:
3769 binOp = spv::OpBitwiseOr;
3770 break;
3771 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003772 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003773 binOp = spv::OpLogicalOr;
3774 break;
3775 case glslang::EOpExclusiveOr:
3776 case glslang::EOpExclusiveOrAssign:
3777 binOp = spv::OpBitwiseXor;
3778 break;
3779 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003780 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003781 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003782 break;
3783
3784 case glslang::EOpLessThan:
3785 case glslang::EOpGreaterThan:
3786 case glslang::EOpLessThanEqual:
3787 case glslang::EOpGreaterThanEqual:
3788 case glslang::EOpEqual:
3789 case glslang::EOpNotEqual:
3790 case glslang::EOpVectorEqual:
3791 case glslang::EOpVectorNotEqual:
3792 comparison = true;
3793 break;
3794 default:
3795 break;
3796 }
3797
John Kessenich7c1aa102015-10-15 13:29:11 -06003798 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003799 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003800 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003801 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003802 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003803
3804 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003805 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003806 builder.promoteScalar(precision, left, right);
3807
qining25262b32016-05-06 17:25:16 -04003808 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3809 addDecoration(result, noContraction);
3810 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003811 }
3812
3813 if (! comparison)
3814 return 0;
3815
John Kessenich7c1aa102015-10-15 13:29:11 -06003816 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003817
John Kessenich4583b612016-08-07 19:14:22 -06003818 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3819 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003820 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003821
3822 switch (op) {
3823 case glslang::EOpLessThan:
3824 if (isFloat)
3825 binOp = spv::OpFOrdLessThan;
3826 else if (isUnsigned)
3827 binOp = spv::OpULessThan;
3828 else
3829 binOp = spv::OpSLessThan;
3830 break;
3831 case glslang::EOpGreaterThan:
3832 if (isFloat)
3833 binOp = spv::OpFOrdGreaterThan;
3834 else if (isUnsigned)
3835 binOp = spv::OpUGreaterThan;
3836 else
3837 binOp = spv::OpSGreaterThan;
3838 break;
3839 case glslang::EOpLessThanEqual:
3840 if (isFloat)
3841 binOp = spv::OpFOrdLessThanEqual;
3842 else if (isUnsigned)
3843 binOp = spv::OpULessThanEqual;
3844 else
3845 binOp = spv::OpSLessThanEqual;
3846 break;
3847 case glslang::EOpGreaterThanEqual:
3848 if (isFloat)
3849 binOp = spv::OpFOrdGreaterThanEqual;
3850 else if (isUnsigned)
3851 binOp = spv::OpUGreaterThanEqual;
3852 else
3853 binOp = spv::OpSGreaterThanEqual;
3854 break;
3855 case glslang::EOpEqual:
3856 case glslang::EOpVectorEqual:
3857 if (isFloat)
3858 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003859 else if (isBool)
3860 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003861 else
3862 binOp = spv::OpIEqual;
3863 break;
3864 case glslang::EOpNotEqual:
3865 case glslang::EOpVectorNotEqual:
3866 if (isFloat)
3867 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003868 else if (isBool)
3869 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003870 else
3871 binOp = spv::OpINotEqual;
3872 break;
3873 default:
3874 break;
3875 }
3876
qining25262b32016-05-06 17:25:16 -04003877 if (binOp != spv::OpNop) {
3878 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3879 addDecoration(result, noContraction);
3880 return builder.setPrecision(result, precision);
3881 }
John Kessenich140f3df2015-06-26 16:58:36 -06003882
3883 return 0;
3884}
3885
John Kessenich04bb8a02015-12-12 12:28:14 -07003886//
3887// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3888// These can be any of:
3889//
3890// matrix * scalar
3891// scalar * matrix
3892// matrix * matrix linear algebraic
3893// matrix * vector
3894// vector * matrix
3895// matrix * matrix componentwise
3896// matrix op matrix op in {+, -, /}
3897// matrix op scalar op in {+, -, /}
3898// scalar op matrix op in {+, -, /}
3899//
qining25262b32016-05-06 17:25:16 -04003900spv::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 -07003901{
3902 bool firstClass = true;
3903
3904 // First, handle first-class matrix operations (* and matrix/scalar)
3905 switch (op) {
3906 case spv::OpFDiv:
3907 if (builder.isMatrix(left) && builder.isScalar(right)) {
3908 // turn matrix / scalar into a multiply...
3909 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3910 op = spv::OpMatrixTimesScalar;
3911 } else
3912 firstClass = false;
3913 break;
3914 case spv::OpMatrixTimesScalar:
3915 if (builder.isMatrix(right))
3916 std::swap(left, right);
3917 assert(builder.isScalar(right));
3918 break;
3919 case spv::OpVectorTimesMatrix:
3920 assert(builder.isVector(left));
3921 assert(builder.isMatrix(right));
3922 break;
3923 case spv::OpMatrixTimesVector:
3924 assert(builder.isMatrix(left));
3925 assert(builder.isVector(right));
3926 break;
3927 case spv::OpMatrixTimesMatrix:
3928 assert(builder.isMatrix(left));
3929 assert(builder.isMatrix(right));
3930 break;
3931 default:
3932 firstClass = false;
3933 break;
3934 }
3935
qining25262b32016-05-06 17:25:16 -04003936 if (firstClass) {
3937 spv::Id result = builder.createBinOp(op, typeId, left, right);
3938 addDecoration(result, noContraction);
3939 return builder.setPrecision(result, precision);
3940 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003941
LoopDawg592860c2016-06-09 08:57:35 -06003942 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003943 // The result type of all of them is the same type as the (a) matrix operand.
3944 // The algorithm is to:
3945 // - break the matrix(es) into vectors
3946 // - smear any scalar to a vector
3947 // - do vector operations
3948 // - make a matrix out the vector results
3949 switch (op) {
3950 case spv::OpFAdd:
3951 case spv::OpFSub:
3952 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003953 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003954 case spv::OpFMul:
3955 {
3956 // one time set up...
3957 bool leftMat = builder.isMatrix(left);
3958 bool rightMat = builder.isMatrix(right);
3959 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3960 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3961 spv::Id scalarType = builder.getScalarTypeId(typeId);
3962 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3963 std::vector<spv::Id> results;
3964 spv::Id smearVec = spv::NoResult;
3965 if (builder.isScalar(left))
3966 smearVec = builder.smearScalar(precision, left, vecType);
3967 else if (builder.isScalar(right))
3968 smearVec = builder.smearScalar(precision, right, vecType);
3969
3970 // do each vector op
3971 for (unsigned int c = 0; c < numCols; ++c) {
3972 std::vector<unsigned int> indexes;
3973 indexes.push_back(c);
3974 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3975 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003976 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3977 addDecoration(result, noContraction);
3978 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003979 }
3980
3981 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003982 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003983 }
3984 default:
3985 assert(0);
3986 return spv::NoResult;
3987 }
3988}
3989
qining25262b32016-05-06 17:25:16 -04003990spv::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 -06003991{
3992 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003993 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003994 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003995#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003996 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003997 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3998#else
Rex Xucabbb782017-03-24 13:41:14 +08003999 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004000 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004001#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004002
4003 switch (op) {
4004 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004005 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004006 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004007 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004008 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004009 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004010 unaryOp = spv::OpSNegate;
4011 break;
4012
4013 case glslang::EOpLogicalNot:
4014 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004015 unaryOp = spv::OpLogicalNot;
4016 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004017 case glslang::EOpBitwiseNot:
4018 unaryOp = spv::OpNot;
4019 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004020
John Kessenich140f3df2015-06-26 16:58:36 -06004021 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004022 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004023 break;
4024 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004025 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004026 break;
4027 case glslang::EOpTranspose:
4028 unaryOp = spv::OpTranspose;
4029 break;
4030
4031 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004032 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004033 break;
4034 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004035 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004036 break;
4037 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004038 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004039 break;
4040 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004041 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004042 break;
4043 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004044 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004045 break;
4046 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004047 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004048 break;
4049 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055
4056 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004058 break;
4059 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004060 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004061 break;
4062 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004063 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004064 break;
4065 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004067 break;
4068 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004069 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004070 break;
4071 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004072 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074
4075 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004076 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004079 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004080 break;
4081
4082 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004083 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004084 break;
4085 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004086 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004087 break;
4088 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004089 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004090 break;
4091 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004092 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004093 break;
4094 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004095 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004096 break;
4097 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004098 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004099 break;
4100
4101 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004102 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 break;
4104 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004105 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004106 break;
4107 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004108 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004109 break;
4110 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004111 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004112 break;
4113 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004114 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004118 break;
4119
4120 case glslang::EOpIsNan:
4121 unaryOp = spv::OpIsNan;
4122 break;
4123 case glslang::EOpIsInf:
4124 unaryOp = spv::OpIsInf;
4125 break;
LoopDawg592860c2016-06-09 08:57:35 -06004126 case glslang::EOpIsFinite:
4127 unaryOp = spv::OpIsFinite;
4128 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004129
Rex Xucbc426e2015-12-15 16:03:10 +08004130 case glslang::EOpFloatBitsToInt:
4131 case glslang::EOpFloatBitsToUint:
4132 case glslang::EOpIntBitsToFloat:
4133 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004134 case glslang::EOpDoubleBitsToInt64:
4135 case glslang::EOpDoubleBitsToUint64:
4136 case glslang::EOpInt64BitsToDouble:
4137 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004138#ifdef AMD_EXTENSIONS
4139 case glslang::EOpFloat16BitsToInt16:
4140 case glslang::EOpFloat16BitsToUint16:
4141 case glslang::EOpInt16BitsToFloat16:
4142 case glslang::EOpUint16BitsToFloat16:
4143#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004144 unaryOp = spv::OpBitcast;
4145 break;
4146
John Kessenich140f3df2015-06-26 16:58:36 -06004147 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004148 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004154 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004155 break;
4156 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004157 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004158 break;
4159 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004160 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004161 break;
4162 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004163 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004164 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004165 case glslang::EOpPackSnorm4x8:
4166 libCall = spv::GLSLstd450PackSnorm4x8;
4167 break;
4168 case glslang::EOpUnpackSnorm4x8:
4169 libCall = spv::GLSLstd450UnpackSnorm4x8;
4170 break;
4171 case glslang::EOpPackUnorm4x8:
4172 libCall = spv::GLSLstd450PackUnorm4x8;
4173 break;
4174 case glslang::EOpUnpackUnorm4x8:
4175 libCall = spv::GLSLstd450UnpackUnorm4x8;
4176 break;
4177 case glslang::EOpPackDouble2x32:
4178 libCall = spv::GLSLstd450PackDouble2x32;
4179 break;
4180 case glslang::EOpUnpackDouble2x32:
4181 libCall = spv::GLSLstd450UnpackDouble2x32;
4182 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004183
Rex Xu8ff43de2016-04-22 16:51:45 +08004184 case glslang::EOpPackInt2x32:
4185 case glslang::EOpUnpackInt2x32:
4186 case glslang::EOpPackUint2x32:
4187 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004188 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004189 break;
4190
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004191#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004192 case glslang::EOpPackInt2x16:
4193 case glslang::EOpUnpackInt2x16:
4194 case glslang::EOpPackUint2x16:
4195 case glslang::EOpUnpackUint2x16:
4196 case glslang::EOpPackInt4x16:
4197 case glslang::EOpUnpackInt4x16:
4198 case glslang::EOpPackUint4x16:
4199 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004200 case glslang::EOpPackFloat2x16:
4201 case glslang::EOpUnpackFloat2x16:
4202 unaryOp = spv::OpBitcast;
4203 break;
4204#endif
4205
John Kessenich140f3df2015-06-26 16:58:36 -06004206 case glslang::EOpDPdx:
4207 unaryOp = spv::OpDPdx;
4208 break;
4209 case glslang::EOpDPdy:
4210 unaryOp = spv::OpDPdy;
4211 break;
4212 case glslang::EOpFwidth:
4213 unaryOp = spv::OpFwidth;
4214 break;
4215 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004216 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004217 unaryOp = spv::OpDPdxFine;
4218 break;
4219 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004220 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004221 unaryOp = spv::OpDPdyFine;
4222 break;
4223 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004224 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004225 unaryOp = spv::OpFwidthFine;
4226 break;
4227 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004228 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004229 unaryOp = spv::OpDPdxCoarse;
4230 break;
4231 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004232 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004233 unaryOp = spv::OpDPdyCoarse;
4234 break;
4235 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004236 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004237 unaryOp = spv::OpFwidthCoarse;
4238 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004239 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004240 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004241 libCall = spv::GLSLstd450InterpolateAtCentroid;
4242 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004243 case glslang::EOpAny:
4244 unaryOp = spv::OpAny;
4245 break;
4246 case glslang::EOpAll:
4247 unaryOp = spv::OpAll;
4248 break;
4249
4250 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004251 if (isFloat)
4252 libCall = spv::GLSLstd450FAbs;
4253 else
4254 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004255 break;
4256 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004257 if (isFloat)
4258 libCall = spv::GLSLstd450FSign;
4259 else
4260 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004261 break;
4262
John Kessenichfc51d282015-08-19 13:34:18 -06004263 case glslang::EOpAtomicCounterIncrement:
4264 case glslang::EOpAtomicCounterDecrement:
4265 case glslang::EOpAtomicCounter:
4266 {
4267 // Handle all of the atomics in one place, in createAtomicOperation()
4268 std::vector<spv::Id> operands;
4269 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004270 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004271 }
4272
John Kessenichfc51d282015-08-19 13:34:18 -06004273 case glslang::EOpBitFieldReverse:
4274 unaryOp = spv::OpBitReverse;
4275 break;
4276 case glslang::EOpBitCount:
4277 unaryOp = spv::OpBitCount;
4278 break;
4279 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004280 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004281 break;
4282 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004283 if (isUnsigned)
4284 libCall = spv::GLSLstd450FindUMsb;
4285 else
4286 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004287 break;
4288
Rex Xu574ab042016-04-14 16:53:07 +08004289 case glslang::EOpBallot:
4290 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004291 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004292 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004293 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004294#ifdef AMD_EXTENSIONS
4295 case glslang::EOpMinInvocations:
4296 case glslang::EOpMaxInvocations:
4297 case glslang::EOpAddInvocations:
4298 case glslang::EOpMinInvocationsNonUniform:
4299 case glslang::EOpMaxInvocationsNonUniform:
4300 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004301 case glslang::EOpMinInvocationsInclusiveScan:
4302 case glslang::EOpMaxInvocationsInclusiveScan:
4303 case glslang::EOpAddInvocationsInclusiveScan:
4304 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4305 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4306 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4307 case glslang::EOpMinInvocationsExclusiveScan:
4308 case glslang::EOpMaxInvocationsExclusiveScan:
4309 case glslang::EOpAddInvocationsExclusiveScan:
4310 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4311 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4312 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004313#endif
Rex Xu51596642016-09-21 18:56:12 +08004314 {
4315 std::vector<spv::Id> operands;
4316 operands.push_back(operand);
4317 return createInvocationsOperation(op, typeId, operands, typeProxy);
4318 }
Rex Xu9d93a232016-05-05 12:30:44 +08004319
4320#ifdef AMD_EXTENSIONS
4321 case glslang::EOpMbcnt:
4322 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4323 libCall = spv::MbcntAMD;
4324 break;
4325
4326 case glslang::EOpCubeFaceIndex:
4327 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4328 libCall = spv::CubeFaceIndexAMD;
4329 break;
4330
4331 case glslang::EOpCubeFaceCoord:
4332 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4333 libCall = spv::CubeFaceCoordAMD;
4334 break;
4335#endif
Rex Xu338b1852016-05-05 20:38:33 +08004336
John Kessenich140f3df2015-06-26 16:58:36 -06004337 default:
4338 return 0;
4339 }
4340
4341 spv::Id id;
4342 if (libCall >= 0) {
4343 std::vector<spv::Id> args;
4344 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004345 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004346 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004347 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004348 }
John Kessenich140f3df2015-06-26 16:58:36 -06004349
qining25262b32016-05-06 17:25:16 -04004350 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004351 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004352}
4353
John Kessenich7a53f762016-01-20 11:19:27 -07004354// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004355spv::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 -07004356{
4357 // Handle unary operations vector by vector.
4358 // The result type is the same type as the original type.
4359 // The algorithm is to:
4360 // - break the matrix into vectors
4361 // - apply the operation to each vector
4362 // - make a matrix out the vector results
4363
4364 // get the types sorted out
4365 int numCols = builder.getNumColumns(operand);
4366 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004367 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4368 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004369 std::vector<spv::Id> results;
4370
4371 // do each vector op
4372 for (int c = 0; c < numCols; ++c) {
4373 std::vector<unsigned int> indexes;
4374 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004375 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4376 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4377 addDecoration(destVec, noContraction);
4378 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004379 }
4380
4381 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004382 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004383}
4384
Rex Xu73e3ce72016-04-27 18:48:17 +08004385spv::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 -06004386{
4387 spv::Op convOp = spv::OpNop;
4388 spv::Id zero = 0;
4389 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004390 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004391
4392 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4393
4394 switch (op) {
4395 case glslang::EOpConvIntToBool:
4396 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004397 case glslang::EOpConvInt64ToBool:
4398 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004399#ifdef AMD_EXTENSIONS
4400 case glslang::EOpConvInt16ToBool:
4401 case glslang::EOpConvUint16ToBool:
4402#endif
4403 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4404 zero = builder.makeUint64Constant(0);
4405#ifdef AMD_EXTENSIONS
4406 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4407 zero = builder.makeUint16Constant(0);
4408#endif
4409 else
4410 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004411 zero = makeSmearedConstant(zero, vectorSize);
4412 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4413
4414 case glslang::EOpConvFloatToBool:
4415 zero = builder.makeFloatConstant(0.0F);
4416 zero = makeSmearedConstant(zero, vectorSize);
4417 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4418
4419 case glslang::EOpConvDoubleToBool:
4420 zero = builder.makeDoubleConstant(0.0);
4421 zero = makeSmearedConstant(zero, vectorSize);
4422 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4423
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004424#ifdef AMD_EXTENSIONS
4425 case glslang::EOpConvFloat16ToBool:
4426 zero = builder.makeFloat16Constant(0.0F);
4427 zero = makeSmearedConstant(zero, vectorSize);
4428 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4429#endif
4430
John Kessenich140f3df2015-06-26 16:58:36 -06004431 case glslang::EOpConvBoolToFloat:
4432 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004433 zero = builder.makeFloatConstant(0.0F);
4434 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004435 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004436
John Kessenich140f3df2015-06-26 16:58:36 -06004437 case glslang::EOpConvBoolToDouble:
4438 convOp = spv::OpSelect;
4439 zero = builder.makeDoubleConstant(0.0);
4440 one = builder.makeDoubleConstant(1.0);
4441 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004442
4443#ifdef AMD_EXTENSIONS
4444 case glslang::EOpConvBoolToFloat16:
4445 convOp = spv::OpSelect;
4446 zero = builder.makeFloat16Constant(0.0F);
4447 one = builder.makeFloat16Constant(1.0F);
4448 break;
4449#endif
4450
John Kessenich140f3df2015-06-26 16:58:36 -06004451 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004452 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004453#ifdef AMD_EXTENSIONS
4454 case glslang::EOpConvBoolToInt16:
4455#endif
4456 if (op == glslang::EOpConvBoolToInt64)
4457 zero = builder.makeInt64Constant(0);
4458#ifdef AMD_EXTENSIONS
4459 else if (op == glslang::EOpConvBoolToInt16)
4460 zero = builder.makeInt16Constant(0);
4461#endif
4462 else
4463 zero = builder.makeIntConstant(0);
4464
4465 if (op == glslang::EOpConvBoolToInt64)
4466 one = builder.makeInt64Constant(1);
4467#ifdef AMD_EXTENSIONS
4468 else if (op == glslang::EOpConvBoolToInt16)
4469 one = builder.makeInt16Constant(1);
4470#endif
4471 else
4472 one = builder.makeIntConstant(1);
4473
John Kessenich140f3df2015-06-26 16:58:36 -06004474 convOp = spv::OpSelect;
4475 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004476
John Kessenich140f3df2015-06-26 16:58:36 -06004477 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004478 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004479#ifdef AMD_EXTENSIONS
4480 case glslang::EOpConvBoolToUint16:
4481#endif
4482 if (op == glslang::EOpConvBoolToUint64)
4483 zero = builder.makeUint64Constant(0);
4484#ifdef AMD_EXTENSIONS
4485 else if (op == glslang::EOpConvBoolToUint16)
4486 zero = builder.makeUint16Constant(0);
4487#endif
4488 else
4489 zero = builder.makeUintConstant(0);
4490
4491 if (op == glslang::EOpConvBoolToUint64)
4492 one = builder.makeUint64Constant(1);
4493#ifdef AMD_EXTENSIONS
4494 else if (op == glslang::EOpConvBoolToUint16)
4495 one = builder.makeUint16Constant(1);
4496#endif
4497 else
4498 one = builder.makeUintConstant(1);
4499
John Kessenich140f3df2015-06-26 16:58:36 -06004500 convOp = spv::OpSelect;
4501 break;
4502
4503 case glslang::EOpConvIntToFloat:
4504 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004505 case glslang::EOpConvInt64ToFloat:
4506 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004507#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004508 case glslang::EOpConvInt16ToFloat:
4509 case glslang::EOpConvInt16ToDouble:
4510 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004511 case glslang::EOpConvIntToFloat16:
4512 case glslang::EOpConvInt64ToFloat16:
4513#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004514 convOp = spv::OpConvertSToF;
4515 break;
4516
4517 case glslang::EOpConvUintToFloat:
4518 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004519 case glslang::EOpConvUint64ToFloat:
4520 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004521#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004522 case glslang::EOpConvUint16ToFloat:
4523 case glslang::EOpConvUint16ToDouble:
4524 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004525 case glslang::EOpConvUintToFloat16:
4526 case glslang::EOpConvUint64ToFloat16:
4527#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004528 convOp = spv::OpConvertUToF;
4529 break;
4530
4531 case glslang::EOpConvDoubleToFloat:
4532 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004533#ifdef AMD_EXTENSIONS
4534 case glslang::EOpConvDoubleToFloat16:
4535 case glslang::EOpConvFloat16ToDouble:
4536 case glslang::EOpConvFloatToFloat16:
4537 case glslang::EOpConvFloat16ToFloat:
4538#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004539 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004540 if (builder.isMatrixType(destType))
4541 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004542 break;
4543
4544 case glslang::EOpConvFloatToInt:
4545 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004546 case glslang::EOpConvFloatToInt64:
4547 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004548#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004549 case glslang::EOpConvFloatToInt16:
4550 case glslang::EOpConvDoubleToInt16:
4551 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004552 case glslang::EOpConvFloat16ToInt:
4553 case glslang::EOpConvFloat16ToInt64:
4554#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004555 convOp = spv::OpConvertFToS;
4556 break;
4557
4558 case glslang::EOpConvUintToInt:
4559 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004560 case glslang::EOpConvUint64ToInt64:
4561 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004562#ifdef AMD_EXTENSIONS
4563 case glslang::EOpConvUint16ToInt16:
4564 case glslang::EOpConvInt16ToUint16:
4565#endif
qininge24aa5e2016-04-07 15:40:27 -04004566 if (builder.isInSpecConstCodeGenMode()) {
4567 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004568 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4569 zero = builder.makeUint64Constant(0);
4570#ifdef AMD_EXTENSIONS
4571 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4572 zero = builder.makeUint16Constant(0);
4573#endif
4574 else
4575 zero = builder.makeUintConstant(0);
4576
qining189b2032016-04-12 23:16:20 -04004577 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004578 // Use OpIAdd, instead of OpBitcast to do the conversion when
4579 // generating for OpSpecConstantOp instruction.
4580 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4581 }
4582 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004583 convOp = spv::OpBitcast;
4584 break;
4585
4586 case glslang::EOpConvFloatToUint:
4587 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004588 case glslang::EOpConvFloatToUint64:
4589 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004590#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004591 case glslang::EOpConvFloatToUint16:
4592 case glslang::EOpConvDoubleToUint16:
4593 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004594 case glslang::EOpConvFloat16ToUint:
4595 case glslang::EOpConvFloat16ToUint64:
4596#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004597 convOp = spv::OpConvertFToU;
4598 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004599
4600 case glslang::EOpConvIntToInt64:
4601 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004602#ifdef AMD_EXTENSIONS
4603 case glslang::EOpConvIntToInt16:
4604 case glslang::EOpConvInt16ToInt:
4605 case glslang::EOpConvInt64ToInt16:
4606 case glslang::EOpConvInt16ToInt64:
4607#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004608 convOp = spv::OpSConvert;
4609 break;
4610
4611 case glslang::EOpConvUintToUint64:
4612 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004613#ifdef AMD_EXTENSIONS
4614 case glslang::EOpConvUintToUint16:
4615 case glslang::EOpConvUint16ToUint:
4616 case glslang::EOpConvUint64ToUint16:
4617 case glslang::EOpConvUint16ToUint64:
4618#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004619 convOp = spv::OpUConvert;
4620 break;
4621
4622 case glslang::EOpConvIntToUint64:
4623 case glslang::EOpConvInt64ToUint:
4624 case glslang::EOpConvUint64ToInt:
4625 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004626#ifdef AMD_EXTENSIONS
4627 case glslang::EOpConvInt16ToUint:
4628 case glslang::EOpConvUintToInt16:
4629 case glslang::EOpConvInt16ToUint64:
4630 case glslang::EOpConvUint64ToInt16:
4631 case glslang::EOpConvUint16ToInt:
4632 case glslang::EOpConvIntToUint16:
4633 case glslang::EOpConvUint16ToInt64:
4634 case glslang::EOpConvInt64ToUint16:
4635#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004636 // OpSConvert/OpUConvert + OpBitCast
4637 switch (op) {
4638 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004639#ifdef AMD_EXTENSIONS
4640 case glslang::EOpConvInt16ToUint64:
4641#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004642 convOp = spv::OpSConvert;
4643 type = builder.makeIntType(64);
4644 break;
4645 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004646#ifdef AMD_EXTENSIONS
4647 case glslang::EOpConvInt16ToUint:
4648#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004649 convOp = spv::OpSConvert;
4650 type = builder.makeIntType(32);
4651 break;
4652 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004653#ifdef AMD_EXTENSIONS
4654 case glslang::EOpConvUint16ToInt:
4655#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004656 convOp = spv::OpUConvert;
4657 type = builder.makeUintType(32);
4658 break;
4659 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004660#ifdef AMD_EXTENSIONS
4661 case glslang::EOpConvUint16ToInt64:
4662#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004663 convOp = spv::OpUConvert;
4664 type = builder.makeUintType(64);
4665 break;
Rex Xucabbb782017-03-24 13:41:14 +08004666#ifdef AMD_EXTENSIONS
4667 case glslang::EOpConvUintToInt16:
4668 case glslang::EOpConvUint64ToInt16:
4669 convOp = spv::OpUConvert;
4670 type = builder.makeUintType(16);
4671 break;
4672 case glslang::EOpConvIntToUint16:
4673 case glslang::EOpConvInt64ToUint16:
4674 convOp = spv::OpSConvert;
4675 type = builder.makeIntType(16);
4676 break;
4677#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004678 default:
4679 assert(0);
4680 break;
4681 }
4682
4683 if (vectorSize > 0)
4684 type = builder.makeVectorType(type, vectorSize);
4685
4686 operand = builder.createUnaryOp(convOp, type, operand);
4687
4688 if (builder.isInSpecConstCodeGenMode()) {
4689 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004690#ifdef AMD_EXTENSIONS
4691 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4692 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4693 zero = builder.makeUint64Constant(0);
4694 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4695 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4696 zero = builder.makeUint16Constant(0);
4697 else
4698 zero = builder.makeUintConstant(0);
4699#else
4700 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4701 zero = builder.makeUint64Constant(0);
4702 else
4703 zero = builder.makeUintConstant(0);
4704#endif
4705
Rex Xu8ff43de2016-04-22 16:51:45 +08004706 zero = makeSmearedConstant(zero, vectorSize);
4707 // Use OpIAdd, instead of OpBitcast to do the conversion when
4708 // generating for OpSpecConstantOp instruction.
4709 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4710 }
4711 // For normal run-time conversion instruction, use OpBitcast.
4712 convOp = spv::OpBitcast;
4713 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004714 default:
4715 break;
4716 }
4717
4718 spv::Id result = 0;
4719 if (convOp == spv::OpNop)
4720 return result;
4721
4722 if (convOp == spv::OpSelect) {
4723 zero = makeSmearedConstant(zero, vectorSize);
4724 one = makeSmearedConstant(one, vectorSize);
4725 result = builder.createTriOp(convOp, destType, operand, one, zero);
4726 } else
4727 result = builder.createUnaryOp(convOp, destType, operand);
4728
John Kessenich32cfd492016-02-02 12:37:46 -07004729 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004730}
4731
4732spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4733{
4734 if (vectorSize == 0)
4735 return constant;
4736
4737 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4738 std::vector<spv::Id> components;
4739 for (int c = 0; c < vectorSize; ++c)
4740 components.push_back(constant);
4741 return builder.makeCompositeConstant(vectorTypeId, components);
4742}
4743
John Kessenich426394d2015-07-23 10:22:48 -06004744// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004745spv::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 -06004746{
4747 spv::Op opCode = spv::OpNop;
4748
4749 switch (op) {
4750 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004751 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004752 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004753 opCode = spv::OpAtomicIAdd;
4754 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004755 case glslang::EOpAtomicCounterSubtract:
4756 opCode = spv::OpAtomicISub;
4757 break;
John Kessenich426394d2015-07-23 10:22:48 -06004758 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004759 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004760 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004761 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004762 break;
4763 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004764 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004765 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004766 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004767 break;
4768 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004769 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004770 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004771 opCode = spv::OpAtomicAnd;
4772 break;
4773 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004774 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004775 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004776 opCode = spv::OpAtomicOr;
4777 break;
4778 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004779 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004780 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004781 opCode = spv::OpAtomicXor;
4782 break;
4783 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004784 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004785 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004786 opCode = spv::OpAtomicExchange;
4787 break;
4788 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004789 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004790 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004791 opCode = spv::OpAtomicCompareExchange;
4792 break;
4793 case glslang::EOpAtomicCounterIncrement:
4794 opCode = spv::OpAtomicIIncrement;
4795 break;
4796 case glslang::EOpAtomicCounterDecrement:
4797 opCode = spv::OpAtomicIDecrement;
4798 break;
4799 case glslang::EOpAtomicCounter:
4800 opCode = spv::OpAtomicLoad;
4801 break;
4802 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004803 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004804 break;
4805 }
4806
4807 // Sort out the operands
4808 // - mapping from glslang -> SPV
4809 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004810 // - compare-exchange swaps the value and comparator
4811 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004812 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4813 auto opIt = operands.begin(); // walk the glslang operands
4814 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004815 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4816 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4817 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004818 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4819 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004820 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004821 spvAtomicOperands.push_back(*(opIt + 1));
4822 spvAtomicOperands.push_back(*opIt);
4823 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004824 }
John Kessenich426394d2015-07-23 10:22:48 -06004825
John Kessenich3e60a6f2015-09-14 22:45:16 -06004826 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004827 for (; opIt != operands.end(); ++opIt)
4828 spvAtomicOperands.push_back(*opIt);
4829
4830 return builder.createOp(opCode, typeId, spvAtomicOperands);
4831}
4832
John Kessenich91cef522016-05-05 16:45:40 -06004833// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004834spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004835{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004836#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004837 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004838 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004839#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004840
Rex Xu51596642016-09-21 18:56:12 +08004841 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004842 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004843 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4844
chaocf200da82016-12-20 12:44:35 -08004845 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4846 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004847 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4848 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004849 } else if (op == glslang::EOpAnyInvocation ||
4850 op == glslang::EOpAllInvocations ||
4851 op == glslang::EOpAllInvocationsEqual) {
4852 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4853 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004854 } else {
4855 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004856#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004857 if (op == glslang::EOpMinInvocationsNonUniform ||
4858 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004859 op == glslang::EOpAddInvocationsNonUniform ||
4860 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4861 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4862 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4863 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4864 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4865 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004866 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004867#endif
Rex Xu51596642016-09-21 18:56:12 +08004868
4869 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004870#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004871 switch (op) {
4872 case glslang::EOpMinInvocations:
4873 case glslang::EOpMaxInvocations:
4874 case glslang::EOpAddInvocations:
4875 case glslang::EOpMinInvocationsNonUniform:
4876 case glslang::EOpMaxInvocationsNonUniform:
4877 case glslang::EOpAddInvocationsNonUniform:
4878 groupOperation = spv::GroupOperationReduce;
4879 spvGroupOperands.push_back(groupOperation);
4880 break;
4881 case glslang::EOpMinInvocationsInclusiveScan:
4882 case glslang::EOpMaxInvocationsInclusiveScan:
4883 case glslang::EOpAddInvocationsInclusiveScan:
4884 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4885 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4886 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4887 groupOperation = spv::GroupOperationInclusiveScan;
4888 spvGroupOperands.push_back(groupOperation);
4889 break;
4890 case glslang::EOpMinInvocationsExclusiveScan:
4891 case glslang::EOpMaxInvocationsExclusiveScan:
4892 case glslang::EOpAddInvocationsExclusiveScan:
4893 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4894 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4895 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4896 groupOperation = spv::GroupOperationExclusiveScan;
4897 spvGroupOperands.push_back(groupOperation);
4898 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004899 default:
4900 break;
Rex Xu430ef402016-10-14 17:22:23 +08004901 }
Rex Xu9d93a232016-05-05 12:30:44 +08004902#endif
Rex Xu51596642016-09-21 18:56:12 +08004903 }
4904
4905 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4906 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004907
4908 switch (op) {
4909 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004910 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004911 break;
John Kessenich91cef522016-05-05 16:45:40 -06004912 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004913 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004914 break;
John Kessenich91cef522016-05-05 16:45:40 -06004915 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004916 opCode = spv::OpSubgroupAllEqualKHR;
4917 break;
Rex Xu51596642016-09-21 18:56:12 +08004918 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004919 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004920 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004921 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004922 break;
4923 case glslang::EOpReadFirstInvocation:
4924 opCode = spv::OpSubgroupFirstInvocationKHR;
4925 break;
4926 case glslang::EOpBallot:
4927 {
4928 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4929 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4930 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4931 //
4932 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4933 //
4934 spv::Id uintType = builder.makeUintType(32);
4935 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4936 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4937
4938 std::vector<spv::Id> components;
4939 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4940 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4941
4942 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4943 return builder.createUnaryOp(spv::OpBitcast, typeId,
4944 builder.createCompositeConstruct(uvec2Type, components));
4945 }
4946
Rex Xu9d93a232016-05-05 12:30:44 +08004947#ifdef AMD_EXTENSIONS
4948 case glslang::EOpMinInvocations:
4949 case glslang::EOpMaxInvocations:
4950 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004951 case glslang::EOpMinInvocationsInclusiveScan:
4952 case glslang::EOpMaxInvocationsInclusiveScan:
4953 case glslang::EOpAddInvocationsInclusiveScan:
4954 case glslang::EOpMinInvocationsExclusiveScan:
4955 case glslang::EOpMaxInvocationsExclusiveScan:
4956 case glslang::EOpAddInvocationsExclusiveScan:
4957 if (op == glslang::EOpMinInvocations ||
4958 op == glslang::EOpMinInvocationsInclusiveScan ||
4959 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004960 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004961 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004962 else {
4963 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004964 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004965 else
Rex Xu51596642016-09-21 18:56:12 +08004966 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004967 }
Rex Xu430ef402016-10-14 17:22:23 +08004968 } else if (op == glslang::EOpMaxInvocations ||
4969 op == glslang::EOpMaxInvocationsInclusiveScan ||
4970 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004971 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004972 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004973 else {
4974 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004975 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004976 else
Rex Xu51596642016-09-21 18:56:12 +08004977 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004978 }
4979 } else {
4980 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004981 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004982 else
Rex Xu51596642016-09-21 18:56:12 +08004983 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004984 }
4985
Rex Xu2bbbe062016-08-23 15:41:05 +08004986 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004987 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004988
4989 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004990 case glslang::EOpMinInvocationsNonUniform:
4991 case glslang::EOpMaxInvocationsNonUniform:
4992 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004993 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4994 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4995 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4996 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4997 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4998 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4999 if (op == glslang::EOpMinInvocationsNonUniform ||
5000 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5001 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005002 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005003 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005004 else {
5005 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005006 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005007 else
Rex Xu51596642016-09-21 18:56:12 +08005008 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005009 }
5010 }
Rex Xu430ef402016-10-14 17:22:23 +08005011 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5012 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5013 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005014 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005015 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005016 else {
5017 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005018 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005019 else
Rex Xu51596642016-09-21 18:56:12 +08005020 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005021 }
5022 }
5023 else {
5024 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005025 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005026 else
Rex Xu51596642016-09-21 18:56:12 +08005027 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005028 }
5029
Rex Xu2bbbe062016-08-23 15:41:05 +08005030 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005031 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005032
5033 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005034#endif
John Kessenich91cef522016-05-05 16:45:40 -06005035 default:
5036 logger->missingFunctionality("invocation operation");
5037 return spv::NoResult;
5038 }
Rex Xu51596642016-09-21 18:56:12 +08005039
5040 assert(opCode != spv::OpNop);
5041 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005042}
5043
Rex Xu2bbbe062016-08-23 15:41:05 +08005044// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005045spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005046{
Rex Xub7072052016-09-26 15:53:40 +08005047#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005048 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5049 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005050 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005051 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005052 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5053 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5054 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005055#else
5056 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5057 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005058 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5059 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005060#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005061
5062 // Handle group invocation operations scalar by scalar.
5063 // The result type is the same type as the original type.
5064 // The algorithm is to:
5065 // - break the vector into scalars
5066 // - apply the operation to each scalar
5067 // - make a vector out the scalar results
5068
5069 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005070 int numComponents = builder.getNumComponents(operands[0]);
5071 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005072 std::vector<spv::Id> results;
5073
5074 // do each scalar op
5075 for (int comp = 0; comp < numComponents; ++comp) {
5076 std::vector<unsigned int> indexes;
5077 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005078 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005079 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005080 if (op == spv::OpSubgroupReadInvocationKHR) {
5081 spvGroupOperands.push_back(scalar);
5082 spvGroupOperands.push_back(operands[1]);
5083 } else if (op == spv::OpGroupBroadcast) {
5084 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005085 spvGroupOperands.push_back(scalar);
5086 spvGroupOperands.push_back(operands[1]);
5087 } else {
chaocf200da82016-12-20 12:44:35 -08005088 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005089 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005090 spvGroupOperands.push_back(scalar);
5091 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005092
Rex Xub7072052016-09-26 15:53:40 +08005093 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005094 }
5095
5096 // put the pieces together
5097 return builder.createCompositeConstruct(typeId, results);
5098}
Rex Xu2bbbe062016-08-23 15:41:05 +08005099
John Kessenich5e4b1242015-08-06 22:53:06 -06005100spv::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 -06005101{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005102#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005103 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005104 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5105#else
Rex Xucabbb782017-03-24 13:41:14 +08005106 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005107 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005108#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005109
John Kessenich140f3df2015-06-26 16:58:36 -06005110 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005111 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005112 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005113 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005114 spv::Id typeId0 = 0;
5115 if (consumedOperands > 0)
5116 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005117 spv::Id typeId1 = 0;
5118 if (consumedOperands > 1)
5119 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005120 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005121
5122 switch (op) {
5123 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005124 if (isFloat)
5125 libCall = spv::GLSLstd450FMin;
5126 else if (isUnsigned)
5127 libCall = spv::GLSLstd450UMin;
5128 else
5129 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005130 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005131 break;
5132 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005133 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005134 break;
5135 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005136 if (isFloat)
5137 libCall = spv::GLSLstd450FMax;
5138 else if (isUnsigned)
5139 libCall = spv::GLSLstd450UMax;
5140 else
5141 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005142 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005143 break;
5144 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005145 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005146 break;
5147 case glslang::EOpDot:
5148 opCode = spv::OpDot;
5149 break;
5150 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005151 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005152 break;
5153
5154 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005155 if (isFloat)
5156 libCall = spv::GLSLstd450FClamp;
5157 else if (isUnsigned)
5158 libCall = spv::GLSLstd450UClamp;
5159 else
5160 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005161 builder.promoteScalar(precision, operands.front(), operands[1]);
5162 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005163 break;
5164 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005165 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5166 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005167 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005168 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005169 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005170 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005171 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005172 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005173 break;
5174 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005175 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005176 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005177 break;
5178 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005179 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005180 builder.promoteScalar(precision, operands[0], operands[2]);
5181 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183
5184 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005185 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005186 break;
5187 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005188 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 break;
5190 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005191 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005192 break;
5193 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005194 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005195 break;
5196 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005197 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005198 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005199 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005200 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005201 libCall = spv::GLSLstd450InterpolateAtSample;
5202 break;
5203 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005204 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005205 libCall = spv::GLSLstd450InterpolateAtOffset;
5206 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005207 case glslang::EOpAddCarry:
5208 opCode = spv::OpIAddCarry;
5209 typeId = builder.makeStructResultType(typeId0, typeId0);
5210 consumedOperands = 2;
5211 break;
5212 case glslang::EOpSubBorrow:
5213 opCode = spv::OpISubBorrow;
5214 typeId = builder.makeStructResultType(typeId0, typeId0);
5215 consumedOperands = 2;
5216 break;
5217 case glslang::EOpUMulExtended:
5218 opCode = spv::OpUMulExtended;
5219 typeId = builder.makeStructResultType(typeId0, typeId0);
5220 consumedOperands = 2;
5221 break;
5222 case glslang::EOpIMulExtended:
5223 opCode = spv::OpSMulExtended;
5224 typeId = builder.makeStructResultType(typeId0, typeId0);
5225 consumedOperands = 2;
5226 break;
5227 case glslang::EOpBitfieldExtract:
5228 if (isUnsigned)
5229 opCode = spv::OpBitFieldUExtract;
5230 else
5231 opCode = spv::OpBitFieldSExtract;
5232 break;
5233 case glslang::EOpBitfieldInsert:
5234 opCode = spv::OpBitFieldInsert;
5235 break;
5236
5237 case glslang::EOpFma:
5238 libCall = spv::GLSLstd450Fma;
5239 break;
5240 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005241 {
5242 libCall = spv::GLSLstd450FrexpStruct;
5243 assert(builder.isPointerType(typeId1));
5244 typeId1 = builder.getContainedTypeId(typeId1);
5245#ifdef AMD_EXTENSIONS
5246 int width = builder.getScalarTypeWidth(typeId1);
5247#else
5248 int width = 32;
5249#endif
5250 if (builder.getNumComponents(operands[0]) == 1)
5251 frexpIntType = builder.makeIntegerType(width, true);
5252 else
5253 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5254 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5255 consumedOperands = 1;
5256 }
John Kessenich55e7d112015-11-15 21:33:39 -07005257 break;
5258 case glslang::EOpLdexp:
5259 libCall = spv::GLSLstd450Ldexp;
5260 break;
5261
Rex Xu574ab042016-04-14 16:53:07 +08005262 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005263 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005264
Rex Xu9d93a232016-05-05 12:30:44 +08005265#ifdef AMD_EXTENSIONS
5266 case glslang::EOpSwizzleInvocations:
5267 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5268 libCall = spv::SwizzleInvocationsAMD;
5269 break;
5270 case glslang::EOpSwizzleInvocationsMasked:
5271 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5272 libCall = spv::SwizzleInvocationsMaskedAMD;
5273 break;
5274 case glslang::EOpWriteInvocation:
5275 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5276 libCall = spv::WriteInvocationAMD;
5277 break;
5278
5279 case glslang::EOpMin3:
5280 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5281 if (isFloat)
5282 libCall = spv::FMin3AMD;
5283 else {
5284 if (isUnsigned)
5285 libCall = spv::UMin3AMD;
5286 else
5287 libCall = spv::SMin3AMD;
5288 }
5289 break;
5290 case glslang::EOpMax3:
5291 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5292 if (isFloat)
5293 libCall = spv::FMax3AMD;
5294 else {
5295 if (isUnsigned)
5296 libCall = spv::UMax3AMD;
5297 else
5298 libCall = spv::SMax3AMD;
5299 }
5300 break;
5301 case glslang::EOpMid3:
5302 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5303 if (isFloat)
5304 libCall = spv::FMid3AMD;
5305 else {
5306 if (isUnsigned)
5307 libCall = spv::UMid3AMD;
5308 else
5309 libCall = spv::SMid3AMD;
5310 }
5311 break;
5312
5313 case glslang::EOpInterpolateAtVertex:
5314 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5315 libCall = spv::InterpolateAtVertexAMD;
5316 break;
5317#endif
5318
John Kessenich140f3df2015-06-26 16:58:36 -06005319 default:
5320 return 0;
5321 }
5322
5323 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005324 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005325 // Use an extended instruction from the standard library.
5326 // Construct the call arguments, without modifying the original operands vector.
5327 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5328 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005329 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005330 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005331 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005332 case 0:
5333 // should all be handled by visitAggregate and createNoArgOperation
5334 assert(0);
5335 return 0;
5336 case 1:
5337 // should all be handled by createUnaryOperation
5338 assert(0);
5339 return 0;
5340 case 2:
5341 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5342 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005343 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005344 // anything 3 or over doesn't have l-value operands, so all should be consumed
5345 assert(consumedOperands == operands.size());
5346 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005347 break;
5348 }
5349 }
5350
John Kessenich55e7d112015-11-15 21:33:39 -07005351 // Decode the return types that were structures
5352 switch (op) {
5353 case glslang::EOpAddCarry:
5354 case glslang::EOpSubBorrow:
5355 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5356 id = builder.createCompositeExtract(id, typeId0, 0);
5357 break;
5358 case glslang::EOpUMulExtended:
5359 case glslang::EOpIMulExtended:
5360 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5361 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5362 break;
5363 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005364 {
5365 assert(operands.size() == 2);
5366 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5367 // "exp" is floating-point type (from HLSL intrinsic)
5368 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5369 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5370 builder.createStore(member1, operands[1]);
5371 } else
5372 // "exp" is integer type (from GLSL built-in function)
5373 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5374 id = builder.createCompositeExtract(id, typeId0, 0);
5375 }
John Kessenich55e7d112015-11-15 21:33:39 -07005376 break;
5377 default:
5378 break;
5379 }
5380
John Kessenich32cfd492016-02-02 12:37:46 -07005381 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005382}
5383
Rex Xu9d93a232016-05-05 12:30:44 +08005384// Intrinsics with no arguments (or no return value, and no precision).
5385spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005386{
5387 // TODO: get the barrier operands correct
5388
5389 switch (op) {
5390 case glslang::EOpEmitVertex:
5391 builder.createNoResultOp(spv::OpEmitVertex);
5392 return 0;
5393 case glslang::EOpEndPrimitive:
5394 builder.createNoResultOp(spv::OpEndPrimitive);
5395 return 0;
5396 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005397 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005398 return 0;
5399 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005400 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005401 return 0;
5402 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005403 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005404 return 0;
5405 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005406 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005407 return 0;
5408 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005409 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005410 return 0;
5411 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005412 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005413 return 0;
5414 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005415 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005416 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005417 case glslang::EOpAllMemoryBarrierWithGroupSync:
5418 // Control barrier with non-"None" semantic is also a memory barrier.
5419 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5420 return 0;
5421 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5422 // Control barrier with non-"None" semantic is also a memory barrier.
5423 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5424 return 0;
5425 case glslang::EOpWorkgroupMemoryBarrier:
5426 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5427 return 0;
5428 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5429 // Control barrier with non-"None" semantic is also a memory barrier.
5430 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5431 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005432#ifdef AMD_EXTENSIONS
5433 case glslang::EOpTime:
5434 {
5435 std::vector<spv::Id> args; // Dummy arguments
5436 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5437 return builder.setPrecision(id, precision);
5438 }
5439#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005440 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005441 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005442 return 0;
5443 }
5444}
5445
5446spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5447{
John Kessenich2f273362015-07-18 22:34:27 -06005448 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005449 spv::Id id;
5450 if (symbolValues.end() != iter) {
5451 id = iter->second;
5452 return id;
5453 }
5454
5455 // it was not found, create it
5456 id = createSpvVariable(symbol);
5457 symbolValues[symbol->getId()] = id;
5458
Rex Xuc884b4a2016-06-29 15:03:44 +08005459 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005460 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005461 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005462 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005463 if (symbol->getType().getQualifier().hasSpecConstantId())
5464 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005465 if (symbol->getQualifier().hasIndex())
5466 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5467 if (symbol->getQualifier().hasComponent())
5468 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5469 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005470 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005471 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005472 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005473 if (symbol->getQualifier().hasXfbBuffer())
5474 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5475 if (symbol->getQualifier().hasXfbOffset())
5476 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5477 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005478 // atomic counters use this:
5479 if (symbol->getQualifier().hasOffset())
5480 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005481 }
5482
scygan2c864272016-05-18 18:09:17 +02005483 if (symbol->getQualifier().hasLocation())
5484 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005485 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005486 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005487 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005488 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005489 }
John Kessenich140f3df2015-06-26 16:58:36 -06005490 if (symbol->getQualifier().hasSet())
5491 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005492 else if (IsDescriptorResource(symbol->getType())) {
5493 // default to 0
5494 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5495 }
John Kessenich140f3df2015-06-26 16:58:36 -06005496 if (symbol->getQualifier().hasBinding())
5497 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005498 if (symbol->getQualifier().hasAttachment())
5499 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005500 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005501 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005502 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005503 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005504 if (symbol->getQualifier().hasXfbBuffer())
5505 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5506 }
5507
Rex Xu1da878f2016-02-21 20:59:01 +08005508 if (symbol->getType().isImage()) {
5509 std::vector<spv::Decoration> memory;
5510 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5511 for (unsigned int i = 0; i < memory.size(); ++i)
5512 addDecoration(id, memory[i]);
5513 }
5514
John Kessenich140f3df2015-06-26 16:58:36 -06005515 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005516 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005517 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005518 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005519
John Kessenichecba76f2017-01-06 00:34:48 -07005520#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005521 if (builtIn == spv::BuiltInSampleMask) {
5522 spv::Decoration decoration;
5523 // GL_NV_sample_mask_override_coverage extension
5524 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005525 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005526 else
5527 decoration = (spv::Decoration)spv::DecorationMax;
5528 addDecoration(id, decoration);
5529 if (decoration != spv::DecorationMax) {
5530 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5531 }
5532 }
chaoc771d89f2017-01-13 01:10:53 -08005533 else if (builtIn == spv::BuiltInLayer) {
5534 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005535 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005536 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5537 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5538 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5539 }
John Kessenichb41bff62017-08-11 13:07:17 -06005540 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005541 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5542 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5543 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5544 }
5545 }
5546
chaoc6e5acae2016-12-20 13:28:52 -08005547 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005548 addDecoration(id, spv::DecorationPassthroughNV);
5549 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005550 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5551 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005552#endif
5553
John Kessenich140f3df2015-06-26 16:58:36 -06005554 return id;
5555}
5556
John Kessenich55e7d112015-11-15 21:33:39 -07005557// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005558void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5559{
John Kessenich4016e382016-07-15 11:53:56 -06005560 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005561 builder.addDecoration(id, dec);
5562}
5563
John Kessenich55e7d112015-11-15 21:33:39 -07005564// If 'dec' is valid, add a one-operand decoration to an object
5565void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5566{
John Kessenich4016e382016-07-15 11:53:56 -06005567 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005568 builder.addDecoration(id, dec, value);
5569}
5570
5571// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005572void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5573{
John Kessenich4016e382016-07-15 11:53:56 -06005574 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005575 builder.addMemberDecoration(id, (unsigned)member, dec);
5576}
5577
John Kessenich92187592016-02-01 13:45:25 -07005578// If 'dec' is valid, add a one-operand decoration to a struct member
5579void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5580{
John Kessenich4016e382016-07-15 11:53:56 -06005581 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005582 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5583}
5584
John Kessenich55e7d112015-11-15 21:33:39 -07005585// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005586// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005587//
5588// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5589//
5590// Recursively walk the nodes. The nodes form a tree whose leaves are
5591// regular constants, which themselves are trees that createSpvConstant()
5592// recursively walks. So, this function walks the "top" of the tree:
5593// - emit specialization constant-building instructions for specConstant
5594// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005595spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005596{
John Kessenich7cc0e282016-03-20 00:46:02 -06005597 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005598
qining4f4bb812016-04-03 23:55:17 -04005599 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005600 if (! node.getQualifier().specConstant) {
5601 // hand off to the non-spec-constant path
5602 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5603 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005604 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005605 nextConst, false);
5606 }
5607
5608 // We now know we have a specialization constant to build
5609
John Kessenichd94c0032016-05-30 19:29:40 -06005610 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005611 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5612 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5613 std::vector<spv::Id> dimConstId;
5614 for (int dim = 0; dim < 3; ++dim) {
5615 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5616 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5617 if (specConst)
5618 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5619 }
5620 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5621 }
5622
5623 // An AST node labelled as specialization constant should be a symbol node.
5624 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5625 if (auto* sn = node.getAsSymbolNode()) {
5626 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005627 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5628 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5629 // will set the builder into spec constant op instruction generating mode.
5630 sub_tree->traverse(this);
5631 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005632 } else if (auto* const_union_array = &sn->getConstArray()){
5633 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005634 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5635 builder.addName(id, sn->getName().c_str());
5636 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005637 }
5638 }
qining4f4bb812016-04-03 23:55:17 -04005639
5640 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5641 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005642 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005643 exit(1);
5644 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005645}
5646
John Kessenich140f3df2015-06-26 16:58:36 -06005647// Use 'consts' as the flattened glslang source of scalar constants to recursively
5648// build the aggregate SPIR-V constant.
5649//
5650// If there are not enough elements present in 'consts', 0 will be substituted;
5651// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5652//
qining08408382016-03-21 09:51:37 -04005653spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005654{
5655 // vector of constants for SPIR-V
5656 std::vector<spv::Id> spvConsts;
5657
5658 // Type is used for struct and array constants
5659 spv::Id typeId = convertGlslangToSpvType(glslangType);
5660
5661 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005662 glslang::TType elementType(glslangType, 0);
5663 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005664 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005665 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005666 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005667 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005668 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005669 } else if (glslangType.getStruct()) {
5670 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5671 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005672 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005673 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005674 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5675 bool zero = nextConst >= consts.size();
5676 switch (glslangType.getBasicType()) {
5677 case glslang::EbtInt:
5678 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5679 break;
5680 case glslang::EbtUint:
5681 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5682 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005683 case glslang::EbtInt64:
5684 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5685 break;
5686 case glslang::EbtUint64:
5687 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5688 break;
Rex Xucabbb782017-03-24 13:41:14 +08005689#ifdef AMD_EXTENSIONS
5690 case glslang::EbtInt16:
5691 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5692 break;
5693 case glslang::EbtUint16:
5694 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5695 break;
5696#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005697 case glslang::EbtFloat:
5698 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5699 break;
5700 case glslang::EbtDouble:
5701 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5702 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005703#ifdef AMD_EXTENSIONS
5704 case glslang::EbtFloat16:
5705 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5706 break;
5707#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005708 case glslang::EbtBool:
5709 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5710 break;
5711 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005712 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005713 break;
5714 }
5715 ++nextConst;
5716 }
5717 } else {
5718 // we have a non-aggregate (scalar) constant
5719 bool zero = nextConst >= consts.size();
5720 spv::Id scalar = 0;
5721 switch (glslangType.getBasicType()) {
5722 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005723 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005724 break;
5725 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005726 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005727 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005728 case glslang::EbtInt64:
5729 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5730 break;
5731 case glslang::EbtUint64:
5732 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5733 break;
Rex Xucabbb782017-03-24 13:41:14 +08005734#ifdef AMD_EXTENSIONS
5735 case glslang::EbtInt16:
5736 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5737 break;
5738 case glslang::EbtUint16:
5739 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5740 break;
5741#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005742 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005743 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005744 break;
5745 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005746 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005747 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005748#ifdef AMD_EXTENSIONS
5749 case glslang::EbtFloat16:
5750 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5751 break;
5752#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005753 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005754 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005755 break;
5756 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005757 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005758 break;
5759 }
5760 ++nextConst;
5761 return scalar;
5762 }
5763
5764 return builder.makeCompositeConstant(typeId, spvConsts);
5765}
5766
John Kessenich7c1aa102015-10-15 13:29:11 -06005767// Return true if the node is a constant or symbol whose reading has no
5768// non-trivial observable cost or effect.
5769bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5770{
5771 // don't know what this is
5772 if (node == nullptr)
5773 return false;
5774
5775 // a constant is safe
5776 if (node->getAsConstantUnion() != nullptr)
5777 return true;
5778
5779 // not a symbol means non-trivial
5780 if (node->getAsSymbolNode() == nullptr)
5781 return false;
5782
5783 // a symbol, depends on what's being read
5784 switch (node->getType().getQualifier().storage) {
5785 case glslang::EvqTemporary:
5786 case glslang::EvqGlobal:
5787 case glslang::EvqIn:
5788 case glslang::EvqInOut:
5789 case glslang::EvqConst:
5790 case glslang::EvqConstReadOnly:
5791 case glslang::EvqUniform:
5792 return true;
5793 default:
5794 return false;
5795 }
qining25262b32016-05-06 17:25:16 -04005796}
John Kessenich7c1aa102015-10-15 13:29:11 -06005797
5798// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005799// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005800// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005801// Return true if trivial.
5802bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5803{
5804 if (node == nullptr)
5805 return false;
5806
John Kessenich84cc15f2017-05-24 16:44:47 -06005807 // count non scalars as trivial, as well as anything coming from HLSL
5808 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005809 return true;
5810
John Kessenich7c1aa102015-10-15 13:29:11 -06005811 // symbols and constants are trivial
5812 if (isTrivialLeaf(node))
5813 return true;
5814
5815 // otherwise, it needs to be a simple operation or one or two leaf nodes
5816
5817 // not a simple operation
5818 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5819 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5820 if (binaryNode == nullptr && unaryNode == nullptr)
5821 return false;
5822
5823 // not on leaf nodes
5824 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5825 return false;
5826
5827 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5828 return false;
5829 }
5830
5831 switch (node->getAsOperator()->getOp()) {
5832 case glslang::EOpLogicalNot:
5833 case glslang::EOpConvIntToBool:
5834 case glslang::EOpConvUintToBool:
5835 case glslang::EOpConvFloatToBool:
5836 case glslang::EOpConvDoubleToBool:
5837 case glslang::EOpEqual:
5838 case glslang::EOpNotEqual:
5839 case glslang::EOpLessThan:
5840 case glslang::EOpGreaterThan:
5841 case glslang::EOpLessThanEqual:
5842 case glslang::EOpGreaterThanEqual:
5843 case glslang::EOpIndexDirect:
5844 case glslang::EOpIndexDirectStruct:
5845 case glslang::EOpLogicalXor:
5846 case glslang::EOpAny:
5847 case glslang::EOpAll:
5848 return true;
5849 default:
5850 return false;
5851 }
5852}
5853
5854// Emit short-circuiting code, where 'right' is never evaluated unless
5855// the left side is true (for &&) or false (for ||).
5856spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5857{
5858 spv::Id boolTypeId = builder.makeBoolType();
5859
5860 // emit left operand
5861 builder.clearAccessChain();
5862 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005863 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005864
5865 // Operands to accumulate OpPhi operands
5866 std::vector<spv::Id> phiOperands;
5867 // accumulate left operand's phi information
5868 phiOperands.push_back(leftId);
5869 phiOperands.push_back(builder.getBuildPoint()->getId());
5870
5871 // Make the two kinds of operation symmetric with a "!"
5872 // || => emit "if (! left) result = right"
5873 // && => emit "if ( left) result = right"
5874 //
5875 // TODO: this runtime "not" for || could be avoided by adding functionality
5876 // to 'builder' to have an "else" without an "then"
5877 if (op == glslang::EOpLogicalOr)
5878 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5879
5880 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005881 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005882
5883 // emit right operand as the "then" part of the "if"
5884 builder.clearAccessChain();
5885 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005886 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005887
5888 // accumulate left operand's phi information
5889 phiOperands.push_back(rightId);
5890 phiOperands.push_back(builder.getBuildPoint()->getId());
5891
5892 // finish the "if"
5893 ifBuilder.makeEndIf();
5894
5895 // phi together the two results
5896 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5897}
5898
Rex Xu9d93a232016-05-05 12:30:44 +08005899// Return type Id of the imported set of extended instructions corresponds to the name.
5900// Import this set if it has not been imported yet.
5901spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5902{
5903 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5904 return extBuiltinMap[name];
5905 else {
Rex Xu51596642016-09-21 18:56:12 +08005906 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005907 spv::Id extBuiltins = builder.import(name);
5908 extBuiltinMap[name] = extBuiltins;
5909 return extBuiltins;
5910 }
5911}
5912
John Kessenich140f3df2015-06-26 16:58:36 -06005913}; // end anonymous namespace
5914
5915namespace glslang {
5916
John Kessenich68d78fd2015-07-12 19:28:10 -06005917void GetSpirvVersion(std::string& version)
5918{
John Kessenich9e55f632015-07-15 10:03:39 -06005919 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005920 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005921 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005922 version = buf;
5923}
5924
John Kessenich140f3df2015-06-26 16:58:36 -06005925// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005926void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005927{
5928 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005929 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005930 if (out.fail())
5931 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005932 for (int i = 0; i < (int)spirv.size(); ++i) {
5933 unsigned int word = spirv[i];
5934 out.write((const char*)&word, 4);
5935 }
5936 out.close();
5937}
5938
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005939// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005940void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005941{
5942 std::ofstream out;
5943 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005944 if (out.fail())
5945 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005946 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005947 if (varName != nullptr) {
5948 out << "\t #pragma once" << std::endl;
5949 out << "const uint32_t " << varName << "[] = {" << std::endl;
5950 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005951 const int WORDS_PER_LINE = 8;
5952 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5953 out << "\t";
5954 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5955 const unsigned int word = spirv[i + j];
5956 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5957 if (i + j + 1 < (int)spirv.size()) {
5958 out << ",";
5959 }
5960 }
5961 out << std::endl;
5962 }
Flavio15017db2017-02-15 14:29:33 -08005963 if (varName != nullptr) {
5964 out << "};";
5965 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005966 out.close();
5967}
5968
John Kessenich140f3df2015-06-26 16:58:36 -06005969//
5970// Set up the glslang traversal
5971//
John Kessenich121853f2017-05-31 17:11:16 -06005972void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005973{
Lei Zhang17535f72016-05-04 15:55:59 -04005974 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005975 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005976}
5977
John Kessenich121853f2017-05-31 17:11:16 -06005978void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5979 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005980{
John Kessenich140f3df2015-06-26 16:58:36 -06005981 TIntermNode* root = intermediate.getTreeRoot();
5982
5983 if (root == 0)
5984 return;
5985
John Kessenich121853f2017-05-31 17:11:16 -06005986 glslang::SpvOptions defaultOptions;
5987 if (options == nullptr)
5988 options = &defaultOptions;
5989
John Kessenich140f3df2015-06-26 16:58:36 -06005990 glslang::GetThreadPoolAllocator().push();
5991
John Kessenich121853f2017-05-31 17:11:16 -06005992 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005993 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005994 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005995 it.dumpSpv(spirv);
5996
5997 glslang::GetThreadPoolAllocator().pop();
5998}
5999
6000}; // end namespace glslang