blob: 78ec8338bb02fb5290e754400eb273e1e4884114 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800125 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600126 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600127 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
129 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600130 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
131 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
132 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700134 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600135 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600136 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
137 glslang::TLayoutPacking, const glslang::TQualifier&);
138 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
139 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700140 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700141 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800142 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600143 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700144 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
147 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100148 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600149
John Kessenich6fccb3c2016-09-19 16:01:41 -0600150 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void makeFunctions(const glslang::TIntermSequence&);
152 void makeGlobalInitializers(const glslang::TIntermSequence&);
153 void visitFunctions(const glslang::TIntermSequence&);
154 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600156 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
157 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
159
qining25262b32016-05-06 17:25:16 -0400160 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
161 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
162 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800163 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800164 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800166 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800167 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800168 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600169 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800170 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
172 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700173 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700175 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400176 spv::Id createSpvConstant(const glslang::TIntermTyped&);
177 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600178 bool isTrivialLeaf(const glslang::TIntermTyped* node);
179 bool isTrivial(const glslang::TIntermTyped* node);
180 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800181 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich121853f2017-05-31 17:11:16 -0600183 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600185 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700186 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600187 int sequenceDepth;
188
Lei Zhang17535f72016-05-04 15:55:59 -0400189 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400190
John Kessenich140f3df2015-06-26 16:58:36 -0600191 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
192 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700193 bool inEntryPoint;
194 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700195 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700196 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600197 const glslang::TIntermediate* glslangIntermediate;
198 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800199 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600200
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600202 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700204 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600205 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600206 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600207};
208
209//
210// Helper functions for translating glslang representations to SPIR-V enumerants.
211//
212
213// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700214spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600215{
John Kessenich66e2faf2016-03-12 18:34:36 -0700216 switch (source) {
217 case glslang::EShSourceGlsl:
218 switch (profile) {
219 case ENoProfile:
220 case ECoreProfile:
221 case ECompatibilityProfile:
222 return spv::SourceLanguageGLSL;
223 case EEsProfile:
224 return spv::SourceLanguageESSL;
225 default:
226 return spv::SourceLanguageUnknown;
227 }
228 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600229 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 default:
231 return spv::SourceLanguageUnknown;
232 }
233}
234
235// Translate glslang language (stage) to SPIR-V execution model.
236spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
237{
238 switch (stage) {
239 case EShLangVertex: return spv::ExecutionModelVertex;
240 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
241 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
242 case EShLangGeometry: return spv::ExecutionModelGeometry;
243 case EShLangFragment: return spv::ExecutionModelFragment;
244 case EShLangCompute: return spv::ExecutionModelGLCompute;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::ExecutionModelFragment;
248 }
249}
250
John Kessenich140f3df2015-06-26 16:58:36 -0600251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
John Kessenichf6640762016-08-01 19:44:00 -0600268// Translate glslang precision to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenichf6640762016-08-01 19:44:00 -0600271 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang type to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
281{
282 return TranslatePrecisionDecoration(type.getQualifier().precision);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600286spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.getBasicType() == glslang::EbtBlock) {
289 switch (type.getQualifier().storage) {
290 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600291 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::EvqVaryingIn: return spv::DecorationBlock;
293 case glslang::EvqVaryingOut: return spv::DecorationBlock;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 break;
297 }
298 }
299
John Kessenich4016e382016-07-15 11:53:56 -0600300 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600301}
302
Rex Xu1da878f2016-02-21 20:59:01 +0800303// Translate glslang type to SPIR-V memory decorations.
304void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
305{
306 if (qualifier.coherent)
307 memory.push_back(spv::DecorationCoherent);
308 if (qualifier.volatil)
309 memory.push_back(spv::DecorationVolatile);
310 if (qualifier.restrict)
311 memory.push_back(spv::DecorationRestrict);
312 if (qualifier.readonly)
313 memory.push_back(spv::DecorationNonWritable);
314 if (qualifier.writeonly)
315 memory.push_back(spv::DecorationNonReadable);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700319spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::ElmRowMajor:
324 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 default:
328 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 }
331 } else {
332 switch (type.getBasicType()) {
333 default:
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 break;
336 case glslang::EbtBlock:
337 switch (type.getQualifier().storage) {
338 case glslang::EvqUniform:
339 case glslang::EvqBuffer:
340 switch (type.getQualifier().layoutPacking) {
341 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 }
346 case glslang::EvqVaryingIn:
347 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600349 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 }
355 }
356}
357
358// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600359// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700360// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800361spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600362{
Rex Xubbceed72016-05-21 09:40:44 +0800363 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700367 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800370#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800371 else if (qualifier.explicitInterp) {
372 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800373 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800374 }
Rex Xu9d93a232016-05-05 12:30:44 +0800375#endif
Rex Xubbceed72016-05-21 09:40:44 +0800376 else
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378}
379
380// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800382// should be applied.
383spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
384{
385 if (qualifier.patch)
386 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700389 else if (qualifier.sample) {
390 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700392 } else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600394}
395
John Kessenich92187592016-02-01 13:45:25 -0700396// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationInvariant;
401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600403}
404
qining9220dbb2016-05-04 17:34:38 -0400405// If glslang type is noContraction, return SPIR-V NoContraction decoration.
406spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
407{
408 if (qualifier.noContraction)
409 return spv::DecorationNoContraction;
410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400412}
413
David Netoa901ffe2016-06-08 14:11:40 +0100414// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
415// associated capabilities when required. For some built-in variables, a capability
416// is generated only when using the variable in an executable instruction, but not when
417// just declaring a struct member variable with it. This is true for PointSize,
418// ClipDistance, and CullDistance.
419spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
421 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700422 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600423 // Defer adding the capability until the built-in is actually used.
424 if (! memberDeclaration) {
425 switch (glslangIntermediate->getStage()) {
426 case EShLangGeometry:
427 builder.addCapability(spv::CapabilityGeometryPointSize);
428 break;
429 case EShLangTessControl:
430 case EShLangTessEvaluation:
431 builder.addCapability(spv::CapabilityTessellationPointSize);
432 break;
433 default:
434 break;
435 }
John Kessenich92187592016-02-01 13:45:25 -0700436 }
437 return spv::BuiltInPointSize;
438
John Kessenichebb50532016-05-16 19:22:05 -0600439 // These *Distance capabilities logically belong here, but if the member is declared and
440 // then never used, consumers of SPIR-V prefer the capability not be declared.
441 // They are now generated when used, rather than here when declared.
442 // Potentially, the specification should be more clear what the minimum
443 // use needed is to trigger the capability.
444 //
John Kessenich92187592016-02-01 13:45:25 -0700445 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100446 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800447 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700448 return spv::BuiltInClipDistance;
449
450 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100451 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800452 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInCullDistance;
454
455 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800456 if (!memberDeclaration) {
457 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800458#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800459 if (glslangIntermediate->getStage() == EShLangVertex ||
460 glslangIntermediate->getStage() == EShLangTessControl ||
461 glslangIntermediate->getStage() == EShLangTessEvaluation) {
462
463 builder.addExtension(spv::E_SPV_NV_viewport_array2);
464 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
465 }
chaoc771d89f2017-01-13 01:10:53 -0800466#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800467 }
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInViewportIndex;
469
John Kessenich5e801132016-02-15 11:09:46 -0700470 case glslang::EbvSampleId:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSampleId;
473
474 case glslang::EbvSamplePosition:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSamplePosition;
477
478 case glslang::EbvSampleMask:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleMask;
481
John Kessenich78a45572016-07-08 14:05:15 -0600482 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
chaoc771d89f2017-01-13 01:10:53 -0800490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
495
John Kessenich78a45572016-07-08 14:05:15 -0600496 return spv::BuiltInLayer;
497
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvVertexId: return spv::BuiltInVertexId;
500 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700501 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
502 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800505 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
506 builder.addCapability(spv::CapabilityDrawParameters);
507 return spv::BuiltInBaseVertex;
508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
519 case glslang::EbvPrimitiveId:
520 if (glslangIntermediate->getStage() == EShLangFragment)
521 builder.addCapability(spv::CapabilityGeometry);
522 return spv::BuiltInPrimitiveId;
523
Rex Xu37cdcee2017-06-29 17:46:34 +0800524 case glslang::EbvFragStencilRef:
525 logger->missingFunctionality("shader stencil export");
526 return spv::BuiltInMax;
527
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
530 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
531 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
532 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
533 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
534 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
535 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
537 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
538 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
539 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
540 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
541 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
542 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
543 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupSize;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupLocalInvocationId;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupEqMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupGeMaskKHR;
564
Rex Xu574ab042016-04-14 16:53:07 +0800565 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
568 return spv::BuiltInSubgroupGtMaskKHR;
569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupLeMaskKHR;
574
Rex Xu574ab042016-04-14 16:53:07 +0800575 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
577 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
578 return spv::BuiltInSubgroupLtMaskKHR;
579
Rex Xu9d93a232016-05-05 12:30:44 +0800580#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800581 case glslang::EbvBaryCoordNoPersp:
582 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
583 return spv::BuiltInBaryCoordNoPerspAMD;
584
585 case glslang::EbvBaryCoordNoPerspCentroid:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
588
589 case glslang::EbvBaryCoordNoPerspSample:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordNoPerspSampleAMD;
592
593 case glslang::EbvBaryCoordSmooth:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordSmoothAMD;
596
597 case glslang::EbvBaryCoordSmoothCentroid:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordSmoothCentroidAMD;
600
601 case glslang::EbvBaryCoordSmoothSample:
602 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
603 return spv::BuiltInBaryCoordSmoothSampleAMD;
604
605 case glslang::EbvBaryCoordPullModel:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800608#endif
chaoc771d89f2017-01-13 01:10:53 -0800609
John Kessenich6c8aaac2017-02-27 01:20:51 -0700610 case glslang::EbvDeviceIndex:
611 builder.addExtension(spv::E_SPV_KHR_device_group);
612 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700613 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614
615 case glslang::EbvViewIndex:
616 builder.addExtension(spv::E_SPV_KHR_multiview);
617 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700618 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700619
chaoc771d89f2017-01-13 01:10:53 -0800620#ifdef NV_EXTENSIONS
621 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_viewport_array2);
624 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInViewportMaskNV;
627 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryPositionNV;
633 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
636 builder.addCapability(spv::CapabilityShaderStereoViewNV);
637 }
chaoc771d89f2017-01-13 01:10:53 -0800638 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800639 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInPositionPerViewNV;
645 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
648 builder.addCapability(spv::CapabilityPerViewAttributesNV);
649 }
chaocdf3956c2017-02-14 14:52:34 -0800650 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800651#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800652 default:
653 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655}
656
Rex Xufc618912015-09-09 16:42:49 +0800657// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700658spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800659{
660 assert(type.getBasicType() == glslang::EbtSampler);
661
John Kessenich5d0fa972016-02-15 11:57:00 -0700662 // Check for capabilities
663 switch (type.getQualifier().layoutFormat) {
664 case glslang::ElfRg32f:
665 case glslang::ElfRg16f:
666 case glslang::ElfR11fG11fB10f:
667 case glslang::ElfR16f:
668 case glslang::ElfRgba16:
669 case glslang::ElfRgb10A2:
670 case glslang::ElfRg16:
671 case glslang::ElfRg8:
672 case glslang::ElfR16:
673 case glslang::ElfR8:
674 case glslang::ElfRgba16Snorm:
675 case glslang::ElfRg16Snorm:
676 case glslang::ElfRg8Snorm:
677 case glslang::ElfR16Snorm:
678 case glslang::ElfR8Snorm:
679
680 case glslang::ElfRg32i:
681 case glslang::ElfRg16i:
682 case glslang::ElfRg8i:
683 case glslang::ElfR16i:
684 case glslang::ElfR8i:
685
686 case glslang::ElfRgb10a2ui:
687 case glslang::ElfRg32ui:
688 case glslang::ElfRg16ui:
689 case glslang::ElfRg8ui:
690 case glslang::ElfR16ui:
691 case glslang::ElfR8ui:
692 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
693 break;
694
695 default:
696 break;
697 }
698
699 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800700 switch (type.getQualifier().layoutFormat) {
701 case glslang::ElfNone: return spv::ImageFormatUnknown;
702 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
703 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
704 case glslang::ElfR32f: return spv::ImageFormatR32f;
705 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
706 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
707 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
708 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
709 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
710 case glslang::ElfR16f: return spv::ImageFormatR16f;
711 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
712 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
713 case glslang::ElfRg16: return spv::ImageFormatRg16;
714 case glslang::ElfRg8: return spv::ImageFormatRg8;
715 case glslang::ElfR16: return spv::ImageFormatR16;
716 case glslang::ElfR8: return spv::ImageFormatR8;
717 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
718 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
719 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
720 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
721 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
722 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
723 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
724 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
725 case glslang::ElfR32i: return spv::ImageFormatR32i;
726 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
727 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
728 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
729 case glslang::ElfR16i: return spv::ImageFormatR16i;
730 case glslang::ElfR8i: return spv::ImageFormatR8i;
731 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
732 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
733 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
734 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
735 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
736 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
737 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
738 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
739 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
740 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600741 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800742 }
743}
744
Rex Xu57e65922017-07-04 23:23:40 +0800745spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
746{
747 switch (selectionControl) {
748 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
749 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
750 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
751 default: return spv::SelectionControlMaskNone;
752 }
753}
754
steve-lunargf1709e72017-05-02 20:14:50 -0600755spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
756{
757 switch (loopControl) {
758 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
759 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
760 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
761 // TODO: DependencyInfinite
762 // TODO: DependencyLength
763 default: return spv::LoopControlMaskNone;
764 }
765}
766
John Kessenicha5c5fb62017-05-05 05:09:58 -0600767// Translate glslang type to SPIR-V storage class.
768spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
769{
770 if (type.getQualifier().isPipeInput())
771 return spv::StorageClassInput;
772 else if (type.getQualifier().isPipeOutput())
773 return spv::StorageClassOutput;
774 else if (type.getBasicType() == glslang::EbtAtomicUint)
775 return spv::StorageClassAtomicCounter;
776 else if (type.containsOpaque())
777 return spv::StorageClassUniformConstant;
778 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
779 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
780 return spv::StorageClassStorageBuffer;
781 } else if (type.getQualifier().isUniformOrBuffer()) {
782 if (type.getQualifier().layoutPushConstant)
783 return spv::StorageClassPushConstant;
784 if (type.getBasicType() == glslang::EbtBlock)
785 return spv::StorageClassUniform;
786 else
787 return spv::StorageClassUniformConstant;
788 } else {
789 switch (type.getQualifier().storage) {
790 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
791 case glslang::EvqGlobal: return spv::StorageClassPrivate;
792 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
793 case glslang::EvqTemporary: return spv::StorageClassFunction;
794 default:
795 assert(0);
796 return spv::StorageClassFunction;
797 }
798 }
799}
800
qining25262b32016-05-06 17:25:16 -0400801// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700802// descriptor set.
803bool IsDescriptorResource(const glslang::TType& type)
804{
John Kessenichf7497e22016-03-08 21:36:22 -0700805 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700806 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700807 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700808
809 // non block...
810 // basically samplerXXX/subpass/sampler/texture are all included
811 // if they are the global-scope-class, not the function parameter
812 // (or local, if they ever exist) class.
813 if (type.getBasicType() == glslang::EbtSampler)
814 return type.getQualifier().isUniformOrBuffer();
815
816 // None of the above.
817 return false;
818}
819
John Kesseniche0b6cad2015-12-24 10:30:13 -0700820void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
821{
822 if (child.layoutMatrix == glslang::ElmNone)
823 child.layoutMatrix = parent.layoutMatrix;
824
825 if (parent.invariant)
826 child.invariant = true;
827 if (parent.nopersp)
828 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800829#ifdef AMD_EXTENSIONS
830 if (parent.explicitInterp)
831 child.explicitInterp = true;
832#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833 if (parent.flat)
834 child.flat = true;
835 if (parent.centroid)
836 child.centroid = true;
837 if (parent.patch)
838 child.patch = true;
839 if (parent.sample)
840 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800841 if (parent.coherent)
842 child.coherent = true;
843 if (parent.volatil)
844 child.volatil = true;
845 if (parent.restrict)
846 child.restrict = true;
847 if (parent.readonly)
848 child.readonly = true;
849 if (parent.writeonly)
850 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851}
852
John Kessenichf2b7f332016-09-01 17:05:23 -0600853bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700854{
John Kessenich7b9fa252016-01-21 18:56:57 -0700855 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600856 // - struct members might inherit from a struct declaration
857 // (note that non-block structs don't explicitly inherit,
858 // only implicitly, meaning no decoration involved)
859 // - affect decorations on the struct members
860 // (note smooth does not, and expecting something like volatile
861 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700862 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600863 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864}
865
John Kessenich140f3df2015-06-26 16:58:36 -0600866//
867// Implement the TGlslangToSpvTraverser class.
868//
869
John Kessenich121853f2017-05-31 17:11:16 -0600870TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
871 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
872 : TIntermTraverser(true, false, true),
873 options(options),
874 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600875 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400876 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700877 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600878 glslangIntermediate(glslangIntermediate)
879{
880 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
881
882 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700883 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600884 if (options.generateDebugInfo) {
885 builder.setSourceFile(glslangIntermediate->getSourceFile());
886 builder.setSourceText(glslangIntermediate->getSourceText());
John Kesseniche485c7a2017-05-31 18:50:53 -0600887 builder.setEmitOpLines();
John Kessenich121853f2017-05-31 17:11:16 -0600888 }
John Kessenich140f3df2015-06-26 16:58:36 -0600889 stdBuiltins = builder.import("GLSL.std.450");
890 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600891 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
892 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600895 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
896 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600897 builder.addSourceExtension(it->c_str());
898
899 // Add the top-level modes for this shader.
900
John Kessenich92187592016-02-01 13:45:25 -0700901 if (glslangIntermediate->getXfbMode()) {
902 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600903 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700904 }
John Kessenich140f3df2015-06-26 16:58:36 -0600905
906 unsigned int mode;
907 switch (glslangIntermediate->getStage()) {
908 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600909 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600910 break;
911
steve-lunarge7412492017-03-23 11:56:07 -0600912 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600913 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600914 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600915
steve-lunarge7412492017-03-23 11:56:07 -0600916 glslang::TLayoutGeometry primitive;
917
918 if (glslangIntermediate->getStage() == EShLangTessControl) {
919 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
920 primitive = glslangIntermediate->getOutputPrimitive();
921 } else {
922 primitive = glslangIntermediate->getInputPrimitive();
923 }
924
925 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700926 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
927 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
928 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600929 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600930 }
John Kessenich4016e382016-07-15 11:53:56 -0600931 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600932 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
933
John Kesseniche6903322015-10-13 16:29:02 -0600934 switch (glslangIntermediate->getVertexSpacing()) {
935 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
936 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
937 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600938 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600939 }
John Kessenich4016e382016-07-15 11:53:56 -0600940 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600941 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
942
943 switch (glslangIntermediate->getVertexOrder()) {
944 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
945 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600946 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600947 }
John Kessenich4016e382016-07-15 11:53:56 -0600948 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600949 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
950
951 if (glslangIntermediate->getPointMode())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 break;
954
955 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 switch (glslangIntermediate->getInputPrimitive()) {
958 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
959 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
960 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700961 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600962 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600963 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
John Kessenich4016e382016-07-15 11:53:56 -0600965 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600966 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600967
John Kessenich140f3df2015-06-26 16:58:36 -0600968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
969
970 switch (glslangIntermediate->getOutputPrimitive()) {
971 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
972 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
973 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600974 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600975 }
John Kessenich4016e382016-07-15 11:53:56 -0600976 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600977 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
978 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
979 break;
980
981 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600982 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600983 if (glslangIntermediate->getPixelCenterInteger())
984 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600985
John Kessenich140f3df2015-06-26 16:58:36 -0600986 if (glslangIntermediate->getOriginUpperLeft())
987 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600988 else
989 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600990
991 if (glslangIntermediate->getEarlyFragmentTests())
992 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
993
chaocc1204522017-06-30 17:14:30 -0700994 if (glslangIntermediate->getPostDepthCoverage()) {
995 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
996 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
997 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
998 }
999
John Kesseniche6903322015-10-13 16:29:02 -06001000 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001001 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1002 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001003 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001004 }
John Kessenich4016e382016-07-15 11:53:56 -06001005 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001006 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1007
1008 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1009 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001010 break;
1011
1012 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001013 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001014 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1015 glslangIntermediate->getLocalSize(1),
1016 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001017 break;
1018
1019 default:
1020 break;
1021 }
John Kessenich140f3df2015-06-26 16:58:36 -06001022}
1023
John Kessenichfca82622016-11-26 13:23:20 -07001024// Finish creating SPV, after the traversal is complete.
1025void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001026{
John Kessenich517fe7a2016-11-26 13:31:47 -07001027 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001028 builder.setBuildPoint(shaderEntry->getLastBlock());
1029 builder.leaveFunction();
1030 }
1031
John Kessenich7ba63412015-12-20 17:37:07 -07001032 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001033 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1034 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001035
qiningda397332016-03-09 19:54:03 -05001036 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001037}
1038
John Kessenichfca82622016-11-26 13:23:20 -07001039// Write the SPV into 'out'.
1040void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001041{
John Kessenichfca82622016-11-26 13:23:20 -07001042 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001043}
1044
1045//
1046// Implement the traversal functions.
1047//
1048// Return true from interior nodes to have the external traversal
1049// continue on to children. Return false if children were
1050// already processed.
1051//
1052
1053//
qining25262b32016-05-06 17:25:16 -04001054// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001055// - uniform/input reads
1056// - output writes
1057// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1058// - something simple that degenerates into the last bullet
1059//
1060void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1061{
qining75d1d802016-04-06 14:42:01 -04001062 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1063 if (symbol->getType().getQualifier().isSpecConstant())
1064 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1065
John Kessenich140f3df2015-06-26 16:58:36 -06001066 // getSymbolId() will set up all the IO decorations on the first call.
1067 // Formal function parameters were mapped during makeFunctions().
1068 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001069
1070 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1071 if (builder.isPointer(id)) {
1072 spv::StorageClass sc = builder.getStorageClass(id);
1073 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1074 iOSet.insert(id);
1075 }
1076
1077 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001078 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001079 // Prepare to generate code for the access
1080
1081 // L-value chains will be computed left to right. We're on the symbol now,
1082 // which is the left-most part of the access chain, so now is "clear" time,
1083 // followed by setting the base.
1084 builder.clearAccessChain();
1085
1086 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001087 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001088 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001089 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001090 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001091 // These are also pure R-values.
1092 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001093 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001094 builder.setAccessChainRValue(id);
1095 else
1096 builder.setAccessChainLValue(id);
1097 }
1098}
1099
1100bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1101{
John Kesseniche485c7a2017-05-31 18:50:53 -06001102 builder.setLine(node->getLoc().line);
1103
qining40887662016-04-03 22:20:42 -04001104 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1105 if (node->getType().getQualifier().isSpecConstant())
1106 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1107
John Kessenich140f3df2015-06-26 16:58:36 -06001108 // First, handle special cases
1109 switch (node->getOp()) {
1110 case glslang::EOpAssign:
1111 case glslang::EOpAddAssign:
1112 case glslang::EOpSubAssign:
1113 case glslang::EOpMulAssign:
1114 case glslang::EOpVectorTimesMatrixAssign:
1115 case glslang::EOpVectorTimesScalarAssign:
1116 case glslang::EOpMatrixTimesScalarAssign:
1117 case glslang::EOpMatrixTimesMatrixAssign:
1118 case glslang::EOpDivAssign:
1119 case glslang::EOpModAssign:
1120 case glslang::EOpAndAssign:
1121 case glslang::EOpInclusiveOrAssign:
1122 case glslang::EOpExclusiveOrAssign:
1123 case glslang::EOpLeftShiftAssign:
1124 case glslang::EOpRightShiftAssign:
1125 // A bin-op assign "a += b" means the same thing as "a = a + b"
1126 // where a is evaluated before b. For a simple assignment, GLSL
1127 // says to evaluate the left before the right. So, always, left
1128 // node then right node.
1129 {
1130 // get the left l-value, save it away
1131 builder.clearAccessChain();
1132 node->getLeft()->traverse(this);
1133 spv::Builder::AccessChain lValue = builder.getAccessChain();
1134
1135 // evaluate the right
1136 builder.clearAccessChain();
1137 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001138 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001139
1140 if (node->getOp() != glslang::EOpAssign) {
1141 // the left is also an r-value
1142 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001143 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001146 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001147 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001148 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1149 node->getType().getBasicType());
1150
1151 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001152 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001153 }
1154
1155 // store the result
1156 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001157 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001158
1159 // assignments are expressions having an rValue after they are evaluated...
1160 builder.clearAccessChain();
1161 builder.setAccessChainRValue(rValue);
1162 }
1163 return false;
1164 case glslang::EOpIndexDirect:
1165 case glslang::EOpIndexDirectStruct:
1166 {
1167 // Get the left part of the access chain.
1168 node->getLeft()->traverse(this);
1169
1170 // Add the next element in the chain
1171
David Netoa901ffe2016-06-08 14:11:40 +01001172 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001173 if (! node->getLeft()->getType().isArray() &&
1174 node->getLeft()->getType().isVector() &&
1175 node->getOp() == glslang::EOpIndexDirect) {
1176 // This is essentially a hard-coded vector swizzle of size 1,
1177 // so short circuit the access-chain stuff with a swizzle.
1178 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001179 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001180 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001181 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001182 int spvIndex = glslangIndex;
1183 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1184 node->getOp() == glslang::EOpIndexDirectStruct)
1185 {
1186 // This may be, e.g., an anonymous block-member selection, which generally need
1187 // index remapping due to hidden members in anonymous blocks.
1188 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1189 assert(remapper.size() > 0);
1190 spvIndex = remapper[glslangIndex];
1191 }
John Kessenichebb50532016-05-16 19:22:05 -06001192
David Netoa901ffe2016-06-08 14:11:40 +01001193 // normal case for indexing array or structure or block
1194 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1195
1196 // Add capabilities here for accessing PointSize and clip/cull distance.
1197 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001198 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001199 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001200 }
1201 }
1202 return false;
1203 case glslang::EOpIndexIndirect:
1204 {
1205 // Structure or array or vector indirection.
1206 // Will use native SPIR-V access-chain for struct and array indirection;
1207 // matrices are arrays of vectors, so will also work for a matrix.
1208 // Will use the access chain's 'component' for variable index into a vector.
1209
1210 // This adapter is building access chains left to right.
1211 // Set up the access chain to the left.
1212 node->getLeft()->traverse(this);
1213
1214 // save it so that computing the right side doesn't trash it
1215 spv::Builder::AccessChain partial = builder.getAccessChain();
1216
1217 // compute the next index in the chain
1218 builder.clearAccessChain();
1219 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001220 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001221
1222 // restore the saved access chain
1223 builder.setAccessChain(partial);
1224
1225 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001226 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001227 else
John Kessenichfa668da2015-09-13 14:46:30 -06001228 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001229 }
1230 return false;
1231 case glslang::EOpVectorSwizzle:
1232 {
1233 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001234 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001236 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001237 }
1238 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001239 case glslang::EOpMatrixSwizzle:
1240 logger->missingFunctionality("matrix swizzle");
1241 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001242 case glslang::EOpLogicalOr:
1243 case glslang::EOpLogicalAnd:
1244 {
1245
1246 // These may require short circuiting, but can sometimes be done as straight
1247 // binary operations. The right operand must be short circuited if it has
1248 // side effects, and should probably be if it is complex.
1249 if (isTrivial(node->getRight()->getAsTyped()))
1250 break; // handle below as a normal binary operation
1251 // otherwise, we need to do dynamic short circuiting on the right operand
1252 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1253 builder.clearAccessChain();
1254 builder.setAccessChainRValue(result);
1255 }
1256 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001257 default:
1258 break;
1259 }
1260
1261 // Assume generic binary op...
1262
John Kessenich32cfd492016-02-02 12:37:46 -07001263 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001264 builder.clearAccessChain();
1265 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001266 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001267
John Kessenich32cfd492016-02-02 12:37:46 -07001268 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001269 builder.clearAccessChain();
1270 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001271 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001272
John Kessenich32cfd492016-02-02 12:37:46 -07001273 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001274 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001275 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001276 convertGlslangToSpvType(node->getType()), left, right,
1277 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001278
John Kessenich50e57562015-12-21 21:21:11 -07001279 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001280 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001281 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001282 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001283 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001284 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001285 return false;
1286 }
John Kessenich140f3df2015-06-26 16:58:36 -06001287}
1288
1289bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1290{
John Kesseniche485c7a2017-05-31 18:50:53 -06001291 builder.setLine(node->getLoc().line);
1292
qining40887662016-04-03 22:20:42 -04001293 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1294 if (node->getType().getQualifier().isSpecConstant())
1295 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1296
John Kessenichfc51d282015-08-19 13:34:18 -06001297 spv::Id result = spv::NoResult;
1298
1299 // try texturing first
1300 result = createImageTextureFunctionCall(node);
1301 if (result != spv::NoResult) {
1302 builder.clearAccessChain();
1303 builder.setAccessChainRValue(result);
1304
1305 return false; // done with this node
1306 }
1307
1308 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001309
1310 if (node->getOp() == glslang::EOpArrayLength) {
1311 // Quite special; won't want to evaluate the operand.
1312
1313 // Normal .length() would have been constant folded by the front-end.
1314 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001315 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001316 assert(node->getOperand()->getType().isRuntimeSizedArray());
1317 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1318 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001319 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1320 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001321
1322 builder.clearAccessChain();
1323 builder.setAccessChainRValue(length);
1324
1325 return false;
1326 }
1327
John Kessenichfc51d282015-08-19 13:34:18 -06001328 // Start by evaluating the operand
1329
John Kessenich8c8505c2016-07-26 12:50:38 -06001330 // Does it need a swizzle inversion? If so, evaluation is inverted;
1331 // operate first on the swizzle base, then apply the swizzle.
1332 spv::Id invertedType = spv::NoType;
1333 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1334 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1335 invertedType = getInvertedSwizzleType(*node->getOperand());
1336
John Kessenich140f3df2015-06-26 16:58:36 -06001337 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001338 if (invertedType != spv::NoType)
1339 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1340 else
1341 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001342
Rex Xufc618912015-09-09 16:42:49 +08001343 spv::Id operand = spv::NoResult;
1344
1345 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1346 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001347 node->getOp() == glslang::EOpAtomicCounter ||
1348 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001349 operand = builder.accessChainGetLValue(); // Special case l-value operands
1350 else
John Kessenich32cfd492016-02-02 12:37:46 -07001351 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001352
John Kessenichf6640762016-08-01 19:44:00 -06001353 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001354 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001357 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001358 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001359
1360 // if not, then possibly an operation
1361 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001362 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001365 if (invertedType)
1366 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1367
John Kessenich140f3df2015-06-26 16:58:36 -06001368 builder.clearAccessChain();
1369 builder.setAccessChainRValue(result);
1370
1371 return false; // done with this node
1372 }
1373
1374 // it must be a special case, check...
1375 switch (node->getOp()) {
1376 case glslang::EOpPostIncrement:
1377 case glslang::EOpPostDecrement:
1378 case glslang::EOpPreIncrement:
1379 case glslang::EOpPreDecrement:
1380 {
1381 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001382 spv::Id one = 0;
1383 if (node->getBasicType() == glslang::EbtFloat)
1384 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001385 else if (node->getBasicType() == glslang::EbtDouble)
1386 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001387#ifdef AMD_EXTENSIONS
1388 else if (node->getBasicType() == glslang::EbtFloat16)
1389 one = builder.makeFloat16Constant(1.0F);
1390#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001391 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1392 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001393#ifdef AMD_EXTENSIONS
1394 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1395 one = builder.makeInt16Constant(1);
1396#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001397 else
1398 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 glslang::TOperator op;
1400 if (node->getOp() == glslang::EOpPreIncrement ||
1401 node->getOp() == glslang::EOpPostIncrement)
1402 op = glslang::EOpAdd;
1403 else
1404 op = glslang::EOpSub;
1405
John Kessenichf6640762016-08-01 19:44:00 -06001406 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001407 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001408 convertGlslangToSpvType(node->getType()), operand, one,
1409 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001410 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 // The result of operation is always stored, but conditionally the
1413 // consumed result. The consumed result is always an r-value.
1414 builder.accessChainStore(result);
1415 builder.clearAccessChain();
1416 if (node->getOp() == glslang::EOpPreIncrement ||
1417 node->getOp() == glslang::EOpPreDecrement)
1418 builder.setAccessChainRValue(result);
1419 else
1420 builder.setAccessChainRValue(operand);
1421 }
1422
1423 return false;
1424
1425 case glslang::EOpEmitStreamVertex:
1426 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1427 return false;
1428 case glslang::EOpEndStreamPrimitive:
1429 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1430 return false;
1431
1432 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001433 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001434 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001435 }
John Kessenich140f3df2015-06-26 16:58:36 -06001436}
1437
1438bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1439{
qining27e04a02016-04-14 16:40:20 -04001440 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1441 if (node->getType().getQualifier().isSpecConstant())
1442 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1443
John Kessenichfc51d282015-08-19 13:34:18 -06001444 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001445 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1446 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001447
1448 // try texturing
1449 result = createImageTextureFunctionCall(node);
1450 if (result != spv::NoResult) {
1451 builder.clearAccessChain();
1452 builder.setAccessChainRValue(result);
1453
1454 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001455#ifdef AMD_EXTENSIONS
1456 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1457#else
John Kessenich56bab042015-09-16 10:54:31 -06001458 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001459#endif
Rex Xufc618912015-09-09 16:42:49 +08001460 // "imageStore" is a special case, which has no result
1461 return false;
1462 }
John Kessenichfc51d282015-08-19 13:34:18 -06001463
John Kessenich140f3df2015-06-26 16:58:36 -06001464 glslang::TOperator binOp = glslang::EOpNull;
1465 bool reduceComparison = true;
1466 bool isMatrix = false;
1467 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001468 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001469
1470 assert(node->getOp());
1471
John Kessenichf6640762016-08-01 19:44:00 -06001472 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001473
1474 switch (node->getOp()) {
1475 case glslang::EOpSequence:
1476 {
1477 if (preVisit)
1478 ++sequenceDepth;
1479 else
1480 --sequenceDepth;
1481
1482 if (sequenceDepth == 1) {
1483 // If this is the parent node of all the functions, we want to see them
1484 // early, so all call points have actual SPIR-V functions to reference.
1485 // In all cases, still let the traverser visit the children for us.
1486 makeFunctions(node->getAsAggregate()->getSequence());
1487
John Kessenich6fccb3c2016-09-19 16:01:41 -06001488 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001489 // anything else gets there, so visit out of order, doing them all now.
1490 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1491
John Kessenich6a60c2f2016-12-08 21:01:59 -07001492 // 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 -06001493 // so do them manually.
1494 visitFunctions(node->getAsAggregate()->getSequence());
1495
1496 return false;
1497 }
1498
1499 return true;
1500 }
1501 case glslang::EOpLinkerObjects:
1502 {
1503 if (visit == glslang::EvPreVisit)
1504 linkageOnly = true;
1505 else
1506 linkageOnly = false;
1507
1508 return true;
1509 }
1510 case glslang::EOpComma:
1511 {
1512 // processing from left to right naturally leaves the right-most
1513 // lying around in the access chain
1514 glslang::TIntermSequence& glslangOperands = node->getSequence();
1515 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1516 glslangOperands[i]->traverse(this);
1517
1518 return false;
1519 }
1520 case glslang::EOpFunction:
1521 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001522 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001523 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001524 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001525 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001526 } else {
1527 handleFunctionEntry(node);
1528 }
1529 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001530 if (inEntryPoint)
1531 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001532 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001533 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001534 }
1535
1536 return true;
1537 case glslang::EOpParameters:
1538 // Parameters will have been consumed by EOpFunction processing, but not
1539 // the body, so we still visited the function node's children, making this
1540 // child redundant.
1541 return false;
1542 case glslang::EOpFunctionCall:
1543 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001544 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001545 if (node->isUserDefined())
1546 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001547 // 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 -07001548 if (result) {
1549 builder.clearAccessChain();
1550 builder.setAccessChainRValue(result);
1551 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001552 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001553
1554 return false;
1555 }
1556 case glslang::EOpConstructMat2x2:
1557 case glslang::EOpConstructMat2x3:
1558 case glslang::EOpConstructMat2x4:
1559 case glslang::EOpConstructMat3x2:
1560 case glslang::EOpConstructMat3x3:
1561 case glslang::EOpConstructMat3x4:
1562 case glslang::EOpConstructMat4x2:
1563 case glslang::EOpConstructMat4x3:
1564 case glslang::EOpConstructMat4x4:
1565 case glslang::EOpConstructDMat2x2:
1566 case glslang::EOpConstructDMat2x3:
1567 case glslang::EOpConstructDMat2x4:
1568 case glslang::EOpConstructDMat3x2:
1569 case glslang::EOpConstructDMat3x3:
1570 case glslang::EOpConstructDMat3x4:
1571 case glslang::EOpConstructDMat4x2:
1572 case glslang::EOpConstructDMat4x3:
1573 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001574 case glslang::EOpConstructIMat2x2:
1575 case glslang::EOpConstructIMat2x3:
1576 case glslang::EOpConstructIMat2x4:
1577 case glslang::EOpConstructIMat3x2:
1578 case glslang::EOpConstructIMat3x3:
1579 case glslang::EOpConstructIMat3x4:
1580 case glslang::EOpConstructIMat4x2:
1581 case glslang::EOpConstructIMat4x3:
1582 case glslang::EOpConstructIMat4x4:
1583 case glslang::EOpConstructUMat2x2:
1584 case glslang::EOpConstructUMat2x3:
1585 case glslang::EOpConstructUMat2x4:
1586 case glslang::EOpConstructUMat3x2:
1587 case glslang::EOpConstructUMat3x3:
1588 case glslang::EOpConstructUMat3x4:
1589 case glslang::EOpConstructUMat4x2:
1590 case glslang::EOpConstructUMat4x3:
1591 case glslang::EOpConstructUMat4x4:
1592 case glslang::EOpConstructBMat2x2:
1593 case glslang::EOpConstructBMat2x3:
1594 case glslang::EOpConstructBMat2x4:
1595 case glslang::EOpConstructBMat3x2:
1596 case glslang::EOpConstructBMat3x3:
1597 case glslang::EOpConstructBMat3x4:
1598 case glslang::EOpConstructBMat4x2:
1599 case glslang::EOpConstructBMat4x3:
1600 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001601#ifdef AMD_EXTENSIONS
1602 case glslang::EOpConstructF16Mat2x2:
1603 case glslang::EOpConstructF16Mat2x3:
1604 case glslang::EOpConstructF16Mat2x4:
1605 case glslang::EOpConstructF16Mat3x2:
1606 case glslang::EOpConstructF16Mat3x3:
1607 case glslang::EOpConstructF16Mat3x4:
1608 case glslang::EOpConstructF16Mat4x2:
1609 case glslang::EOpConstructF16Mat4x3:
1610 case glslang::EOpConstructF16Mat4x4:
1611#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001612 isMatrix = true;
1613 // fall through
1614 case glslang::EOpConstructFloat:
1615 case glslang::EOpConstructVec2:
1616 case glslang::EOpConstructVec3:
1617 case glslang::EOpConstructVec4:
1618 case glslang::EOpConstructDouble:
1619 case glslang::EOpConstructDVec2:
1620 case glslang::EOpConstructDVec3:
1621 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001622#ifdef AMD_EXTENSIONS
1623 case glslang::EOpConstructFloat16:
1624 case glslang::EOpConstructF16Vec2:
1625 case glslang::EOpConstructF16Vec3:
1626 case glslang::EOpConstructF16Vec4:
1627#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001628 case glslang::EOpConstructBool:
1629 case glslang::EOpConstructBVec2:
1630 case glslang::EOpConstructBVec3:
1631 case glslang::EOpConstructBVec4:
1632 case glslang::EOpConstructInt:
1633 case glslang::EOpConstructIVec2:
1634 case glslang::EOpConstructIVec3:
1635 case glslang::EOpConstructIVec4:
1636 case glslang::EOpConstructUint:
1637 case glslang::EOpConstructUVec2:
1638 case glslang::EOpConstructUVec3:
1639 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001640 case glslang::EOpConstructInt64:
1641 case glslang::EOpConstructI64Vec2:
1642 case glslang::EOpConstructI64Vec3:
1643 case glslang::EOpConstructI64Vec4:
1644 case glslang::EOpConstructUint64:
1645 case glslang::EOpConstructU64Vec2:
1646 case glslang::EOpConstructU64Vec3:
1647 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001648#ifdef AMD_EXTENSIONS
1649 case glslang::EOpConstructInt16:
1650 case glslang::EOpConstructI16Vec2:
1651 case glslang::EOpConstructI16Vec3:
1652 case glslang::EOpConstructI16Vec4:
1653 case glslang::EOpConstructUint16:
1654 case glslang::EOpConstructU16Vec2:
1655 case glslang::EOpConstructU16Vec3:
1656 case glslang::EOpConstructU16Vec4:
1657#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001658 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001659 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001660 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001661 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001662 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001663 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001664 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001665 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001666 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001667 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001668 std::vector<spv::Id> constituents;
1669 for (int c = 0; c < (int)arguments.size(); ++c)
1670 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001671 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001672 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001673 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001674 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001675 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001676
1677 builder.clearAccessChain();
1678 builder.setAccessChainRValue(constructed);
1679
1680 return false;
1681 }
1682
1683 // These six are component-wise compares with component-wise results.
1684 // Forward on to createBinaryOperation(), requesting a vector result.
1685 case glslang::EOpLessThan:
1686 case glslang::EOpGreaterThan:
1687 case glslang::EOpLessThanEqual:
1688 case glslang::EOpGreaterThanEqual:
1689 case glslang::EOpVectorEqual:
1690 case glslang::EOpVectorNotEqual:
1691 {
1692 // Map the operation to a binary
1693 binOp = node->getOp();
1694 reduceComparison = false;
1695 switch (node->getOp()) {
1696 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1697 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1698 default: binOp = node->getOp(); break;
1699 }
1700
1701 break;
1702 }
1703 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001704 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001705 binOp = glslang::EOpMul;
1706 break;
1707 case glslang::EOpOuterProduct:
1708 // two vectors multiplied to make a matrix
1709 binOp = glslang::EOpOuterProduct;
1710 break;
1711 case glslang::EOpDot:
1712 {
qining25262b32016-05-06 17:25:16 -04001713 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001714 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001715 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001716 binOp = glslang::EOpMul;
1717 break;
1718 }
1719 case glslang::EOpMod:
1720 // when an aggregate, this is the floating-point mod built-in function,
1721 // which can be emitted by the one in createBinaryOperation()
1722 binOp = glslang::EOpMod;
1723 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001724 case glslang::EOpEmitVertex:
1725 case glslang::EOpEndPrimitive:
1726 case glslang::EOpBarrier:
1727 case glslang::EOpMemoryBarrier:
1728 case glslang::EOpMemoryBarrierAtomicCounter:
1729 case glslang::EOpMemoryBarrierBuffer:
1730 case glslang::EOpMemoryBarrierImage:
1731 case glslang::EOpMemoryBarrierShared:
1732 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001733 case glslang::EOpAllMemoryBarrierWithGroupSync:
1734 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1735 case glslang::EOpWorkgroupMemoryBarrier:
1736 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001737 noReturnValue = true;
1738 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1739 break;
1740
John Kessenich426394d2015-07-23 10:22:48 -06001741 case glslang::EOpAtomicAdd:
1742 case glslang::EOpAtomicMin:
1743 case glslang::EOpAtomicMax:
1744 case glslang::EOpAtomicAnd:
1745 case glslang::EOpAtomicOr:
1746 case glslang::EOpAtomicXor:
1747 case glslang::EOpAtomicExchange:
1748 case glslang::EOpAtomicCompSwap:
1749 atomic = true;
1750 break;
1751
John Kessenich0d0c6d32017-07-23 16:08:26 -06001752 case glslang::EOpAtomicCounterAdd:
1753 case glslang::EOpAtomicCounterSubtract:
1754 case glslang::EOpAtomicCounterMin:
1755 case glslang::EOpAtomicCounterMax:
1756 case glslang::EOpAtomicCounterAnd:
1757 case glslang::EOpAtomicCounterOr:
1758 case glslang::EOpAtomicCounterXor:
1759 case glslang::EOpAtomicCounterExchange:
1760 case glslang::EOpAtomicCounterCompSwap:
1761 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1762 builder.addCapability(spv::CapabilityAtomicStorageOps);
1763 atomic = true;
1764 break;
1765
John Kessenich140f3df2015-06-26 16:58:36 -06001766 default:
1767 break;
1768 }
1769
1770 //
1771 // See if it maps to a regular operation.
1772 //
John Kessenich140f3df2015-06-26 16:58:36 -06001773 if (binOp != glslang::EOpNull) {
1774 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1775 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1776 assert(left && right);
1777
1778 builder.clearAccessChain();
1779 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001780 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001781
1782 builder.clearAccessChain();
1783 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001784 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001785
John Kesseniche485c7a2017-05-31 18:50:53 -06001786 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001787 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001788 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001789 left->getType().getBasicType(), reduceComparison);
1790
1791 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001792 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001793 builder.clearAccessChain();
1794 builder.setAccessChainRValue(result);
1795
1796 return false;
1797 }
1798
John Kessenich426394d2015-07-23 10:22:48 -06001799 //
1800 // Create the list of operands.
1801 //
John Kessenich140f3df2015-06-26 16:58:36 -06001802 glslang::TIntermSequence& glslangOperands = node->getSequence();
1803 std::vector<spv::Id> operands;
1804 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001805 // special case l-value operands; there are just a few
1806 bool lvalue = false;
1807 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001808 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001809 case glslang::EOpModf:
1810 if (arg == 1)
1811 lvalue = true;
1812 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001813 case glslang::EOpInterpolateAtSample:
1814 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001815#ifdef AMD_EXTENSIONS
1816 case glslang::EOpInterpolateAtVertex:
1817#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001818 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001819 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001820
1821 // Does it need a swizzle inversion? If so, evaluation is inverted;
1822 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001823 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001824 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1825 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1826 }
Rex Xu7a26c172015-12-08 17:12:09 +08001827 break;
Rex Xud4782c12015-09-06 16:30:11 +08001828 case glslang::EOpAtomicAdd:
1829 case glslang::EOpAtomicMin:
1830 case glslang::EOpAtomicMax:
1831 case glslang::EOpAtomicAnd:
1832 case glslang::EOpAtomicOr:
1833 case glslang::EOpAtomicXor:
1834 case glslang::EOpAtomicExchange:
1835 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001836 case glslang::EOpAtomicCounterAdd:
1837 case glslang::EOpAtomicCounterSubtract:
1838 case glslang::EOpAtomicCounterMin:
1839 case glslang::EOpAtomicCounterMax:
1840 case glslang::EOpAtomicCounterAnd:
1841 case glslang::EOpAtomicCounterOr:
1842 case glslang::EOpAtomicCounterXor:
1843 case glslang::EOpAtomicCounterExchange:
1844 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001845 if (arg == 0)
1846 lvalue = true;
1847 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001848 case glslang::EOpAddCarry:
1849 case glslang::EOpSubBorrow:
1850 if (arg == 2)
1851 lvalue = true;
1852 break;
1853 case glslang::EOpUMulExtended:
1854 case glslang::EOpIMulExtended:
1855 if (arg >= 2)
1856 lvalue = true;
1857 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001858 default:
1859 break;
1860 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001861 builder.clearAccessChain();
1862 if (invertedType != spv::NoType && arg == 0)
1863 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1864 else
1865 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001866 if (lvalue)
1867 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001868 else {
1869 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001870 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001871 }
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
John Kessenich426394d2015-07-23 10:22:48 -06001873
John Kesseniche485c7a2017-05-31 18:50:53 -06001874 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001875 if (atomic) {
1876 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001877 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001878 } else {
1879 // Pass through to generic operations.
1880 switch (glslangOperands.size()) {
1881 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001882 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001883 break;
1884 case 1:
qining25262b32016-05-06 17:25:16 -04001885 result = createUnaryOperation(
1886 node->getOp(), precision,
1887 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001888 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001889 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001890 break;
1891 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001893 break;
1894 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001895 if (invertedType)
1896 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001897 }
1898
1899 if (noReturnValue)
1900 return false;
1901
1902 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001903 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001904 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001905 } else {
1906 builder.clearAccessChain();
1907 builder.setAccessChainRValue(result);
1908 return false;
1909 }
1910}
1911
John Kessenich433e9ff2017-01-26 20:31:11 -07001912// This path handles both if-then-else and ?:
1913// The if-then-else has a node type of void, while
1914// ?: has either a void or a non-void node type
1915//
1916// Leaving the result, when not void:
1917// GLSL only has r-values as the result of a :?, but
1918// if we have an l-value, that can be more efficient if it will
1919// become the base of a complex r-value expression, because the
1920// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001921bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1922{
John Kessenich433e9ff2017-01-26 20:31:11 -07001923 // See if it simple and safe to generate OpSelect instead of using control flow.
1924 // Crucially, side effects must be avoided, and there are performance trade-offs.
1925 // Return true if good idea (and safe) for OpSelect, false otherwise.
1926 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001927 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1928 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001929 return false;
1930
1931 if (node->getTrueBlock() == nullptr ||
1932 node->getFalseBlock() == nullptr)
1933 return false;
1934
1935 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1936 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1937
1938 // return true if a single operand to ? : is okay for OpSelect
1939 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001940 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001941 };
1942
1943 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1944 operandOkay(node->getFalseBlock()->getAsTyped());
1945 };
1946
1947 // Emit OpSelect for this selection.
1948 const auto handleAsOpSelect = [&]() {
1949 node->getCondition()->traverse(this);
1950 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1951 node->getTrueBlock()->traverse(this);
1952 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1953 node->getFalseBlock()->traverse(this);
1954 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1955
John Kesseniche485c7a2017-05-31 18:50:53 -06001956 builder.setLine(node->getLoc().line);
1957
John Kesseniche434ad92017-03-30 10:09:28 -06001958 // smear condition to vector, if necessary (AST is always scalar)
1959 if (builder.isVector(trueValue))
1960 condition = builder.smearScalar(spv::NoPrecision, condition,
1961 builder.makeVectorType(builder.makeBoolType(),
1962 builder.getNumComponents(trueValue)));
1963
1964 spv::Id select = builder.createTriOp(spv::OpSelect,
1965 convertGlslangToSpvType(node->getType()), condition,
1966 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001967 builder.clearAccessChain();
1968 builder.setAccessChainRValue(select);
1969 };
1970
1971 // Try for OpSelect
1972
1973 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001974 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1975 if (node->getType().getQualifier().isSpecConstant())
1976 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1977
John Kessenich433e9ff2017-01-26 20:31:11 -07001978 handleAsOpSelect();
1979 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001980 }
1981
Rex Xu57e65922017-07-04 23:23:40 +08001982 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001983 // Don't handle results as temporaries, because there will be two names
1984 // and better to leave SSA to later passes.
1985 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1986 ? spv::NoResult
1987 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1988
John Kessenich140f3df2015-06-26 16:58:36 -06001989 // emit the condition before doing anything with selection
1990 node->getCondition()->traverse(this);
1991
Rex Xu57e65922017-07-04 23:23:40 +08001992 // Selection control:
1993 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
1994
John Kessenich140f3df2015-06-26 16:58:36 -06001995 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08001996 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001997
John Kessenich433e9ff2017-01-26 20:31:11 -07001998 // emit the "then" statement
1999 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002000 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002001 if (result != spv::NoResult)
2002 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002003 }
2004
John Kessenich433e9ff2017-01-26 20:31:11 -07002005 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002006 ifBuilder.makeBeginElse();
2007 // emit the "else" statement
2008 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002009 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002010 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002011 }
2012
John Kessenich433e9ff2017-01-26 20:31:11 -07002013 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002014 ifBuilder.makeEndIf();
2015
John Kessenich433e9ff2017-01-26 20:31:11 -07002016 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002017 // GLSL only has r-values as the result of a :?, but
2018 // if we have an l-value, that can be more efficient if it will
2019 // become the base of a complex r-value expression, because the
2020 // next layer copies r-values into memory to use the access-chain mechanism
2021 builder.clearAccessChain();
2022 builder.setAccessChainLValue(result);
2023 }
2024
2025 return false;
2026}
2027
2028bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2029{
2030 // emit and get the condition before doing anything with switch
2031 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002032 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002033
Rex Xu57e65922017-07-04 23:23:40 +08002034 // Selection control:
2035 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2036
John Kessenich140f3df2015-06-26 16:58:36 -06002037 // browse the children to sort out code segments
2038 int defaultSegment = -1;
2039 std::vector<TIntermNode*> codeSegments;
2040 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2041 std::vector<int> caseValues;
2042 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2043 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2044 TIntermNode* child = *c;
2045 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002046 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002047 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002048 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002049 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2050 } else
2051 codeSegments.push_back(child);
2052 }
2053
qining25262b32016-05-06 17:25:16 -04002054 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002055 // statements between the last case and the end of the switch statement
2056 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2057 (int)codeSegments.size() == defaultSegment)
2058 codeSegments.push_back(nullptr);
2059
2060 // make the switch statement
2061 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002062 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002063
2064 // emit all the code in the segments
2065 breakForLoop.push(false);
2066 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2067 builder.nextSwitchSegment(segmentBlocks, s);
2068 if (codeSegments[s])
2069 codeSegments[s]->traverse(this);
2070 else
2071 builder.addSwitchBreak();
2072 }
2073 breakForLoop.pop();
2074
2075 builder.endSwitch(segmentBlocks);
2076
2077 return false;
2078}
2079
2080void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2081{
2082 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002083 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002084
2085 builder.clearAccessChain();
2086 builder.setAccessChainRValue(constant);
2087}
2088
2089bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2090{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002091 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002092 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002093
2094 // Loop control:
2095 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2096
2097 // TODO: dependency length
2098
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002099 // Spec requires back edges to target header blocks, and every header block
2100 // must dominate its merge block. Make a header block first to ensure these
2101 // conditions are met. By definition, it will contain OpLoopMerge, followed
2102 // by a block-ending branch. But we don't want to put any other body/test
2103 // instructions in it, since the body/test may have arbitrary instructions,
2104 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002105 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002106 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002107 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002108 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002109 spv::Block& test = builder.makeNewBlock();
2110 builder.createBranch(&test);
2111
2112 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002113 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002114 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002115 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2116
2117 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002118 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002119 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002120 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002121 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002122 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002123
2124 builder.setBuildPoint(&blocks.continue_target);
2125 if (node->getTerminal())
2126 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002127 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002128 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002129 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002130 builder.createBranch(&blocks.body);
2131
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002132 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002133 builder.setBuildPoint(&blocks.body);
2134 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002135 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002136 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002137 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002138
2139 builder.setBuildPoint(&blocks.continue_target);
2140 if (node->getTerminal())
2141 node->getTerminal()->traverse(this);
2142 if (node->getTest()) {
2143 node->getTest()->traverse(this);
2144 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002145 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002146 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002147 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002148 // TODO: unless there was a break/return/discard instruction
2149 // somewhere in the body, this is an infinite loop, so we should
2150 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002151 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002152 }
John Kessenich140f3df2015-06-26 16:58:36 -06002153 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002155 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002156 return false;
2157}
2158
2159bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2160{
2161 if (node->getExpression())
2162 node->getExpression()->traverse(this);
2163
John Kesseniche485c7a2017-05-31 18:50:53 -06002164 builder.setLine(node->getLoc().line);
2165
John Kessenich140f3df2015-06-26 16:58:36 -06002166 switch (node->getFlowOp()) {
2167 case glslang::EOpKill:
2168 builder.makeDiscard();
2169 break;
2170 case glslang::EOpBreak:
2171 if (breakForLoop.top())
2172 builder.createLoopExit();
2173 else
2174 builder.addSwitchBreak();
2175 break;
2176 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002177 builder.createLoopContinue();
2178 break;
2179 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002180 if (node->getExpression()) {
2181 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2182 spv::Id returnId = accessChainLoad(glslangReturnType);
2183 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2184 builder.clearAccessChain();
2185 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2186 builder.setAccessChainLValue(copyId);
2187 multiTypeStore(glslangReturnType, returnId);
2188 returnId = builder.createLoad(copyId);
2189 }
2190 builder.makeReturn(false, returnId);
2191 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002192 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002193
2194 builder.clearAccessChain();
2195 break;
2196
2197 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002198 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002199 break;
2200 }
2201
2202 return false;
2203}
2204
2205spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2206{
qining25262b32016-05-06 17:25:16 -04002207 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002208 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002209 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002210 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002211 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002212 }
2213
2214 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002215 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002216 spv::Id spvType = convertGlslangToSpvType(node->getType());
2217
Rex Xuf89ad982017-04-07 23:22:33 +08002218#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002219 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2220 node->getType().containsBasicType(glslang::EbtInt16) ||
2221 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002222 if (contains16BitType) {
2223 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2224 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2225 builder.addCapability(spv::CapabilityStorageInputOutput16);
2226 } else if (storageClass == spv::StorageClassPushConstant) {
2227 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2228 builder.addCapability(spv::CapabilityStoragePushConstant16);
2229 } else if (storageClass == spv::StorageClassUniform) {
2230 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2231 builder.addCapability(spv::CapabilityStorageUniform16);
2232 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2233 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2234 }
2235 }
2236#endif
2237
John Kessenich140f3df2015-06-26 16:58:36 -06002238 const char* name = node->getName().c_str();
2239 if (glslang::IsAnonymous(name))
2240 name = "";
2241
2242 return builder.createVariable(storageClass, spvType, name);
2243}
2244
2245// Return type Id of the sampled type.
2246spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2247{
2248 switch (sampler.type) {
2249 case glslang::EbtFloat: return builder.makeFloatType(32);
2250 case glslang::EbtInt: return builder.makeIntType(32);
2251 case glslang::EbtUint: return builder.makeUintType(32);
2252 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002254 return builder.makeFloatType(32);
2255 }
2256}
2257
John Kessenich8c8505c2016-07-26 12:50:38 -06002258// If node is a swizzle operation, return the type that should be used if
2259// the swizzle base is first consumed by another operation, before the swizzle
2260// is applied.
2261spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2262{
John Kessenichecba76f2017-01-06 00:34:48 -07002263 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002264 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2265 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2266 else
2267 return spv::NoType;
2268}
2269
2270// When inverting a swizzle with a parent op, this function
2271// will apply the swizzle operation to a completed parent operation.
2272spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2273{
2274 std::vector<unsigned> swizzle;
2275 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2276 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2277}
2278
John Kessenich8c8505c2016-07-26 12:50:38 -06002279// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2280void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2281{
2282 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2283 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2284 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2285}
2286
John Kessenich3ac051e2015-12-20 11:29:16 -07002287// Convert from a glslang type to an SPV type, by calling into a
2288// recursive version of this function. This establishes the inherited
2289// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002290spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2291{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002292 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002293}
2294
2295// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002296// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002297// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002298spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002299{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002300 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002301
2302 switch (type.getBasicType()) {
2303 case glslang::EbtVoid:
2304 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002305 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002306 break;
2307 case glslang::EbtFloat:
2308 spvType = builder.makeFloatType(32);
2309 break;
2310 case glslang::EbtDouble:
2311 spvType = builder.makeFloatType(64);
2312 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002313#ifdef AMD_EXTENSIONS
2314 case glslang::EbtFloat16:
2315 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002316 spvType = builder.makeFloatType(16);
2317 break;
2318#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002319 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002320 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2321 // a 32-bit int where non-0 means true.
2322 if (explicitLayout != glslang::ElpNone)
2323 spvType = builder.makeUintType(32);
2324 else
2325 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002326 break;
2327 case glslang::EbtInt:
2328 spvType = builder.makeIntType(32);
2329 break;
2330 case glslang::EbtUint:
2331 spvType = builder.makeUintType(32);
2332 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002333 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002334 spvType = builder.makeIntType(64);
2335 break;
2336 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002337 spvType = builder.makeUintType(64);
2338 break;
Rex Xucabbb782017-03-24 13:41:14 +08002339#ifdef AMD_EXTENSIONS
2340 case glslang::EbtInt16:
2341 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2342 spvType = builder.makeIntType(16);
2343 break;
2344 case glslang::EbtUint16:
2345 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2346 spvType = builder.makeUintType(16);
2347 break;
2348#endif
John Kessenich426394d2015-07-23 10:22:48 -06002349 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002350 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002351 spvType = builder.makeUintType(32);
2352 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002353 case glslang::EbtSampler:
2354 {
2355 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002356 if (sampler.sampler) {
2357 // pure sampler
2358 spvType = builder.makeSamplerType();
2359 } else {
2360 // an image is present, make its type
2361 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2362 sampler.image ? 2 : 1, TranslateImageFormat(type));
2363 if (sampler.combined) {
2364 // already has both image and sampler, make the combined type
2365 spvType = builder.makeSampledImageType(spvType);
2366 }
John Kessenich55e7d112015-11-15 21:33:39 -07002367 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002368 }
John Kessenich140f3df2015-06-26 16:58:36 -06002369 break;
2370 case glslang::EbtStruct:
2371 case glslang::EbtBlock:
2372 {
2373 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002374 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002375
2376 // Try to share structs for different layouts, but not yet for other
2377 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002378 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002379 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002380 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002381 break;
2382
2383 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002384 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002385 memberRemapper[glslangMembers].resize(glslangMembers->size());
2386 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002387 }
2388 break;
2389 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002390 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002391 break;
2392 }
2393
2394 if (type.isMatrix())
2395 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2396 else {
2397 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2398 if (type.getVectorSize() > 1)
2399 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2400 }
2401
2402 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002403 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2404
John Kessenichc9a80832015-09-12 12:17:44 -06002405 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002406 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002407 // We need to decorate array strides for types needing explicit layout, except blocks.
2408 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002409 // Use a dummy glslang type for querying internal strides of
2410 // arrays of arrays, but using just a one-dimensional array.
2411 glslang::TType simpleArrayType(type, 0); // deference type of the array
2412 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2413 simpleArrayType.getArraySizes().dereference();
2414
2415 // Will compute the higher-order strides here, rather than making a whole
2416 // pile of types and doing repetitive recursion on their contents.
2417 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2418 }
John Kessenichf8842e52016-01-04 19:22:56 -07002419
2420 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002421 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002422 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002423 if (stride > 0)
2424 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002425 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002426 }
2427 } else {
2428 // single-dimensional array, and don't yet have stride
2429
John Kessenichf8842e52016-01-04 19:22:56 -07002430 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002431 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2432 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002433 }
John Kessenich31ed4832015-09-09 17:51:38 -06002434
John Kessenichc9a80832015-09-12 12:17:44 -06002435 // Do the outer dimension, which might not be known for a runtime-sized array
2436 if (type.isRuntimeSizedArray()) {
2437 spvType = builder.makeRuntimeArray(spvType);
2438 } else {
2439 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002440 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002441 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 if (stride > 0)
2443 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002444 }
2445
2446 return spvType;
2447}
2448
John Kessenich0e737842017-03-24 18:38:16 -06002449// TODO: this functionality should exist at a higher level, in creating the AST
2450//
2451// Identify interface members that don't have their required extension turned on.
2452//
2453bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2454{
2455 auto& extensions = glslangIntermediate->getRequestedExtensions();
2456
Rex Xubcf291a2017-03-29 23:01:36 +08002457 if (member.getFieldName() == "gl_ViewportMask" &&
2458 extensions.find("GL_NV_viewport_array2") == extensions.end())
2459 return true;
2460 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2461 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2462 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002463 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2464 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2465 return true;
2466 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2467 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2468 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002469 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2470 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2471 return true;
John Kessenichd6be6da2017-08-17 23:49:39 -06002472 if ((member.getFieldName() == "gl_ViewportIndex" || member.getFieldName() == "gl_Layer") &&
2473 extensions.find(glslang::E_GL_ARB_shader_viewport_layer_array) == extensions.end() &&
John Kessenich786e8792017-08-19 15:54:49 -06002474 extensions.find("GL_NV_viewport_array2") == extensions.end())
John Kessenichd6be6da2017-08-17 23:49:39 -06002475 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002476
2477 return false;
2478};
2479
John Kessenich6090df02016-06-30 21:18:02 -06002480// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2481// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2482// Mutually recursive with convertGlslangToSpvType().
2483spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2484 const glslang::TTypeList* glslangMembers,
2485 glslang::TLayoutPacking explicitLayout,
2486 const glslang::TQualifier& qualifier)
2487{
2488 // Create a vector of struct types for SPIR-V to consume
2489 std::vector<spv::Id> spvMembers;
2490 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 -06002491 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2492 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2493 if (glslangMember.hiddenMember()) {
2494 ++memberDelta;
2495 if (type.getBasicType() == glslang::EbtBlock)
2496 memberRemapper[glslangMembers][i] = -1;
2497 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002498 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002499 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002500 if (filterMember(glslangMember))
2501 continue;
2502 }
John Kessenich6090df02016-06-30 21:18:02 -06002503 // modify just this child's view of the qualifier
2504 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2505 InheritQualifiers(memberQualifier, qualifier);
2506
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002507 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002508 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002509 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002510
2511 // recurse
2512 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2513 }
2514 }
2515
2516 // Make the SPIR-V type
2517 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002518 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002519 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2520
2521 // Decorate it
2522 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2523
2524 return spvType;
2525}
2526
2527void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2528 const glslang::TTypeList* glslangMembers,
2529 glslang::TLayoutPacking explicitLayout,
2530 const glslang::TQualifier& qualifier,
2531 spv::Id spvType)
2532{
2533 // Name and decorate the non-hidden members
2534 int offset = -1;
2535 int locationOffset = 0; // for use within the members of this struct
2536 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2537 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2538 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002539 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002540 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002541 if (filterMember(glslangMember))
2542 continue;
2543 }
John Kessenich6090df02016-06-30 21:18:02 -06002544
2545 // modify just this child's view of the qualifier
2546 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2547 InheritQualifiers(memberQualifier, qualifier);
2548
2549 // using -1 above to indicate a hidden member
2550 if (member >= 0) {
2551 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2552 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2553 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2554 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002555 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2556 type.getQualifier().storage == glslang::EvqVaryingOut) {
2557 if (type.getBasicType() == glslang::EbtBlock ||
2558 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002559 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2560 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2561 }
2562 }
2563 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2564
Rex Xu286ca432017-07-27 14:33:16 +08002565 if (type.getBasicType() == glslang::EbtBlock &&
2566 qualifier.storage == glslang::EvqBuffer) {
2567 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002568 std::vector<spv::Decoration> memory;
2569 TranslateMemoryDecoration(memberQualifier, memory);
2570 for (unsigned int i = 0; i < memory.size(); ++i)
2571 addMemberDecoration(spvType, member, memory[i]);
2572 }
2573
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002574 // Location assignment was already completed correctly by the front end,
2575 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002576 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002577 // ill-specified and decisions have been made to not allow this.
2578 if (! type.isArray() && memberQualifier.hasLocation())
2579 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002580
John Kessenich2f47bc92016-06-30 21:47:35 -06002581 if (qualifier.hasLocation()) // track for upcoming inheritance
2582 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2583
John Kessenich6090df02016-06-30 21:18:02 -06002584 // component, XFB, others
2585 if (glslangMember.getQualifier().hasComponent())
2586 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2587 if (glslangMember.getQualifier().hasXfbOffset())
2588 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2589 else if (explicitLayout != glslang::ElpNone) {
2590 // figure out what to do with offset, which is accumulating
2591 int nextOffset;
2592 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2593 if (offset >= 0)
2594 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2595 offset = nextOffset;
2596 }
2597
2598 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2599 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2600
2601 // built-in variable decorations
2602 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002603 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002604 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002605
2606#ifdef NV_EXTENSIONS
2607 if (builtIn == spv::BuiltInLayer) {
2608 // SPV_NV_viewport_array2 extension
2609 if (glslangMember.getQualifier().layoutViewportRelative){
2610 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2611 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2612 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2613 }
2614 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2615 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2616 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2617 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2618 }
2619 }
chaocdf3956c2017-02-14 14:52:34 -08002620 if (glslangMember.getQualifier().layoutPassthrough) {
2621 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2622 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2623 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2624 }
chaoc771d89f2017-01-13 01:10:53 -08002625#endif
John Kessenich6090df02016-06-30 21:18:02 -06002626 }
2627 }
2628
2629 // Decorate the structure
2630 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002631 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002632 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2633 builder.addCapability(spv::CapabilityGeometryStreams);
2634 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2635 }
2636 if (glslangIntermediate->getXfbMode()) {
2637 builder.addCapability(spv::CapabilityTransformFeedback);
2638 if (type.getQualifier().hasXfbStride())
2639 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2640 if (type.getQualifier().hasXfbBuffer())
2641 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2642 }
2643}
2644
John Kessenich6c292d32016-02-15 20:58:50 -07002645// Turn the expression forming the array size into an id.
2646// This is not quite trivial, because of specialization constants.
2647// Sometimes, a raw constant is turned into an Id, and sometimes
2648// a specialization constant expression is.
2649spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2650{
2651 // First, see if this is sized with a node, meaning a specialization constant:
2652 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2653 if (specNode != nullptr) {
2654 builder.clearAccessChain();
2655 specNode->traverse(this);
2656 return accessChainLoad(specNode->getAsTyped()->getType());
2657 }
qining25262b32016-05-06 17:25:16 -04002658
John Kessenich6c292d32016-02-15 20:58:50 -07002659 // Otherwise, need a compile-time (front end) size, get it:
2660 int size = arraySizes.getDimSize(dim);
2661 assert(size > 0);
2662 return builder.makeUintConstant(size);
2663}
2664
John Kessenich103bef92016-02-08 21:38:15 -07002665// Wrap the builder's accessChainLoad to:
2666// - localize handling of RelaxedPrecision
2667// - use the SPIR-V inferred type instead of another conversion of the glslang type
2668// (avoids unnecessary work and possible type punning for structures)
2669// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002670spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2671{
John Kessenich103bef92016-02-08 21:38:15 -07002672 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2673 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2674
2675 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002676 if (type.getBasicType() == glslang::EbtBool) {
2677 if (builder.isScalarType(nominalTypeId)) {
2678 // Conversion for bool
2679 spv::Id boolType = builder.makeBoolType();
2680 if (nominalTypeId != boolType)
2681 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2682 } else if (builder.isVectorType(nominalTypeId)) {
2683 // Conversion for bvec
2684 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2685 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2686 if (nominalTypeId != bvecType)
2687 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2688 }
2689 }
John Kessenich103bef92016-02-08 21:38:15 -07002690
2691 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002692}
2693
Rex Xu27253232016-02-23 17:51:09 +08002694// Wrap the builder's accessChainStore to:
2695// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002696//
2697// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002698void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2699{
2700 // Need to convert to abstract types when necessary
2701 if (type.getBasicType() == glslang::EbtBool) {
2702 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2703
2704 if (builder.isScalarType(nominalTypeId)) {
2705 // Conversion for bool
2706 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002707 if (nominalTypeId != boolType) {
2708 // keep these outside arguments, for determinant order-of-evaluation
2709 spv::Id one = builder.makeUintConstant(1);
2710 spv::Id zero = builder.makeUintConstant(0);
2711 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2712 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002713 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002714 } else if (builder.isVectorType(nominalTypeId)) {
2715 // Conversion for bvec
2716 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2717 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002718 if (nominalTypeId != bvecType) {
2719 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002720 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2721 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2722 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002723 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002724 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2725 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002726 }
2727 }
2728
2729 builder.accessChainStore(rvalue);
2730}
2731
John Kessenich4bf71552016-09-02 11:20:21 -06002732// For storing when types match at the glslang level, but not might match at the
2733// SPIR-V level.
2734//
2735// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002736// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002737// as in a member-decorated way.
2738//
2739// NOTE: This function can handle any store request; if it's not special it
2740// simplifies to a simple OpStore.
2741//
2742// Implicitly uses the existing builder.accessChain as the storage target.
2743void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2744{
John Kessenichb3e24e42016-09-11 12:33:43 -06002745 // we only do the complex path here if it's an aggregate
2746 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002747 accessChainStore(type, rValue);
2748 return;
2749 }
2750
John Kessenichb3e24e42016-09-11 12:33:43 -06002751 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002752 spv::Id rType = builder.getTypeId(rValue);
2753 spv::Id lValue = builder.accessChainGetLValue();
2754 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2755 if (lType == rType) {
2756 accessChainStore(type, rValue);
2757 return;
2758 }
2759
John Kessenichb3e24e42016-09-11 12:33:43 -06002760 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002761 // where the two types were the same type in GLSL. This requires member
2762 // by member copy, recursively.
2763
John Kessenichb3e24e42016-09-11 12:33:43 -06002764 // If an array, copy element by element.
2765 if (type.isArray()) {
2766 glslang::TType glslangElementType(type, 0);
2767 spv::Id elementRType = builder.getContainedTypeId(rType);
2768 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2769 // get the source member
2770 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002771
John Kessenichb3e24e42016-09-11 12:33:43 -06002772 // set up the target storage
2773 builder.clearAccessChain();
2774 builder.setAccessChainLValue(lValue);
2775 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002776
John Kessenichb3e24e42016-09-11 12:33:43 -06002777 // store the member
2778 multiTypeStore(glslangElementType, elementRValue);
2779 }
2780 } else {
2781 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002782
John Kessenichb3e24e42016-09-11 12:33:43 -06002783 // loop over structure members
2784 const glslang::TTypeList& members = *type.getStruct();
2785 for (int m = 0; m < (int)members.size(); ++m) {
2786 const glslang::TType& glslangMemberType = *members[m].type;
2787
2788 // get the source member
2789 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2790 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2791
2792 // set up the target storage
2793 builder.clearAccessChain();
2794 builder.setAccessChainLValue(lValue);
2795 builder.accessChainPush(builder.makeIntConstant(m));
2796
2797 // store the member
2798 multiTypeStore(glslangMemberType, memberRValue);
2799 }
John Kessenich4bf71552016-09-02 11:20:21 -06002800 }
2801}
2802
John Kessenichf85e8062015-12-19 13:57:10 -07002803// Decide whether or not this type should be
2804// decorated with offsets and strides, and if so
2805// whether std140 or std430 rules should be applied.
2806glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002807{
John Kessenichf85e8062015-12-19 13:57:10 -07002808 // has to be a block
2809 if (type.getBasicType() != glslang::EbtBlock)
2810 return glslang::ElpNone;
2811
2812 // has to be a uniform or buffer block
2813 if (type.getQualifier().storage != glslang::EvqUniform &&
2814 type.getQualifier().storage != glslang::EvqBuffer)
2815 return glslang::ElpNone;
2816
2817 // return the layout to use
2818 switch (type.getQualifier().layoutPacking) {
2819 case glslang::ElpStd140:
2820 case glslang::ElpStd430:
2821 return type.getQualifier().layoutPacking;
2822 default:
2823 return glslang::ElpNone;
2824 }
John Kessenich31ed4832015-09-09 17:51:38 -06002825}
2826
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002827// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002828int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002829{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002830 int size;
John Kessenich49987892015-12-29 17:11:44 -07002831 int stride;
2832 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002833
2834 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002835}
2836
John Kessenich49987892015-12-29 17:11:44 -07002837// 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 -07002838// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002839int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002840{
John Kessenich49987892015-12-29 17:11:44 -07002841 glslang::TType elementType;
2842 elementType.shallowCopy(matrixType);
2843 elementType.clearArraySizes();
2844
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002845 int size;
John Kessenich49987892015-12-29 17:11:44 -07002846 int stride;
2847 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2848
2849 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002850}
2851
John Kessenich5e4b1242015-08-06 22:53:06 -06002852// Given a member type of a struct, realign the current offset for it, and compute
2853// the next (not yet aligned) offset for the next member, which will get aligned
2854// on the next call.
2855// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2856// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2857// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002858void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002859 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002860{
2861 // this will get a positive value when deemed necessary
2862 nextOffset = -1;
2863
John Kessenich5e4b1242015-08-06 22:53:06 -06002864 // override anything in currentOffset with user-set offset
2865 if (memberType.getQualifier().hasOffset())
2866 currentOffset = memberType.getQualifier().layoutOffset;
2867
2868 // It could be that current linker usage in glslang updated all the layoutOffset,
2869 // in which case the following code does not matter. But, that's not quite right
2870 // once cross-compilation unit GLSL validation is done, as the original user
2871 // settings are needed in layoutOffset, and then the following will come into play.
2872
John Kessenichf85e8062015-12-19 13:57:10 -07002873 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002874 if (! memberType.getQualifier().hasOffset())
2875 currentOffset = -1;
2876
2877 return;
2878 }
2879
John Kessenichf85e8062015-12-19 13:57:10 -07002880 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002881 if (currentOffset < 0)
2882 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002883
John Kessenich5e4b1242015-08-06 22:53:06 -06002884 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2885 // but possibly not yet correctly aligned.
2886
2887 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002888 int dummyStride;
2889 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002890
2891 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002892 // TODO: make this consistent in early phases of code:
2893 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2894 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2895 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002896 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002897 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002898 int dummySize;
2899 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2900 if (componentAlignment <= 4)
2901 memberAlignment = componentAlignment;
2902 }
2903
2904 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002906
2907 // Bump up to vec4 if there is a bad straddle
2908 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2909 glslang::RoundToPow2(currentOffset, 16);
2910
John Kessenich5e4b1242015-08-06 22:53:06 -06002911 nextOffset = currentOffset + memberSize;
2912}
2913
David Netoa901ffe2016-06-08 14:11:40 +01002914void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002915{
David Netoa901ffe2016-06-08 14:11:40 +01002916 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2917 switch (glslangBuiltIn)
2918 {
2919 case glslang::EbvClipDistance:
2920 case glslang::EbvCullDistance:
2921 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002922#ifdef NV_EXTENSIONS
2923 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002924 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002925 case glslang::EbvViewportMaskNV:
2926 case glslang::EbvSecondaryPositionNV:
2927 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002928 case glslang::EbvPositionPerViewNV:
2929 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002930#endif
David Netoa901ffe2016-06-08 14:11:40 +01002931 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2932 // Alternately, we could just call this for any glslang built-in, since the
2933 // capability already guards against duplicates.
2934 TranslateBuiltInDecoration(glslangBuiltIn, false);
2935 break;
2936 default:
2937 // Capabilities were already generated when the struct was declared.
2938 break;
2939 }
John Kessenichebb50532016-05-16 19:22:05 -06002940}
2941
John Kessenich6fccb3c2016-09-19 16:01:41 -06002942bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002943{
John Kessenicheee9d532016-09-19 18:09:30 -06002944 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002945}
2946
2947// Make all the functions, skeletally, without actually visiting their bodies.
2948void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2949{
John Kessenichfad62972017-07-18 02:35:46 -06002950 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2951 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2952 if (paramPrecision != spv::NoPrecision)
2953 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002954 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002955 };
2956
John Kessenich140f3df2015-06-26 16:58:36 -06002957 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2958 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002959 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002960 continue;
2961
2962 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002963 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002964 //
qining25262b32016-05-06 17:25:16 -04002965 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002966 // function. What it is an address of varies:
2967 //
John Kessenich4bf71552016-09-02 11:20:21 -06002968 // - "in" parameters not marked as "const" can be written to without modifying the calling
2969 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002970 //
2971 // - "const in" parameters can just be the r-value, as no writes need occur.
2972 //
John Kessenich4bf71552016-09-02 11:20:21 -06002973 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2974 // 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 -06002975
2976 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002977 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002978 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2979
John Kessenichfad62972017-07-18 02:35:46 -06002980 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2981 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002982
John Kessenichfad62972017-07-18 02:35:46 -06002983 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002984 for (int p = 0; p < (int)parameters.size(); ++p) {
2985 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2986 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002987 // can we pass by reference?
2988 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002989 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002990 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002991 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002992 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002993 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002994 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2995 else
John Kessenich4bf71552016-09-02 11:20:21 -06002996 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06002997 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06002998 paramTypes.push_back(typeId);
2999 }
3000
3001 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003002 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3003 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003004 glslFunction->getName().c_str(), paramTypes,
3005 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003006 if (implicitThis)
3007 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003008
3009 // Track function to emit/call later
3010 functionMap[glslFunction->getName().c_str()] = function;
3011
3012 // Set the parameter id's
3013 for (int p = 0; p < (int)parameters.size(); ++p) {
3014 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3015 // give a name too
3016 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3017 }
3018 }
3019}
3020
3021// Process all the initializers, while skipping the functions and link objects
3022void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3023{
3024 builder.setBuildPoint(shaderEntry->getLastBlock());
3025 for (int i = 0; i < (int)initializers.size(); ++i) {
3026 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3027 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3028
3029 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003030 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003031 initializer->traverse(this);
3032 }
3033 }
3034}
3035
3036// Process all the functions, while skipping initializers.
3037void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3038{
3039 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3040 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003041 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003042 node->traverse(this);
3043 }
3044}
3045
3046void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3047{
qining25262b32016-05-06 17:25:16 -04003048 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003049 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003050 currentFunction = functionMap[node->getName().c_str()];
3051 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003052 builder.setBuildPoint(functionBlock);
3053}
3054
Rex Xu04db3f52015-09-16 11:44:02 +08003055void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003056{
Rex Xufc618912015-09-09 16:42:49 +08003057 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003058
3059 glslang::TSampler sampler = {};
3060 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003061 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003062 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3063 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3064 }
3065
John Kessenich140f3df2015-06-26 16:58:36 -06003066 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3067 builder.clearAccessChain();
3068 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003069
3070 // Special case l-value operands
3071 bool lvalue = false;
3072 switch (node.getOp()) {
3073 case glslang::EOpImageAtomicAdd:
3074 case glslang::EOpImageAtomicMin:
3075 case glslang::EOpImageAtomicMax:
3076 case glslang::EOpImageAtomicAnd:
3077 case glslang::EOpImageAtomicOr:
3078 case glslang::EOpImageAtomicXor:
3079 case glslang::EOpImageAtomicExchange:
3080 case glslang::EOpImageAtomicCompSwap:
3081 if (i == 0)
3082 lvalue = true;
3083 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003084 case glslang::EOpSparseImageLoad:
3085 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3086 lvalue = true;
3087 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003088 case glslang::EOpSparseTexture:
3089 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3090 lvalue = true;
3091 break;
3092 case glslang::EOpSparseTextureClamp:
3093 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3094 lvalue = true;
3095 break;
3096 case glslang::EOpSparseTextureLod:
3097 case glslang::EOpSparseTextureOffset:
3098 if (i == 3)
3099 lvalue = true;
3100 break;
3101 case glslang::EOpSparseTextureFetch:
3102 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3103 lvalue = true;
3104 break;
3105 case glslang::EOpSparseTextureFetchOffset:
3106 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3107 lvalue = true;
3108 break;
3109 case glslang::EOpSparseTextureLodOffset:
3110 case glslang::EOpSparseTextureGrad:
3111 case glslang::EOpSparseTextureOffsetClamp:
3112 if (i == 4)
3113 lvalue = true;
3114 break;
3115 case glslang::EOpSparseTextureGradOffset:
3116 case glslang::EOpSparseTextureGradClamp:
3117 if (i == 5)
3118 lvalue = true;
3119 break;
3120 case glslang::EOpSparseTextureGradOffsetClamp:
3121 if (i == 6)
3122 lvalue = true;
3123 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003124 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003125 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3126 lvalue = true;
3127 break;
3128 case glslang::EOpSparseTextureGatherOffset:
3129 case glslang::EOpSparseTextureGatherOffsets:
3130 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3131 lvalue = true;
3132 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003133#ifdef AMD_EXTENSIONS
3134 case glslang::EOpSparseTextureGatherLod:
3135 if (i == 3)
3136 lvalue = true;
3137 break;
3138 case glslang::EOpSparseTextureGatherLodOffset:
3139 case glslang::EOpSparseTextureGatherLodOffsets:
3140 if (i == 4)
3141 lvalue = true;
3142 break;
Rex Xu129799a2017-07-05 17:23:28 +08003143 case glslang::EOpSparseImageLoadLod:
3144 if (i == 3)
3145 lvalue = true;
3146 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003147#endif
Rex Xufc618912015-09-09 16:42:49 +08003148 default:
3149 break;
3150 }
3151
Rex Xu6b86d492015-09-16 17:48:22 +08003152 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003153 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003154 else
John Kessenich32cfd492016-02-02 12:37:46 -07003155 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003156 }
3157}
3158
John Kessenichfc51d282015-08-19 13:34:18 -06003159void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003160{
John Kessenichfc51d282015-08-19 13:34:18 -06003161 builder.clearAccessChain();
3162 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003163 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003164}
John Kessenich140f3df2015-06-26 16:58:36 -06003165
John Kessenichfc51d282015-08-19 13:34:18 -06003166spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3167{
John Kesseniche485c7a2017-05-31 18:50:53 -06003168 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003169 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003170
3171 builder.setLine(node->getLoc().line);
3172
John Kessenich8c8505c2016-07-26 12:50:38 -06003173 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003174
John Kessenichfc51d282015-08-19 13:34:18 -06003175 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003176 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3177 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3178 std::vector<spv::Id> arguments;
3179 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003180 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003181 else
3182 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003183 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003184
3185 spv::Builder::TextureParameters params = { };
3186 params.sampler = arguments[0];
3187
Rex Xu04db3f52015-09-16 11:44:02 +08003188 glslang::TCrackedTextureOp cracked;
3189 node->crackTexture(sampler, cracked);
3190
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003191 const bool isUnsignedResult =
3192 node->getType().getBasicType() == glslang::EbtUint64 ||
3193 node->getType().getBasicType() == glslang::EbtUint;
3194
John Kessenichfc51d282015-08-19 13:34:18 -06003195 // Check for queries
3196 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003197 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3198 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003199 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003200
John Kessenichfc51d282015-08-19 13:34:18 -06003201 switch (node->getOp()) {
3202 case glslang::EOpImageQuerySize:
3203 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003204 if (arguments.size() > 1) {
3205 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003206 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003207 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003208 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003209 case glslang::EOpImageQuerySamples:
3210 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003211 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003212 case glslang::EOpTextureQueryLod:
3213 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003214 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003215 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003216 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003217 case glslang::EOpSparseTexelsResident:
3218 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003219 default:
3220 assert(0);
3221 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 }
John Kessenich140f3df2015-06-26 16:58:36 -06003223 }
3224
Rex Xufc618912015-09-09 16:42:49 +08003225 // Check for image functions other than queries
3226 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003227 std::vector<spv::Id> operands;
3228 auto opIt = arguments.begin();
3229 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003230
3231 // Handle subpass operations
3232 // TODO: GLSL should change to have the "MS" only on the type rather than the
3233 // built-in function.
3234 if (cracked.subpass) {
3235 // add on the (0,0) coordinate
3236 spv::Id zero = builder.makeIntConstant(0);
3237 std::vector<spv::Id> comps;
3238 comps.push_back(zero);
3239 comps.push_back(zero);
3240 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3241 if (sampler.ms) {
3242 operands.push_back(spv::ImageOperandsSampleMask);
3243 operands.push_back(*(opIt++));
3244 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003245 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003246 }
3247
John Kessenich56bab042015-09-16 10:54:31 -06003248 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003249#ifdef AMD_EXTENSIONS
3250 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3251#else
John Kessenich56bab042015-09-16 10:54:31 -06003252 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003253#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003254 if (sampler.ms) {
3255 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003256 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003257#ifdef AMD_EXTENSIONS
3258 } else if (cracked.lod) {
3259 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3260 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3261
3262 operands.push_back(spv::ImageOperandsLodMask);
3263 operands.push_back(*opIt);
3264#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003265 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003266 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3267 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003268 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003269#ifdef AMD_EXTENSIONS
3270 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3271#else
John Kessenich56bab042015-09-16 10:54:31 -06003272 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003273#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003274 if (sampler.ms) {
3275 operands.push_back(*(opIt + 1));
3276 operands.push_back(spv::ImageOperandsSampleMask);
3277 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003278#ifdef AMD_EXTENSIONS
3279 } else if (cracked.lod) {
3280 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3281 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3282
3283 operands.push_back(*(opIt + 1));
3284 operands.push_back(spv::ImageOperandsLodMask);
3285 operands.push_back(*opIt);
3286#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003287 } else
3288 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003289 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003290 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3291 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003292 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003293#ifdef AMD_EXTENSIONS
3294 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3295#else
Rex Xu5eafa472016-02-19 22:24:03 +08003296 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003297#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003298 builder.addCapability(spv::CapabilitySparseResidency);
3299 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3300 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3301
3302 if (sampler.ms) {
3303 operands.push_back(spv::ImageOperandsSampleMask);
3304 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003305#ifdef AMD_EXTENSIONS
3306 } else if (cracked.lod) {
3307 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3308 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3309
3310 operands.push_back(spv::ImageOperandsLodMask);
3311 operands.push_back(*opIt++);
3312#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003313 }
3314
3315 // Create the return type that was a special structure
3316 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003317 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003318 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3319 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3320
3321 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3322
3323 // Decode the return type
3324 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3325 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003326 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003327 // Process image atomic operations
3328
3329 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3330 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003331 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003332
John Kessenich8c8505c2016-07-26 12:50:38 -06003333 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003334 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003335
3336 std::vector<spv::Id> operands;
3337 operands.push_back(pointer);
3338 for (; opIt != arguments.end(); ++opIt)
3339 operands.push_back(*opIt);
3340
John Kessenich8c8505c2016-07-26 12:50:38 -06003341 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003342 }
3343 }
3344
3345 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003346 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003347 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3348
John Kessenichfc51d282015-08-19 13:34:18 -06003349 // check for bias argument
3350 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003351#ifdef AMD_EXTENSIONS
3352 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3353#else
Rex Xu71519fe2015-11-11 15:35:47 +08003354 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003355#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003356 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003357#ifdef AMD_EXTENSIONS
3358 if (cracked.gather)
3359 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3360#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003361 if (cracked.offset)
3362 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003363#ifdef AMD_EXTENSIONS
3364 else if (cracked.offsets)
3365 ++nonBiasArgCount;
3366#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003367 if (cracked.grad)
3368 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003369 if (cracked.lodClamp)
3370 ++nonBiasArgCount;
3371 if (sparse)
3372 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003373
3374 if ((int)arguments.size() > nonBiasArgCount)
3375 bias = true;
3376 }
3377
John Kessenicha5c33d62016-06-02 23:45:21 -06003378 // See if the sampler param should really be just the SPV image part
3379 if (cracked.fetch) {
3380 // a fetch needs to have the image extracted first
3381 if (builder.isSampledImage(params.sampler))
3382 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3383 }
3384
Rex Xu225e0fc2016-11-17 17:47:59 +08003385#ifdef AMD_EXTENSIONS
3386 if (cracked.gather) {
3387 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3388 if (bias || cracked.lod ||
3389 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3390 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003391 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003392 }
3393 }
3394#endif
3395
John Kessenichfc51d282015-08-19 13:34:18 -06003396 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003397
John Kessenichfc51d282015-08-19 13:34:18 -06003398 params.coords = arguments[1];
3399 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003400 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003401
3402 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003403 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003404 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003405 ++extraArgs;
3406 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003407 params.Dref = arguments[2];
3408 ++extraArgs;
3409 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003410 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003411 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003412 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003413 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003414 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003415 dRefComp = builder.getNumComponents(params.coords) - 1;
3416 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003417 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3418 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003419
3420 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003421 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003422 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003423 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003424 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3425 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3426 noImplicitLod = true;
3427 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003428
3429 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003430 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003431 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003432 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003433 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003434
3435 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003436 if (cracked.grad) {
3437 params.gradX = arguments[2 + extraArgs];
3438 params.gradY = arguments[3 + extraArgs];
3439 extraArgs += 2;
3440 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003441
3442 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003443 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003444 params.offset = arguments[2 + extraArgs];
3445 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003446 } else if (cracked.offsets) {
3447 params.offsets = arguments[2 + extraArgs];
3448 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003449 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003450
3451 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003452 if (cracked.lodClamp) {
3453 params.lodClamp = arguments[2 + extraArgs];
3454 ++extraArgs;
3455 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003456
3457 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003458 if (sparse) {
3459 params.texelOut = arguments[2 + extraArgs];
3460 ++extraArgs;
3461 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003462
John Kessenich76d4dfc2016-06-16 12:43:23 -06003463 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003464 if (cracked.gather && ! sampler.shadow) {
3465 // default component is 0, if missing, otherwise an argument
3466 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003467 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003468 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003469 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003470 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003471 }
3472
3473 // bias
3474 if (bias) {
3475 params.bias = arguments[2 + extraArgs];
3476 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003477 }
John Kessenichfc51d282015-08-19 13:34:18 -06003478
John Kessenich65336482016-06-16 14:06:26 -06003479 // projective component (might not to move)
3480 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3481 // are divided by the last component of P."
3482 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3483 // unused components will appear after all used components."
3484 if (cracked.proj) {
3485 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3486 int projTargetComp;
3487 switch (sampler.dim) {
3488 case glslang::Esd1D: projTargetComp = 1; break;
3489 case glslang::Esd2D: projTargetComp = 2; break;
3490 case glslang::EsdRect: projTargetComp = 2; break;
3491 default: projTargetComp = projSourceComp; break;
3492 }
3493 // copy the projective coordinate if we have to
3494 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003495 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003496 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3497 projSourceComp);
3498 params.coords = builder.createCompositeInsert(projComp, params.coords,
3499 builder.getTypeId(params.coords), projTargetComp);
3500 }
3501 }
3502
John Kessenich8c8505c2016-07-26 12:50:38 -06003503 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003504}
3505
3506spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3507{
3508 // Grab the function's pointer from the previously created function
3509 spv::Function* function = functionMap[node->getName().c_str()];
3510 if (! function)
3511 return 0;
3512
3513 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3514 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3515
3516 // See comments in makeFunctions() for details about the semantics for parameter passing.
3517 //
3518 // These imply we need a four step process:
3519 // 1. Evaluate the arguments
3520 // 2. Allocate and make copies of in, out, and inout arguments
3521 // 3. Make the call
3522 // 4. Copy back the results
3523
3524 // 1. Evaluate the arguments
3525 std::vector<spv::Builder::AccessChain> lValues;
3526 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003527 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003528 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003529 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003530 // build l-value
3531 builder.clearAccessChain();
3532 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003533 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003534 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003535 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003536 // save l-value
3537 lValues.push_back(builder.getAccessChain());
3538 } else {
3539 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003540 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003541 }
3542 }
3543
3544 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3545 // copy the original into that space.
3546 //
3547 // Also, build up the list of actual arguments to pass in for the call
3548 int lValueCount = 0;
3549 int rValueCount = 0;
3550 std::vector<spv::Id> spvArgs;
3551 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003552 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003553 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003554 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003555 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3556 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003557 builder.setAccessChain(lValues[lValueCount]);
3558 arg = builder.accessChainGetLValue();
3559 ++lValueCount;
3560 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003561 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003562 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3563 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3564 // need to copy the input into output space
3565 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003566 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003567 builder.clearAccessChain();
3568 builder.setAccessChainLValue(arg);
3569 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003570 }
3571 ++lValueCount;
3572 } else {
3573 arg = rValues[rValueCount];
3574 ++rValueCount;
3575 }
3576 spvArgs.push_back(arg);
3577 }
3578
3579 // 3. Make the call.
3580 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003581 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003582
3583 // 4. Copy back out an "out" arguments.
3584 lValueCount = 0;
3585 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003586 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003587 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3588 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3589 spv::Id copy = builder.createLoad(spvArgs[a]);
3590 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003591 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003592 }
3593 ++lValueCount;
3594 }
3595 }
3596
3597 return result;
3598}
3599
3600// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003601spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3602 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003603 spv::Id typeId, spv::Id left, spv::Id right,
3604 glslang::TBasicType typeProxy, bool reduceComparison)
3605{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003606#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003607 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003608 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3609#else
Rex Xucabbb782017-03-24 13:41:14 +08003610 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003612#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003613 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003614
3615 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003616 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003617 bool comparison = false;
3618
3619 switch (op) {
3620 case glslang::EOpAdd:
3621 case glslang::EOpAddAssign:
3622 if (isFloat)
3623 binOp = spv::OpFAdd;
3624 else
3625 binOp = spv::OpIAdd;
3626 break;
3627 case glslang::EOpSub:
3628 case glslang::EOpSubAssign:
3629 if (isFloat)
3630 binOp = spv::OpFSub;
3631 else
3632 binOp = spv::OpISub;
3633 break;
3634 case glslang::EOpMul:
3635 case glslang::EOpMulAssign:
3636 if (isFloat)
3637 binOp = spv::OpFMul;
3638 else
3639 binOp = spv::OpIMul;
3640 break;
3641 case glslang::EOpVectorTimesScalar:
3642 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003643 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003644 if (builder.isVector(right))
3645 std::swap(left, right);
3646 assert(builder.isScalar(right));
3647 needMatchingVectors = false;
3648 binOp = spv::OpVectorTimesScalar;
3649 } else
3650 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003651 break;
3652 case glslang::EOpVectorTimesMatrix:
3653 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003654 binOp = spv::OpVectorTimesMatrix;
3655 break;
3656 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003657 binOp = spv::OpMatrixTimesVector;
3658 break;
3659 case glslang::EOpMatrixTimesScalar:
3660 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003661 binOp = spv::OpMatrixTimesScalar;
3662 break;
3663 case glslang::EOpMatrixTimesMatrix:
3664 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003665 binOp = spv::OpMatrixTimesMatrix;
3666 break;
3667 case glslang::EOpOuterProduct:
3668 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003669 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003670 break;
3671
3672 case glslang::EOpDiv:
3673 case glslang::EOpDivAssign:
3674 if (isFloat)
3675 binOp = spv::OpFDiv;
3676 else if (isUnsigned)
3677 binOp = spv::OpUDiv;
3678 else
3679 binOp = spv::OpSDiv;
3680 break;
3681 case glslang::EOpMod:
3682 case glslang::EOpModAssign:
3683 if (isFloat)
3684 binOp = spv::OpFMod;
3685 else if (isUnsigned)
3686 binOp = spv::OpUMod;
3687 else
3688 binOp = spv::OpSMod;
3689 break;
3690 case glslang::EOpRightShift:
3691 case glslang::EOpRightShiftAssign:
3692 if (isUnsigned)
3693 binOp = spv::OpShiftRightLogical;
3694 else
3695 binOp = spv::OpShiftRightArithmetic;
3696 break;
3697 case glslang::EOpLeftShift:
3698 case glslang::EOpLeftShiftAssign:
3699 binOp = spv::OpShiftLeftLogical;
3700 break;
3701 case glslang::EOpAnd:
3702 case glslang::EOpAndAssign:
3703 binOp = spv::OpBitwiseAnd;
3704 break;
3705 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003706 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003707 binOp = spv::OpLogicalAnd;
3708 break;
3709 case glslang::EOpInclusiveOr:
3710 case glslang::EOpInclusiveOrAssign:
3711 binOp = spv::OpBitwiseOr;
3712 break;
3713 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003714 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003715 binOp = spv::OpLogicalOr;
3716 break;
3717 case glslang::EOpExclusiveOr:
3718 case glslang::EOpExclusiveOrAssign:
3719 binOp = spv::OpBitwiseXor;
3720 break;
3721 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003722 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003723 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003724 break;
3725
3726 case glslang::EOpLessThan:
3727 case glslang::EOpGreaterThan:
3728 case glslang::EOpLessThanEqual:
3729 case glslang::EOpGreaterThanEqual:
3730 case glslang::EOpEqual:
3731 case glslang::EOpNotEqual:
3732 case glslang::EOpVectorEqual:
3733 case glslang::EOpVectorNotEqual:
3734 comparison = true;
3735 break;
3736 default:
3737 break;
3738 }
3739
John Kessenich7c1aa102015-10-15 13:29:11 -06003740 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003741 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003742 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003743 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003744 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003745
3746 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003747 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003748 builder.promoteScalar(precision, left, right);
3749
qining25262b32016-05-06 17:25:16 -04003750 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3751 addDecoration(result, noContraction);
3752 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003753 }
3754
3755 if (! comparison)
3756 return 0;
3757
John Kessenich7c1aa102015-10-15 13:29:11 -06003758 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003759
John Kessenich4583b612016-08-07 19:14:22 -06003760 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3761 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003762 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003763
3764 switch (op) {
3765 case glslang::EOpLessThan:
3766 if (isFloat)
3767 binOp = spv::OpFOrdLessThan;
3768 else if (isUnsigned)
3769 binOp = spv::OpULessThan;
3770 else
3771 binOp = spv::OpSLessThan;
3772 break;
3773 case glslang::EOpGreaterThan:
3774 if (isFloat)
3775 binOp = spv::OpFOrdGreaterThan;
3776 else if (isUnsigned)
3777 binOp = spv::OpUGreaterThan;
3778 else
3779 binOp = spv::OpSGreaterThan;
3780 break;
3781 case glslang::EOpLessThanEqual:
3782 if (isFloat)
3783 binOp = spv::OpFOrdLessThanEqual;
3784 else if (isUnsigned)
3785 binOp = spv::OpULessThanEqual;
3786 else
3787 binOp = spv::OpSLessThanEqual;
3788 break;
3789 case glslang::EOpGreaterThanEqual:
3790 if (isFloat)
3791 binOp = spv::OpFOrdGreaterThanEqual;
3792 else if (isUnsigned)
3793 binOp = spv::OpUGreaterThanEqual;
3794 else
3795 binOp = spv::OpSGreaterThanEqual;
3796 break;
3797 case glslang::EOpEqual:
3798 case glslang::EOpVectorEqual:
3799 if (isFloat)
3800 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003801 else if (isBool)
3802 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003803 else
3804 binOp = spv::OpIEqual;
3805 break;
3806 case glslang::EOpNotEqual:
3807 case glslang::EOpVectorNotEqual:
3808 if (isFloat)
3809 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003810 else if (isBool)
3811 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003812 else
3813 binOp = spv::OpINotEqual;
3814 break;
3815 default:
3816 break;
3817 }
3818
qining25262b32016-05-06 17:25:16 -04003819 if (binOp != spv::OpNop) {
3820 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3821 addDecoration(result, noContraction);
3822 return builder.setPrecision(result, precision);
3823 }
John Kessenich140f3df2015-06-26 16:58:36 -06003824
3825 return 0;
3826}
3827
John Kessenich04bb8a02015-12-12 12:28:14 -07003828//
3829// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3830// These can be any of:
3831//
3832// matrix * scalar
3833// scalar * matrix
3834// matrix * matrix linear algebraic
3835// matrix * vector
3836// vector * matrix
3837// matrix * matrix componentwise
3838// matrix op matrix op in {+, -, /}
3839// matrix op scalar op in {+, -, /}
3840// scalar op matrix op in {+, -, /}
3841//
qining25262b32016-05-06 17:25:16 -04003842spv::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 -07003843{
3844 bool firstClass = true;
3845
3846 // First, handle first-class matrix operations (* and matrix/scalar)
3847 switch (op) {
3848 case spv::OpFDiv:
3849 if (builder.isMatrix(left) && builder.isScalar(right)) {
3850 // turn matrix / scalar into a multiply...
3851 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3852 op = spv::OpMatrixTimesScalar;
3853 } else
3854 firstClass = false;
3855 break;
3856 case spv::OpMatrixTimesScalar:
3857 if (builder.isMatrix(right))
3858 std::swap(left, right);
3859 assert(builder.isScalar(right));
3860 break;
3861 case spv::OpVectorTimesMatrix:
3862 assert(builder.isVector(left));
3863 assert(builder.isMatrix(right));
3864 break;
3865 case spv::OpMatrixTimesVector:
3866 assert(builder.isMatrix(left));
3867 assert(builder.isVector(right));
3868 break;
3869 case spv::OpMatrixTimesMatrix:
3870 assert(builder.isMatrix(left));
3871 assert(builder.isMatrix(right));
3872 break;
3873 default:
3874 firstClass = false;
3875 break;
3876 }
3877
qining25262b32016-05-06 17:25:16 -04003878 if (firstClass) {
3879 spv::Id result = builder.createBinOp(op, typeId, left, right);
3880 addDecoration(result, noContraction);
3881 return builder.setPrecision(result, precision);
3882 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003883
LoopDawg592860c2016-06-09 08:57:35 -06003884 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003885 // The result type of all of them is the same type as the (a) matrix operand.
3886 // The algorithm is to:
3887 // - break the matrix(es) into vectors
3888 // - smear any scalar to a vector
3889 // - do vector operations
3890 // - make a matrix out the vector results
3891 switch (op) {
3892 case spv::OpFAdd:
3893 case spv::OpFSub:
3894 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003895 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003896 case spv::OpFMul:
3897 {
3898 // one time set up...
3899 bool leftMat = builder.isMatrix(left);
3900 bool rightMat = builder.isMatrix(right);
3901 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3902 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3903 spv::Id scalarType = builder.getScalarTypeId(typeId);
3904 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3905 std::vector<spv::Id> results;
3906 spv::Id smearVec = spv::NoResult;
3907 if (builder.isScalar(left))
3908 smearVec = builder.smearScalar(precision, left, vecType);
3909 else if (builder.isScalar(right))
3910 smearVec = builder.smearScalar(precision, right, vecType);
3911
3912 // do each vector op
3913 for (unsigned int c = 0; c < numCols; ++c) {
3914 std::vector<unsigned int> indexes;
3915 indexes.push_back(c);
3916 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3917 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003918 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3919 addDecoration(result, noContraction);
3920 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003921 }
3922
3923 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003924 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003925 }
3926 default:
3927 assert(0);
3928 return spv::NoResult;
3929 }
3930}
3931
qining25262b32016-05-06 17:25:16 -04003932spv::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 -06003933{
3934 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003935 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003936 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003937#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003938 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003939 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3940#else
Rex Xucabbb782017-03-24 13:41:14 +08003941 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003942 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003943#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003944
3945 switch (op) {
3946 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003947 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003948 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003949 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003950 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003951 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003952 unaryOp = spv::OpSNegate;
3953 break;
3954
3955 case glslang::EOpLogicalNot:
3956 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003957 unaryOp = spv::OpLogicalNot;
3958 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003959 case glslang::EOpBitwiseNot:
3960 unaryOp = spv::OpNot;
3961 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003962
John Kessenich140f3df2015-06-26 16:58:36 -06003963 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003964 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003965 break;
3966 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003967 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003968 break;
3969 case glslang::EOpTranspose:
3970 unaryOp = spv::OpTranspose;
3971 break;
3972
3973 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003974 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003975 break;
3976 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003977 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003978 break;
3979 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003980 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003981 break;
3982 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003983 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003984 break;
3985 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003986 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003987 break;
3988 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003989 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003990 break;
3991 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003992 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003993 break;
3994 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003995 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003996 break;
3997
3998 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003999 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004000 break;
4001 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004002 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004003 break;
4004 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004005 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004006 break;
4007 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004009 break;
4010 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
4013 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 break;
4016
4017 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004018 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004019 break;
4020 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004021 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004022 break;
4023
4024 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004025 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004026 break;
4027 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004028 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004029 break;
4030 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004031 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004032 break;
4033 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004034 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004035 break;
4036 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004037 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004038 break;
4039 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004040 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004041 break;
4042
4043 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004044 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004045 break;
4046 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004047 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004048 break;
4049 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061
4062 case glslang::EOpIsNan:
4063 unaryOp = spv::OpIsNan;
4064 break;
4065 case glslang::EOpIsInf:
4066 unaryOp = spv::OpIsInf;
4067 break;
LoopDawg592860c2016-06-09 08:57:35 -06004068 case glslang::EOpIsFinite:
4069 unaryOp = spv::OpIsFinite;
4070 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004071
Rex Xucbc426e2015-12-15 16:03:10 +08004072 case glslang::EOpFloatBitsToInt:
4073 case glslang::EOpFloatBitsToUint:
4074 case glslang::EOpIntBitsToFloat:
4075 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004076 case glslang::EOpDoubleBitsToInt64:
4077 case glslang::EOpDoubleBitsToUint64:
4078 case glslang::EOpInt64BitsToDouble:
4079 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004080#ifdef AMD_EXTENSIONS
4081 case glslang::EOpFloat16BitsToInt16:
4082 case glslang::EOpFloat16BitsToUint16:
4083 case glslang::EOpInt16BitsToFloat16:
4084 case glslang::EOpUint16BitsToFloat16:
4085#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004086 unaryOp = spv::OpBitcast;
4087 break;
4088
John Kessenich140f3df2015-06-26 16:58:36 -06004089 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004096 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004097 break;
4098 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004099 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004100 break;
4101 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004102 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 break;
4104 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004105 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004106 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004107 case glslang::EOpPackSnorm4x8:
4108 libCall = spv::GLSLstd450PackSnorm4x8;
4109 break;
4110 case glslang::EOpUnpackSnorm4x8:
4111 libCall = spv::GLSLstd450UnpackSnorm4x8;
4112 break;
4113 case glslang::EOpPackUnorm4x8:
4114 libCall = spv::GLSLstd450PackUnorm4x8;
4115 break;
4116 case glslang::EOpUnpackUnorm4x8:
4117 libCall = spv::GLSLstd450UnpackUnorm4x8;
4118 break;
4119 case glslang::EOpPackDouble2x32:
4120 libCall = spv::GLSLstd450PackDouble2x32;
4121 break;
4122 case glslang::EOpUnpackDouble2x32:
4123 libCall = spv::GLSLstd450UnpackDouble2x32;
4124 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004125
Rex Xu8ff43de2016-04-22 16:51:45 +08004126 case glslang::EOpPackInt2x32:
4127 case glslang::EOpUnpackInt2x32:
4128 case glslang::EOpPackUint2x32:
4129 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004130 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004131 break;
4132
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004133#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004134 case glslang::EOpPackInt2x16:
4135 case glslang::EOpUnpackInt2x16:
4136 case glslang::EOpPackUint2x16:
4137 case glslang::EOpUnpackUint2x16:
4138 case glslang::EOpPackInt4x16:
4139 case glslang::EOpUnpackInt4x16:
4140 case glslang::EOpPackUint4x16:
4141 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004142 case glslang::EOpPackFloat2x16:
4143 case glslang::EOpUnpackFloat2x16:
4144 unaryOp = spv::OpBitcast;
4145 break;
4146#endif
4147
John Kessenich140f3df2015-06-26 16:58:36 -06004148 case glslang::EOpDPdx:
4149 unaryOp = spv::OpDPdx;
4150 break;
4151 case glslang::EOpDPdy:
4152 unaryOp = spv::OpDPdy;
4153 break;
4154 case glslang::EOpFwidth:
4155 unaryOp = spv::OpFwidth;
4156 break;
4157 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004158 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004159 unaryOp = spv::OpDPdxFine;
4160 break;
4161 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004162 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004163 unaryOp = spv::OpDPdyFine;
4164 break;
4165 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004166 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004167 unaryOp = spv::OpFwidthFine;
4168 break;
4169 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004170 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004171 unaryOp = spv::OpDPdxCoarse;
4172 break;
4173 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004174 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004175 unaryOp = spv::OpDPdyCoarse;
4176 break;
4177 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004178 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004179 unaryOp = spv::OpFwidthCoarse;
4180 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004181 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004182 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004183 libCall = spv::GLSLstd450InterpolateAtCentroid;
4184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004185 case glslang::EOpAny:
4186 unaryOp = spv::OpAny;
4187 break;
4188 case glslang::EOpAll:
4189 unaryOp = spv::OpAll;
4190 break;
4191
4192 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004193 if (isFloat)
4194 libCall = spv::GLSLstd450FAbs;
4195 else
4196 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004197 break;
4198 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004199 if (isFloat)
4200 libCall = spv::GLSLstd450FSign;
4201 else
4202 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004203 break;
4204
John Kessenichfc51d282015-08-19 13:34:18 -06004205 case glslang::EOpAtomicCounterIncrement:
4206 case glslang::EOpAtomicCounterDecrement:
4207 case glslang::EOpAtomicCounter:
4208 {
4209 // Handle all of the atomics in one place, in createAtomicOperation()
4210 std::vector<spv::Id> operands;
4211 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004212 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004213 }
4214
John Kessenichfc51d282015-08-19 13:34:18 -06004215 case glslang::EOpBitFieldReverse:
4216 unaryOp = spv::OpBitReverse;
4217 break;
4218 case glslang::EOpBitCount:
4219 unaryOp = spv::OpBitCount;
4220 break;
4221 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004222 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004223 break;
4224 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004225 if (isUnsigned)
4226 libCall = spv::GLSLstd450FindUMsb;
4227 else
4228 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004229 break;
4230
Rex Xu574ab042016-04-14 16:53:07 +08004231 case glslang::EOpBallot:
4232 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004233 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004234 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004235 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004236#ifdef AMD_EXTENSIONS
4237 case glslang::EOpMinInvocations:
4238 case glslang::EOpMaxInvocations:
4239 case glslang::EOpAddInvocations:
4240 case glslang::EOpMinInvocationsNonUniform:
4241 case glslang::EOpMaxInvocationsNonUniform:
4242 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004243 case glslang::EOpMinInvocationsInclusiveScan:
4244 case glslang::EOpMaxInvocationsInclusiveScan:
4245 case glslang::EOpAddInvocationsInclusiveScan:
4246 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4247 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4248 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4249 case glslang::EOpMinInvocationsExclusiveScan:
4250 case glslang::EOpMaxInvocationsExclusiveScan:
4251 case glslang::EOpAddInvocationsExclusiveScan:
4252 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4253 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4254 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004255#endif
Rex Xu51596642016-09-21 18:56:12 +08004256 {
4257 std::vector<spv::Id> operands;
4258 operands.push_back(operand);
4259 return createInvocationsOperation(op, typeId, operands, typeProxy);
4260 }
Rex Xu9d93a232016-05-05 12:30:44 +08004261
4262#ifdef AMD_EXTENSIONS
4263 case glslang::EOpMbcnt:
4264 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4265 libCall = spv::MbcntAMD;
4266 break;
4267
4268 case glslang::EOpCubeFaceIndex:
4269 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4270 libCall = spv::CubeFaceIndexAMD;
4271 break;
4272
4273 case glslang::EOpCubeFaceCoord:
4274 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4275 libCall = spv::CubeFaceCoordAMD;
4276 break;
4277#endif
Rex Xu338b1852016-05-05 20:38:33 +08004278
John Kessenich140f3df2015-06-26 16:58:36 -06004279 default:
4280 return 0;
4281 }
4282
4283 spv::Id id;
4284 if (libCall >= 0) {
4285 std::vector<spv::Id> args;
4286 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004287 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004288 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004289 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004290 }
John Kessenich140f3df2015-06-26 16:58:36 -06004291
qining25262b32016-05-06 17:25:16 -04004292 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004293 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004294}
4295
John Kessenich7a53f762016-01-20 11:19:27 -07004296// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004297spv::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 -07004298{
4299 // Handle unary operations vector by vector.
4300 // The result type is the same type as the original type.
4301 // The algorithm is to:
4302 // - break the matrix into vectors
4303 // - apply the operation to each vector
4304 // - make a matrix out the vector results
4305
4306 // get the types sorted out
4307 int numCols = builder.getNumColumns(operand);
4308 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004309 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4310 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004311 std::vector<spv::Id> results;
4312
4313 // do each vector op
4314 for (int c = 0; c < numCols; ++c) {
4315 std::vector<unsigned int> indexes;
4316 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004317 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4318 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4319 addDecoration(destVec, noContraction);
4320 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004321 }
4322
4323 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004324 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004325}
4326
Rex Xu73e3ce72016-04-27 18:48:17 +08004327spv::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 -06004328{
4329 spv::Op convOp = spv::OpNop;
4330 spv::Id zero = 0;
4331 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004332 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004333
4334 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4335
4336 switch (op) {
4337 case glslang::EOpConvIntToBool:
4338 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004339 case glslang::EOpConvInt64ToBool:
4340 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004341#ifdef AMD_EXTENSIONS
4342 case glslang::EOpConvInt16ToBool:
4343 case glslang::EOpConvUint16ToBool:
4344#endif
4345 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4346 zero = builder.makeUint64Constant(0);
4347#ifdef AMD_EXTENSIONS
4348 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4349 zero = builder.makeUint16Constant(0);
4350#endif
4351 else
4352 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004353 zero = makeSmearedConstant(zero, vectorSize);
4354 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4355
4356 case glslang::EOpConvFloatToBool:
4357 zero = builder.makeFloatConstant(0.0F);
4358 zero = makeSmearedConstant(zero, vectorSize);
4359 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4360
4361 case glslang::EOpConvDoubleToBool:
4362 zero = builder.makeDoubleConstant(0.0);
4363 zero = makeSmearedConstant(zero, vectorSize);
4364 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4365
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004366#ifdef AMD_EXTENSIONS
4367 case glslang::EOpConvFloat16ToBool:
4368 zero = builder.makeFloat16Constant(0.0F);
4369 zero = makeSmearedConstant(zero, vectorSize);
4370 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4371#endif
4372
John Kessenich140f3df2015-06-26 16:58:36 -06004373 case glslang::EOpConvBoolToFloat:
4374 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004375 zero = builder.makeFloatConstant(0.0F);
4376 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004377 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004378
John Kessenich140f3df2015-06-26 16:58:36 -06004379 case glslang::EOpConvBoolToDouble:
4380 convOp = spv::OpSelect;
4381 zero = builder.makeDoubleConstant(0.0);
4382 one = builder.makeDoubleConstant(1.0);
4383 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004384
4385#ifdef AMD_EXTENSIONS
4386 case glslang::EOpConvBoolToFloat16:
4387 convOp = spv::OpSelect;
4388 zero = builder.makeFloat16Constant(0.0F);
4389 one = builder.makeFloat16Constant(1.0F);
4390 break;
4391#endif
4392
John Kessenich140f3df2015-06-26 16:58:36 -06004393 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004394 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004395#ifdef AMD_EXTENSIONS
4396 case glslang::EOpConvBoolToInt16:
4397#endif
4398 if (op == glslang::EOpConvBoolToInt64)
4399 zero = builder.makeInt64Constant(0);
4400#ifdef AMD_EXTENSIONS
4401 else if (op == glslang::EOpConvBoolToInt16)
4402 zero = builder.makeInt16Constant(0);
4403#endif
4404 else
4405 zero = builder.makeIntConstant(0);
4406
4407 if (op == glslang::EOpConvBoolToInt64)
4408 one = builder.makeInt64Constant(1);
4409#ifdef AMD_EXTENSIONS
4410 else if (op == glslang::EOpConvBoolToInt16)
4411 one = builder.makeInt16Constant(1);
4412#endif
4413 else
4414 one = builder.makeIntConstant(1);
4415
John Kessenich140f3df2015-06-26 16:58:36 -06004416 convOp = spv::OpSelect;
4417 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004418
John Kessenich140f3df2015-06-26 16:58:36 -06004419 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004420 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004421#ifdef AMD_EXTENSIONS
4422 case glslang::EOpConvBoolToUint16:
4423#endif
4424 if (op == glslang::EOpConvBoolToUint64)
4425 zero = builder.makeUint64Constant(0);
4426#ifdef AMD_EXTENSIONS
4427 else if (op == glslang::EOpConvBoolToUint16)
4428 zero = builder.makeUint16Constant(0);
4429#endif
4430 else
4431 zero = builder.makeUintConstant(0);
4432
4433 if (op == glslang::EOpConvBoolToUint64)
4434 one = builder.makeUint64Constant(1);
4435#ifdef AMD_EXTENSIONS
4436 else if (op == glslang::EOpConvBoolToUint16)
4437 one = builder.makeUint16Constant(1);
4438#endif
4439 else
4440 one = builder.makeUintConstant(1);
4441
John Kessenich140f3df2015-06-26 16:58:36 -06004442 convOp = spv::OpSelect;
4443 break;
4444
4445 case glslang::EOpConvIntToFloat:
4446 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004447 case glslang::EOpConvInt64ToFloat:
4448 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004449#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004450 case glslang::EOpConvInt16ToFloat:
4451 case glslang::EOpConvInt16ToDouble:
4452 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004453 case glslang::EOpConvIntToFloat16:
4454 case glslang::EOpConvInt64ToFloat16:
4455#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004456 convOp = spv::OpConvertSToF;
4457 break;
4458
4459 case glslang::EOpConvUintToFloat:
4460 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004461 case glslang::EOpConvUint64ToFloat:
4462 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004463#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004464 case glslang::EOpConvUint16ToFloat:
4465 case glslang::EOpConvUint16ToDouble:
4466 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004467 case glslang::EOpConvUintToFloat16:
4468 case glslang::EOpConvUint64ToFloat16:
4469#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004470 convOp = spv::OpConvertUToF;
4471 break;
4472
4473 case glslang::EOpConvDoubleToFloat:
4474 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004475#ifdef AMD_EXTENSIONS
4476 case glslang::EOpConvDoubleToFloat16:
4477 case glslang::EOpConvFloat16ToDouble:
4478 case glslang::EOpConvFloatToFloat16:
4479 case glslang::EOpConvFloat16ToFloat:
4480#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004481 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004482 if (builder.isMatrixType(destType))
4483 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004484 break;
4485
4486 case glslang::EOpConvFloatToInt:
4487 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004488 case glslang::EOpConvFloatToInt64:
4489 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004490#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004491 case glslang::EOpConvFloatToInt16:
4492 case glslang::EOpConvDoubleToInt16:
4493 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004494 case glslang::EOpConvFloat16ToInt:
4495 case glslang::EOpConvFloat16ToInt64:
4496#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004497 convOp = spv::OpConvertFToS;
4498 break;
4499
4500 case glslang::EOpConvUintToInt:
4501 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004502 case glslang::EOpConvUint64ToInt64:
4503 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004504#ifdef AMD_EXTENSIONS
4505 case glslang::EOpConvUint16ToInt16:
4506 case glslang::EOpConvInt16ToUint16:
4507#endif
qininge24aa5e2016-04-07 15:40:27 -04004508 if (builder.isInSpecConstCodeGenMode()) {
4509 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004510 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4511 zero = builder.makeUint64Constant(0);
4512#ifdef AMD_EXTENSIONS
4513 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4514 zero = builder.makeUint16Constant(0);
4515#endif
4516 else
4517 zero = builder.makeUintConstant(0);
4518
qining189b2032016-04-12 23:16:20 -04004519 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004520 // Use OpIAdd, instead of OpBitcast to do the conversion when
4521 // generating for OpSpecConstantOp instruction.
4522 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4523 }
4524 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004525 convOp = spv::OpBitcast;
4526 break;
4527
4528 case glslang::EOpConvFloatToUint:
4529 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004530 case glslang::EOpConvFloatToUint64:
4531 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004532#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004533 case glslang::EOpConvFloatToUint16:
4534 case glslang::EOpConvDoubleToUint16:
4535 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004536 case glslang::EOpConvFloat16ToUint:
4537 case glslang::EOpConvFloat16ToUint64:
4538#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004539 convOp = spv::OpConvertFToU;
4540 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004541
4542 case glslang::EOpConvIntToInt64:
4543 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004544#ifdef AMD_EXTENSIONS
4545 case glslang::EOpConvIntToInt16:
4546 case glslang::EOpConvInt16ToInt:
4547 case glslang::EOpConvInt64ToInt16:
4548 case glslang::EOpConvInt16ToInt64:
4549#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004550 convOp = spv::OpSConvert;
4551 break;
4552
4553 case glslang::EOpConvUintToUint64:
4554 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004555#ifdef AMD_EXTENSIONS
4556 case glslang::EOpConvUintToUint16:
4557 case glslang::EOpConvUint16ToUint:
4558 case glslang::EOpConvUint64ToUint16:
4559 case glslang::EOpConvUint16ToUint64:
4560#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004561 convOp = spv::OpUConvert;
4562 break;
4563
4564 case glslang::EOpConvIntToUint64:
4565 case glslang::EOpConvInt64ToUint:
4566 case glslang::EOpConvUint64ToInt:
4567 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004568#ifdef AMD_EXTENSIONS
4569 case glslang::EOpConvInt16ToUint:
4570 case glslang::EOpConvUintToInt16:
4571 case glslang::EOpConvInt16ToUint64:
4572 case glslang::EOpConvUint64ToInt16:
4573 case glslang::EOpConvUint16ToInt:
4574 case glslang::EOpConvIntToUint16:
4575 case glslang::EOpConvUint16ToInt64:
4576 case glslang::EOpConvInt64ToUint16:
4577#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004578 // OpSConvert/OpUConvert + OpBitCast
4579 switch (op) {
4580 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004581#ifdef AMD_EXTENSIONS
4582 case glslang::EOpConvInt16ToUint64:
4583#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004584 convOp = spv::OpSConvert;
4585 type = builder.makeIntType(64);
4586 break;
4587 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004588#ifdef AMD_EXTENSIONS
4589 case glslang::EOpConvInt16ToUint:
4590#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004591 convOp = spv::OpSConvert;
4592 type = builder.makeIntType(32);
4593 break;
4594 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004595#ifdef AMD_EXTENSIONS
4596 case glslang::EOpConvUint16ToInt:
4597#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004598 convOp = spv::OpUConvert;
4599 type = builder.makeUintType(32);
4600 break;
4601 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004602#ifdef AMD_EXTENSIONS
4603 case glslang::EOpConvUint16ToInt64:
4604#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004605 convOp = spv::OpUConvert;
4606 type = builder.makeUintType(64);
4607 break;
Rex Xucabbb782017-03-24 13:41:14 +08004608#ifdef AMD_EXTENSIONS
4609 case glslang::EOpConvUintToInt16:
4610 case glslang::EOpConvUint64ToInt16:
4611 convOp = spv::OpUConvert;
4612 type = builder.makeUintType(16);
4613 break;
4614 case glslang::EOpConvIntToUint16:
4615 case glslang::EOpConvInt64ToUint16:
4616 convOp = spv::OpSConvert;
4617 type = builder.makeIntType(16);
4618 break;
4619#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004620 default:
4621 assert(0);
4622 break;
4623 }
4624
4625 if (vectorSize > 0)
4626 type = builder.makeVectorType(type, vectorSize);
4627
4628 operand = builder.createUnaryOp(convOp, type, operand);
4629
4630 if (builder.isInSpecConstCodeGenMode()) {
4631 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004632#ifdef AMD_EXTENSIONS
4633 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4634 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4635 zero = builder.makeUint64Constant(0);
4636 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4637 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4638 zero = builder.makeUint16Constant(0);
4639 else
4640 zero = builder.makeUintConstant(0);
4641#else
4642 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4643 zero = builder.makeUint64Constant(0);
4644 else
4645 zero = builder.makeUintConstant(0);
4646#endif
4647
Rex Xu8ff43de2016-04-22 16:51:45 +08004648 zero = makeSmearedConstant(zero, vectorSize);
4649 // Use OpIAdd, instead of OpBitcast to do the conversion when
4650 // generating for OpSpecConstantOp instruction.
4651 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4652 }
4653 // For normal run-time conversion instruction, use OpBitcast.
4654 convOp = spv::OpBitcast;
4655 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004656 default:
4657 break;
4658 }
4659
4660 spv::Id result = 0;
4661 if (convOp == spv::OpNop)
4662 return result;
4663
4664 if (convOp == spv::OpSelect) {
4665 zero = makeSmearedConstant(zero, vectorSize);
4666 one = makeSmearedConstant(one, vectorSize);
4667 result = builder.createTriOp(convOp, destType, operand, one, zero);
4668 } else
4669 result = builder.createUnaryOp(convOp, destType, operand);
4670
John Kessenich32cfd492016-02-02 12:37:46 -07004671 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004672}
4673
4674spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4675{
4676 if (vectorSize == 0)
4677 return constant;
4678
4679 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4680 std::vector<spv::Id> components;
4681 for (int c = 0; c < vectorSize; ++c)
4682 components.push_back(constant);
4683 return builder.makeCompositeConstant(vectorTypeId, components);
4684}
4685
John Kessenich426394d2015-07-23 10:22:48 -06004686// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004687spv::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 -06004688{
4689 spv::Op opCode = spv::OpNop;
4690
4691 switch (op) {
4692 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004693 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004694 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004695 opCode = spv::OpAtomicIAdd;
4696 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004697 case glslang::EOpAtomicCounterSubtract:
4698 opCode = spv::OpAtomicISub;
4699 break;
John Kessenich426394d2015-07-23 10:22:48 -06004700 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004701 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004702 case glslang::EOpAtomicCounterMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004703 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004704 break;
4705 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004706 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004707 case glslang::EOpAtomicCounterMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004708 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004709 break;
4710 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004711 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004712 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004713 opCode = spv::OpAtomicAnd;
4714 break;
4715 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004716 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004717 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004718 opCode = spv::OpAtomicOr;
4719 break;
4720 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004721 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004722 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004723 opCode = spv::OpAtomicXor;
4724 break;
4725 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004726 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004727 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004728 opCode = spv::OpAtomicExchange;
4729 break;
4730 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004731 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004732 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004733 opCode = spv::OpAtomicCompareExchange;
4734 break;
4735 case glslang::EOpAtomicCounterIncrement:
4736 opCode = spv::OpAtomicIIncrement;
4737 break;
4738 case glslang::EOpAtomicCounterDecrement:
4739 opCode = spv::OpAtomicIDecrement;
4740 break;
4741 case glslang::EOpAtomicCounter:
4742 opCode = spv::OpAtomicLoad;
4743 break;
4744 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004745 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004746 break;
4747 }
4748
4749 // Sort out the operands
4750 // - mapping from glslang -> SPV
4751 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004752 // - compare-exchange swaps the value and comparator
4753 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004754 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4755 auto opIt = operands.begin(); // walk the glslang operands
4756 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004757 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4758 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4759 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004760 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4761 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004762 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004763 spvAtomicOperands.push_back(*(opIt + 1));
4764 spvAtomicOperands.push_back(*opIt);
4765 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004766 }
John Kessenich426394d2015-07-23 10:22:48 -06004767
John Kessenich3e60a6f2015-09-14 22:45:16 -06004768 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004769 for (; opIt != operands.end(); ++opIt)
4770 spvAtomicOperands.push_back(*opIt);
4771
4772 return builder.createOp(opCode, typeId, spvAtomicOperands);
4773}
4774
John Kessenich91cef522016-05-05 16:45:40 -06004775// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004776spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004777{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004778#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004779 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004780 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004781#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004782
Rex Xu51596642016-09-21 18:56:12 +08004783 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004784 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004785 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4786
chaocf200da82016-12-20 12:44:35 -08004787 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4788 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004789 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4790 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004791 } else if (op == glslang::EOpAnyInvocation ||
4792 op == glslang::EOpAllInvocations ||
4793 op == glslang::EOpAllInvocationsEqual) {
4794 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4795 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004796 } else {
4797 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004798#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004799 if (op == glslang::EOpMinInvocationsNonUniform ||
4800 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004801 op == glslang::EOpAddInvocationsNonUniform ||
4802 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4803 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4804 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4805 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4806 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4807 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004808 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004809#endif
Rex Xu51596642016-09-21 18:56:12 +08004810
4811 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004812#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004813 switch (op) {
4814 case glslang::EOpMinInvocations:
4815 case glslang::EOpMaxInvocations:
4816 case glslang::EOpAddInvocations:
4817 case glslang::EOpMinInvocationsNonUniform:
4818 case glslang::EOpMaxInvocationsNonUniform:
4819 case glslang::EOpAddInvocationsNonUniform:
4820 groupOperation = spv::GroupOperationReduce;
4821 spvGroupOperands.push_back(groupOperation);
4822 break;
4823 case glslang::EOpMinInvocationsInclusiveScan:
4824 case glslang::EOpMaxInvocationsInclusiveScan:
4825 case glslang::EOpAddInvocationsInclusiveScan:
4826 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4827 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4828 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4829 groupOperation = spv::GroupOperationInclusiveScan;
4830 spvGroupOperands.push_back(groupOperation);
4831 break;
4832 case glslang::EOpMinInvocationsExclusiveScan:
4833 case glslang::EOpMaxInvocationsExclusiveScan:
4834 case glslang::EOpAddInvocationsExclusiveScan:
4835 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4836 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4837 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4838 groupOperation = spv::GroupOperationExclusiveScan;
4839 spvGroupOperands.push_back(groupOperation);
4840 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004841 default:
4842 break;
Rex Xu430ef402016-10-14 17:22:23 +08004843 }
Rex Xu9d93a232016-05-05 12:30:44 +08004844#endif
Rex Xu51596642016-09-21 18:56:12 +08004845 }
4846
4847 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4848 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004849
4850 switch (op) {
4851 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004852 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004853 break;
John Kessenich91cef522016-05-05 16:45:40 -06004854 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004855 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004856 break;
John Kessenich91cef522016-05-05 16:45:40 -06004857 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004858 opCode = spv::OpSubgroupAllEqualKHR;
4859 break;
Rex Xu51596642016-09-21 18:56:12 +08004860 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004861 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004862 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004863 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004864 break;
4865 case glslang::EOpReadFirstInvocation:
4866 opCode = spv::OpSubgroupFirstInvocationKHR;
4867 break;
4868 case glslang::EOpBallot:
4869 {
4870 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4871 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4872 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4873 //
4874 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4875 //
4876 spv::Id uintType = builder.makeUintType(32);
4877 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4878 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4879
4880 std::vector<spv::Id> components;
4881 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4882 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4883
4884 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4885 return builder.createUnaryOp(spv::OpBitcast, typeId,
4886 builder.createCompositeConstruct(uvec2Type, components));
4887 }
4888
Rex Xu9d93a232016-05-05 12:30:44 +08004889#ifdef AMD_EXTENSIONS
4890 case glslang::EOpMinInvocations:
4891 case glslang::EOpMaxInvocations:
4892 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004893 case glslang::EOpMinInvocationsInclusiveScan:
4894 case glslang::EOpMaxInvocationsInclusiveScan:
4895 case glslang::EOpAddInvocationsInclusiveScan:
4896 case glslang::EOpMinInvocationsExclusiveScan:
4897 case glslang::EOpMaxInvocationsExclusiveScan:
4898 case glslang::EOpAddInvocationsExclusiveScan:
4899 if (op == glslang::EOpMinInvocations ||
4900 op == glslang::EOpMinInvocationsInclusiveScan ||
4901 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004902 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004903 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004904 else {
4905 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004906 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004907 else
Rex Xu51596642016-09-21 18:56:12 +08004908 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004909 }
Rex Xu430ef402016-10-14 17:22:23 +08004910 } else if (op == glslang::EOpMaxInvocations ||
4911 op == glslang::EOpMaxInvocationsInclusiveScan ||
4912 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004913 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004914 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004915 else {
4916 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004917 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004918 else
Rex Xu51596642016-09-21 18:56:12 +08004919 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004920 }
4921 } else {
4922 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004923 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004924 else
Rex Xu51596642016-09-21 18:56:12 +08004925 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004926 }
4927
Rex Xu2bbbe062016-08-23 15:41:05 +08004928 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004929 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004930
4931 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004932 case glslang::EOpMinInvocationsNonUniform:
4933 case glslang::EOpMaxInvocationsNonUniform:
4934 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004935 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4936 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4937 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4938 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4939 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4940 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4941 if (op == glslang::EOpMinInvocationsNonUniform ||
4942 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4943 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004944 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004945 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004946 else {
4947 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004948 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004949 else
Rex Xu51596642016-09-21 18:56:12 +08004950 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004951 }
4952 }
Rex Xu430ef402016-10-14 17:22:23 +08004953 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4954 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4955 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004956 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004957 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004958 else {
4959 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004960 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004961 else
Rex Xu51596642016-09-21 18:56:12 +08004962 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004963 }
4964 }
4965 else {
4966 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004967 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004968 else
Rex Xu51596642016-09-21 18:56:12 +08004969 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004970 }
4971
Rex Xu2bbbe062016-08-23 15:41:05 +08004972 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004973 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004974
4975 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004976#endif
John Kessenich91cef522016-05-05 16:45:40 -06004977 default:
4978 logger->missingFunctionality("invocation operation");
4979 return spv::NoResult;
4980 }
Rex Xu51596642016-09-21 18:56:12 +08004981
4982 assert(opCode != spv::OpNop);
4983 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004984}
4985
Rex Xu2bbbe062016-08-23 15:41:05 +08004986// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004987spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004988{
Rex Xub7072052016-09-26 15:53:40 +08004989#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004990 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4991 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004992 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004993 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004994 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4995 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4996 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004997#else
4998 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4999 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005000 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5001 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005002#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005003
5004 // Handle group invocation operations scalar by scalar.
5005 // The result type is the same type as the original type.
5006 // The algorithm is to:
5007 // - break the vector into scalars
5008 // - apply the operation to each scalar
5009 // - make a vector out the scalar results
5010
5011 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005012 int numComponents = builder.getNumComponents(operands[0]);
5013 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005014 std::vector<spv::Id> results;
5015
5016 // do each scalar op
5017 for (int comp = 0; comp < numComponents; ++comp) {
5018 std::vector<unsigned int> indexes;
5019 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005020 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005021 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005022 if (op == spv::OpSubgroupReadInvocationKHR) {
5023 spvGroupOperands.push_back(scalar);
5024 spvGroupOperands.push_back(operands[1]);
5025 } else if (op == spv::OpGroupBroadcast) {
5026 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005027 spvGroupOperands.push_back(scalar);
5028 spvGroupOperands.push_back(operands[1]);
5029 } else {
chaocf200da82016-12-20 12:44:35 -08005030 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005031 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005032 spvGroupOperands.push_back(scalar);
5033 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005034
Rex Xub7072052016-09-26 15:53:40 +08005035 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005036 }
5037
5038 // put the pieces together
5039 return builder.createCompositeConstruct(typeId, results);
5040}
Rex Xu2bbbe062016-08-23 15:41:05 +08005041
John Kessenich5e4b1242015-08-06 22:53:06 -06005042spv::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 -06005043{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005044#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005045 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005046 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5047#else
Rex Xucabbb782017-03-24 13:41:14 +08005048 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005049 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005050#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005051
John Kessenich140f3df2015-06-26 16:58:36 -06005052 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005053 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005054 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005055 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005056 spv::Id typeId0 = 0;
5057 if (consumedOperands > 0)
5058 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005059 spv::Id typeId1 = 0;
5060 if (consumedOperands > 1)
5061 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005062 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005063
5064 switch (op) {
5065 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005066 if (isFloat)
5067 libCall = spv::GLSLstd450FMin;
5068 else if (isUnsigned)
5069 libCall = spv::GLSLstd450UMin;
5070 else
5071 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005072 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005073 break;
5074 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005075 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005076 break;
5077 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005078 if (isFloat)
5079 libCall = spv::GLSLstd450FMax;
5080 else if (isUnsigned)
5081 libCall = spv::GLSLstd450UMax;
5082 else
5083 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005084 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005085 break;
5086 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005087 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005088 break;
5089 case glslang::EOpDot:
5090 opCode = spv::OpDot;
5091 break;
5092 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005093 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005094 break;
5095
5096 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005097 if (isFloat)
5098 libCall = spv::GLSLstd450FClamp;
5099 else if (isUnsigned)
5100 libCall = spv::GLSLstd450UClamp;
5101 else
5102 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005103 builder.promoteScalar(precision, operands.front(), operands[1]);
5104 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005105 break;
5106 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005107 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5108 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005109 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005110 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005111 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005112 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005113 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005114 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005115 break;
5116 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005117 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005118 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005119 break;
5120 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005121 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005122 builder.promoteScalar(precision, operands[0], operands[2]);
5123 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005124 break;
5125
5126 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005127 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005128 break;
5129 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005130 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005131 break;
5132 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005133 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005134 break;
5135 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005136 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005137 break;
5138 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005139 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005140 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005141 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005142 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005143 libCall = spv::GLSLstd450InterpolateAtSample;
5144 break;
5145 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005146 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005147 libCall = spv::GLSLstd450InterpolateAtOffset;
5148 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005149 case glslang::EOpAddCarry:
5150 opCode = spv::OpIAddCarry;
5151 typeId = builder.makeStructResultType(typeId0, typeId0);
5152 consumedOperands = 2;
5153 break;
5154 case glslang::EOpSubBorrow:
5155 opCode = spv::OpISubBorrow;
5156 typeId = builder.makeStructResultType(typeId0, typeId0);
5157 consumedOperands = 2;
5158 break;
5159 case glslang::EOpUMulExtended:
5160 opCode = spv::OpUMulExtended;
5161 typeId = builder.makeStructResultType(typeId0, typeId0);
5162 consumedOperands = 2;
5163 break;
5164 case glslang::EOpIMulExtended:
5165 opCode = spv::OpSMulExtended;
5166 typeId = builder.makeStructResultType(typeId0, typeId0);
5167 consumedOperands = 2;
5168 break;
5169 case glslang::EOpBitfieldExtract:
5170 if (isUnsigned)
5171 opCode = spv::OpBitFieldUExtract;
5172 else
5173 opCode = spv::OpBitFieldSExtract;
5174 break;
5175 case glslang::EOpBitfieldInsert:
5176 opCode = spv::OpBitFieldInsert;
5177 break;
5178
5179 case glslang::EOpFma:
5180 libCall = spv::GLSLstd450Fma;
5181 break;
5182 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005183 {
5184 libCall = spv::GLSLstd450FrexpStruct;
5185 assert(builder.isPointerType(typeId1));
5186 typeId1 = builder.getContainedTypeId(typeId1);
5187#ifdef AMD_EXTENSIONS
5188 int width = builder.getScalarTypeWidth(typeId1);
5189#else
5190 int width = 32;
5191#endif
5192 if (builder.getNumComponents(operands[0]) == 1)
5193 frexpIntType = builder.makeIntegerType(width, true);
5194 else
5195 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5196 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5197 consumedOperands = 1;
5198 }
John Kessenich55e7d112015-11-15 21:33:39 -07005199 break;
5200 case glslang::EOpLdexp:
5201 libCall = spv::GLSLstd450Ldexp;
5202 break;
5203
Rex Xu574ab042016-04-14 16:53:07 +08005204 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005205 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005206
Rex Xu9d93a232016-05-05 12:30:44 +08005207#ifdef AMD_EXTENSIONS
5208 case glslang::EOpSwizzleInvocations:
5209 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5210 libCall = spv::SwizzleInvocationsAMD;
5211 break;
5212 case glslang::EOpSwizzleInvocationsMasked:
5213 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5214 libCall = spv::SwizzleInvocationsMaskedAMD;
5215 break;
5216 case glslang::EOpWriteInvocation:
5217 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5218 libCall = spv::WriteInvocationAMD;
5219 break;
5220
5221 case glslang::EOpMin3:
5222 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5223 if (isFloat)
5224 libCall = spv::FMin3AMD;
5225 else {
5226 if (isUnsigned)
5227 libCall = spv::UMin3AMD;
5228 else
5229 libCall = spv::SMin3AMD;
5230 }
5231 break;
5232 case glslang::EOpMax3:
5233 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5234 if (isFloat)
5235 libCall = spv::FMax3AMD;
5236 else {
5237 if (isUnsigned)
5238 libCall = spv::UMax3AMD;
5239 else
5240 libCall = spv::SMax3AMD;
5241 }
5242 break;
5243 case glslang::EOpMid3:
5244 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5245 if (isFloat)
5246 libCall = spv::FMid3AMD;
5247 else {
5248 if (isUnsigned)
5249 libCall = spv::UMid3AMD;
5250 else
5251 libCall = spv::SMid3AMD;
5252 }
5253 break;
5254
5255 case glslang::EOpInterpolateAtVertex:
5256 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5257 libCall = spv::InterpolateAtVertexAMD;
5258 break;
5259#endif
5260
John Kessenich140f3df2015-06-26 16:58:36 -06005261 default:
5262 return 0;
5263 }
5264
5265 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005266 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005267 // Use an extended instruction from the standard library.
5268 // Construct the call arguments, without modifying the original operands vector.
5269 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5270 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005271 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005272 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005273 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005274 case 0:
5275 // should all be handled by visitAggregate and createNoArgOperation
5276 assert(0);
5277 return 0;
5278 case 1:
5279 // should all be handled by createUnaryOperation
5280 assert(0);
5281 return 0;
5282 case 2:
5283 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5284 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005285 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005286 // anything 3 or over doesn't have l-value operands, so all should be consumed
5287 assert(consumedOperands == operands.size());
5288 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005289 break;
5290 }
5291 }
5292
John Kessenich55e7d112015-11-15 21:33:39 -07005293 // Decode the return types that were structures
5294 switch (op) {
5295 case glslang::EOpAddCarry:
5296 case glslang::EOpSubBorrow:
5297 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5298 id = builder.createCompositeExtract(id, typeId0, 0);
5299 break;
5300 case glslang::EOpUMulExtended:
5301 case glslang::EOpIMulExtended:
5302 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5303 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5304 break;
5305 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005306 {
5307 assert(operands.size() == 2);
5308 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5309 // "exp" is floating-point type (from HLSL intrinsic)
5310 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5311 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5312 builder.createStore(member1, operands[1]);
5313 } else
5314 // "exp" is integer type (from GLSL built-in function)
5315 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5316 id = builder.createCompositeExtract(id, typeId0, 0);
5317 }
John Kessenich55e7d112015-11-15 21:33:39 -07005318 break;
5319 default:
5320 break;
5321 }
5322
John Kessenich32cfd492016-02-02 12:37:46 -07005323 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005324}
5325
Rex Xu9d93a232016-05-05 12:30:44 +08005326// Intrinsics with no arguments (or no return value, and no precision).
5327spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005328{
5329 // TODO: get the barrier operands correct
5330
5331 switch (op) {
5332 case glslang::EOpEmitVertex:
5333 builder.createNoResultOp(spv::OpEmitVertex);
5334 return 0;
5335 case glslang::EOpEndPrimitive:
5336 builder.createNoResultOp(spv::OpEndPrimitive);
5337 return 0;
5338 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005339 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005340 return 0;
5341 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005342 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005343 return 0;
5344 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005345 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005346 return 0;
5347 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005348 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005349 return 0;
5350 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005351 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005352 return 0;
5353 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005354 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005355 return 0;
5356 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005357 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005358 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005359 case glslang::EOpAllMemoryBarrierWithGroupSync:
5360 // Control barrier with non-"None" semantic is also a memory barrier.
5361 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5362 return 0;
5363 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5364 // Control barrier with non-"None" semantic is also a memory barrier.
5365 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5366 return 0;
5367 case glslang::EOpWorkgroupMemoryBarrier:
5368 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5369 return 0;
5370 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5371 // Control barrier with non-"None" semantic is also a memory barrier.
5372 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5373 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005374#ifdef AMD_EXTENSIONS
5375 case glslang::EOpTime:
5376 {
5377 std::vector<spv::Id> args; // Dummy arguments
5378 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5379 return builder.setPrecision(id, precision);
5380 }
5381#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005382 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005383 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005384 return 0;
5385 }
5386}
5387
5388spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5389{
John Kessenich2f273362015-07-18 22:34:27 -06005390 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005391 spv::Id id;
5392 if (symbolValues.end() != iter) {
5393 id = iter->second;
5394 return id;
5395 }
5396
5397 // it was not found, create it
5398 id = createSpvVariable(symbol);
5399 symbolValues[symbol->getId()] = id;
5400
Rex Xuc884b4a2016-06-29 15:03:44 +08005401 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005402 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005403 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005404 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005405 if (symbol->getType().getQualifier().hasSpecConstantId())
5406 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005407 if (symbol->getQualifier().hasIndex())
5408 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5409 if (symbol->getQualifier().hasComponent())
5410 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5411 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005412 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005413 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005414 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005415 if (symbol->getQualifier().hasXfbBuffer())
5416 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5417 if (symbol->getQualifier().hasXfbOffset())
5418 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5419 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005420 // atomic counters use this:
5421 if (symbol->getQualifier().hasOffset())
5422 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005423 }
5424
scygan2c864272016-05-18 18:09:17 +02005425 if (symbol->getQualifier().hasLocation())
5426 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005427 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005428 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005429 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005430 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005431 }
John Kessenich140f3df2015-06-26 16:58:36 -06005432 if (symbol->getQualifier().hasSet())
5433 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005434 else if (IsDescriptorResource(symbol->getType())) {
5435 // default to 0
5436 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5437 }
John Kessenich140f3df2015-06-26 16:58:36 -06005438 if (symbol->getQualifier().hasBinding())
5439 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005440 if (symbol->getQualifier().hasAttachment())
5441 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005442 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005443 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005444 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005445 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005446 if (symbol->getQualifier().hasXfbBuffer())
5447 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5448 }
5449
Rex Xu1da878f2016-02-21 20:59:01 +08005450 if (symbol->getType().isImage()) {
5451 std::vector<spv::Decoration> memory;
5452 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5453 for (unsigned int i = 0; i < memory.size(); ++i)
5454 addDecoration(id, memory[i]);
5455 }
5456
John Kessenich140f3df2015-06-26 16:58:36 -06005457 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005458 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005459 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005460 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005461
John Kessenichecba76f2017-01-06 00:34:48 -07005462#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005463 if (builtIn == spv::BuiltInSampleMask) {
5464 spv::Decoration decoration;
5465 // GL_NV_sample_mask_override_coverage extension
5466 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005467 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005468 else
5469 decoration = (spv::Decoration)spv::DecorationMax;
5470 addDecoration(id, decoration);
5471 if (decoration != spv::DecorationMax) {
5472 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5473 }
5474 }
chaoc771d89f2017-01-13 01:10:53 -08005475 else if (builtIn == spv::BuiltInLayer) {
5476 // SPV_NV_viewport_array2 extension
5477 if (symbol->getQualifier().layoutViewportRelative)
5478 {
5479 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5480 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5481 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5482 }
5483 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5484 {
5485 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5486 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5487 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5488 }
5489 }
5490
chaoc6e5acae2016-12-20 13:28:52 -08005491 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005492 addDecoration(id, spv::DecorationPassthroughNV);
5493 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005494 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5495 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005496#endif
5497
John Kessenich140f3df2015-06-26 16:58:36 -06005498 return id;
5499}
5500
John Kessenich55e7d112015-11-15 21:33:39 -07005501// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005502void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5503{
John Kessenich4016e382016-07-15 11:53:56 -06005504 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005505 builder.addDecoration(id, dec);
5506}
5507
John Kessenich55e7d112015-11-15 21:33:39 -07005508// If 'dec' is valid, add a one-operand decoration to an object
5509void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5510{
John Kessenich4016e382016-07-15 11:53:56 -06005511 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005512 builder.addDecoration(id, dec, value);
5513}
5514
5515// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005516void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5517{
John Kessenich4016e382016-07-15 11:53:56 -06005518 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005519 builder.addMemberDecoration(id, (unsigned)member, dec);
5520}
5521
John Kessenich92187592016-02-01 13:45:25 -07005522// If 'dec' is valid, add a one-operand decoration to a struct member
5523void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5524{
John Kessenich4016e382016-07-15 11:53:56 -06005525 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005526 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5527}
5528
John Kessenich55e7d112015-11-15 21:33:39 -07005529// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005530// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005531//
5532// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5533//
5534// Recursively walk the nodes. The nodes form a tree whose leaves are
5535// regular constants, which themselves are trees that createSpvConstant()
5536// recursively walks. So, this function walks the "top" of the tree:
5537// - emit specialization constant-building instructions for specConstant
5538// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005539spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005540{
John Kessenich7cc0e282016-03-20 00:46:02 -06005541 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005542
qining4f4bb812016-04-03 23:55:17 -04005543 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005544 if (! node.getQualifier().specConstant) {
5545 // hand off to the non-spec-constant path
5546 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5547 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005548 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005549 nextConst, false);
5550 }
5551
5552 // We now know we have a specialization constant to build
5553
John Kessenichd94c0032016-05-30 19:29:40 -06005554 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005555 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5556 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5557 std::vector<spv::Id> dimConstId;
5558 for (int dim = 0; dim < 3; ++dim) {
5559 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5560 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5561 if (specConst)
5562 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5563 }
5564 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5565 }
5566
5567 // An AST node labelled as specialization constant should be a symbol node.
5568 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5569 if (auto* sn = node.getAsSymbolNode()) {
5570 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005571 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5572 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5573 // will set the builder into spec constant op instruction generating mode.
5574 sub_tree->traverse(this);
5575 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005576 } else if (auto* const_union_array = &sn->getConstArray()){
5577 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005578 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5579 builder.addName(id, sn->getName().c_str());
5580 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005581 }
5582 }
qining4f4bb812016-04-03 23:55:17 -04005583
5584 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5585 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005586 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005587 exit(1);
5588 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005589}
5590
John Kessenich140f3df2015-06-26 16:58:36 -06005591// Use 'consts' as the flattened glslang source of scalar constants to recursively
5592// build the aggregate SPIR-V constant.
5593//
5594// If there are not enough elements present in 'consts', 0 will be substituted;
5595// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5596//
qining08408382016-03-21 09:51:37 -04005597spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005598{
5599 // vector of constants for SPIR-V
5600 std::vector<spv::Id> spvConsts;
5601
5602 // Type is used for struct and array constants
5603 spv::Id typeId = convertGlslangToSpvType(glslangType);
5604
5605 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005606 glslang::TType elementType(glslangType, 0);
5607 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005608 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005609 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005610 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005611 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005612 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005613 } else if (glslangType.getStruct()) {
5614 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5615 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005616 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005617 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005618 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5619 bool zero = nextConst >= consts.size();
5620 switch (glslangType.getBasicType()) {
5621 case glslang::EbtInt:
5622 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5623 break;
5624 case glslang::EbtUint:
5625 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5626 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005627 case glslang::EbtInt64:
5628 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5629 break;
5630 case glslang::EbtUint64:
5631 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5632 break;
Rex Xucabbb782017-03-24 13:41:14 +08005633#ifdef AMD_EXTENSIONS
5634 case glslang::EbtInt16:
5635 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5636 break;
5637 case glslang::EbtUint16:
5638 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5639 break;
5640#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005641 case glslang::EbtFloat:
5642 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5643 break;
5644 case glslang::EbtDouble:
5645 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5646 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005647#ifdef AMD_EXTENSIONS
5648 case glslang::EbtFloat16:
5649 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5650 break;
5651#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005652 case glslang::EbtBool:
5653 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5654 break;
5655 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005656 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005657 break;
5658 }
5659 ++nextConst;
5660 }
5661 } else {
5662 // we have a non-aggregate (scalar) constant
5663 bool zero = nextConst >= consts.size();
5664 spv::Id scalar = 0;
5665 switch (glslangType.getBasicType()) {
5666 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005667 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005668 break;
5669 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005670 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005671 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005672 case glslang::EbtInt64:
5673 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5674 break;
5675 case glslang::EbtUint64:
5676 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5677 break;
Rex Xucabbb782017-03-24 13:41:14 +08005678#ifdef AMD_EXTENSIONS
5679 case glslang::EbtInt16:
5680 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5681 break;
5682 case glslang::EbtUint16:
5683 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5684 break;
5685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005686 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005687 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005688 break;
5689 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005690 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005691 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005692#ifdef AMD_EXTENSIONS
5693 case glslang::EbtFloat16:
5694 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5695 break;
5696#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005697 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005698 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005699 break;
5700 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005701 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005702 break;
5703 }
5704 ++nextConst;
5705 return scalar;
5706 }
5707
5708 return builder.makeCompositeConstant(typeId, spvConsts);
5709}
5710
John Kessenich7c1aa102015-10-15 13:29:11 -06005711// Return true if the node is a constant or symbol whose reading has no
5712// non-trivial observable cost or effect.
5713bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5714{
5715 // don't know what this is
5716 if (node == nullptr)
5717 return false;
5718
5719 // a constant is safe
5720 if (node->getAsConstantUnion() != nullptr)
5721 return true;
5722
5723 // not a symbol means non-trivial
5724 if (node->getAsSymbolNode() == nullptr)
5725 return false;
5726
5727 // a symbol, depends on what's being read
5728 switch (node->getType().getQualifier().storage) {
5729 case glslang::EvqTemporary:
5730 case glslang::EvqGlobal:
5731 case glslang::EvqIn:
5732 case glslang::EvqInOut:
5733 case glslang::EvqConst:
5734 case glslang::EvqConstReadOnly:
5735 case glslang::EvqUniform:
5736 return true;
5737 default:
5738 return false;
5739 }
qining25262b32016-05-06 17:25:16 -04005740}
John Kessenich7c1aa102015-10-15 13:29:11 -06005741
5742// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005743// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005744// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005745// Return true if trivial.
5746bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5747{
5748 if (node == nullptr)
5749 return false;
5750
John Kessenich84cc15f2017-05-24 16:44:47 -06005751 // count non scalars as trivial, as well as anything coming from HLSL
5752 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005753 return true;
5754
John Kessenich7c1aa102015-10-15 13:29:11 -06005755 // symbols and constants are trivial
5756 if (isTrivialLeaf(node))
5757 return true;
5758
5759 // otherwise, it needs to be a simple operation or one or two leaf nodes
5760
5761 // not a simple operation
5762 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5763 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5764 if (binaryNode == nullptr && unaryNode == nullptr)
5765 return false;
5766
5767 // not on leaf nodes
5768 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5769 return false;
5770
5771 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5772 return false;
5773 }
5774
5775 switch (node->getAsOperator()->getOp()) {
5776 case glslang::EOpLogicalNot:
5777 case glslang::EOpConvIntToBool:
5778 case glslang::EOpConvUintToBool:
5779 case glslang::EOpConvFloatToBool:
5780 case glslang::EOpConvDoubleToBool:
5781 case glslang::EOpEqual:
5782 case glslang::EOpNotEqual:
5783 case glslang::EOpLessThan:
5784 case glslang::EOpGreaterThan:
5785 case glslang::EOpLessThanEqual:
5786 case glslang::EOpGreaterThanEqual:
5787 case glslang::EOpIndexDirect:
5788 case glslang::EOpIndexDirectStruct:
5789 case glslang::EOpLogicalXor:
5790 case glslang::EOpAny:
5791 case glslang::EOpAll:
5792 return true;
5793 default:
5794 return false;
5795 }
5796}
5797
5798// Emit short-circuiting code, where 'right' is never evaluated unless
5799// the left side is true (for &&) or false (for ||).
5800spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5801{
5802 spv::Id boolTypeId = builder.makeBoolType();
5803
5804 // emit left operand
5805 builder.clearAccessChain();
5806 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005807 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005808
5809 // Operands to accumulate OpPhi operands
5810 std::vector<spv::Id> phiOperands;
5811 // accumulate left operand's phi information
5812 phiOperands.push_back(leftId);
5813 phiOperands.push_back(builder.getBuildPoint()->getId());
5814
5815 // Make the two kinds of operation symmetric with a "!"
5816 // || => emit "if (! left) result = right"
5817 // && => emit "if ( left) result = right"
5818 //
5819 // TODO: this runtime "not" for || could be avoided by adding functionality
5820 // to 'builder' to have an "else" without an "then"
5821 if (op == glslang::EOpLogicalOr)
5822 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5823
5824 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005825 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005826
5827 // emit right operand as the "then" part of the "if"
5828 builder.clearAccessChain();
5829 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005830 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005831
5832 // accumulate left operand's phi information
5833 phiOperands.push_back(rightId);
5834 phiOperands.push_back(builder.getBuildPoint()->getId());
5835
5836 // finish the "if"
5837 ifBuilder.makeEndIf();
5838
5839 // phi together the two results
5840 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5841}
5842
Rex Xu9d93a232016-05-05 12:30:44 +08005843// Return type Id of the imported set of extended instructions corresponds to the name.
5844// Import this set if it has not been imported yet.
5845spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5846{
5847 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5848 return extBuiltinMap[name];
5849 else {
Rex Xu51596642016-09-21 18:56:12 +08005850 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005851 spv::Id extBuiltins = builder.import(name);
5852 extBuiltinMap[name] = extBuiltins;
5853 return extBuiltins;
5854 }
5855}
5856
John Kessenich140f3df2015-06-26 16:58:36 -06005857}; // end anonymous namespace
5858
5859namespace glslang {
5860
John Kessenich68d78fd2015-07-12 19:28:10 -06005861void GetSpirvVersion(std::string& version)
5862{
John Kessenich9e55f632015-07-15 10:03:39 -06005863 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005864 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005865 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005866 version = buf;
5867}
5868
John Kessenich140f3df2015-06-26 16:58:36 -06005869// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005870void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005871{
5872 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005873 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005874 if (out.fail())
5875 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005876 for (int i = 0; i < (int)spirv.size(); ++i) {
5877 unsigned int word = spirv[i];
5878 out.write((const char*)&word, 4);
5879 }
5880 out.close();
5881}
5882
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005883// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005884void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005885{
5886 std::ofstream out;
5887 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005888 if (out.fail())
5889 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005890 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005891 if (varName != nullptr) {
5892 out << "\t #pragma once" << std::endl;
5893 out << "const uint32_t " << varName << "[] = {" << std::endl;
5894 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005895 const int WORDS_PER_LINE = 8;
5896 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5897 out << "\t";
5898 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5899 const unsigned int word = spirv[i + j];
5900 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5901 if (i + j + 1 < (int)spirv.size()) {
5902 out << ",";
5903 }
5904 }
5905 out << std::endl;
5906 }
Flavio15017db2017-02-15 14:29:33 -08005907 if (varName != nullptr) {
5908 out << "};";
5909 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005910 out.close();
5911}
5912
John Kessenich140f3df2015-06-26 16:58:36 -06005913//
5914// Set up the glslang traversal
5915//
John Kessenich121853f2017-05-31 17:11:16 -06005916void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005917{
Lei Zhang17535f72016-05-04 15:55:59 -04005918 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005919 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005920}
5921
John Kessenich121853f2017-05-31 17:11:16 -06005922void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5923 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005924{
John Kessenich140f3df2015-06-26 16:58:36 -06005925 TIntermNode* root = intermediate.getTreeRoot();
5926
5927 if (root == 0)
5928 return;
5929
John Kessenich121853f2017-05-31 17:11:16 -06005930 glslang::SpvOptions defaultOptions;
5931 if (options == nullptr)
5932 options = &defaultOptions;
5933
John Kessenich140f3df2015-06-26 16:58:36 -06005934 glslang::GetThreadPoolAllocator().push();
5935
John Kessenich121853f2017-05-31 17:11:16 -06005936 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005937 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005938 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005939 it.dumpSpv(spirv);
5940
5941 glslang::GetThreadPoolAllocator().pop();
5942}
5943
5944}; // end namespace glslang