blob: cb48d3496b51b6514a42595285012e026aaddb61 [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:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
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);
steve-lunargf1709e72017-05-02 20:14:50 -0600125 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenich140f3df2015-06-26 16:58:36 -0600126 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
127 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600128 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
129 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
130 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600131 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700132 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600133 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600134 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
135 glslang::TLayoutPacking, const glslang::TQualifier&);
136 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
137 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700138 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700139 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800140 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600141 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700142 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700143 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
144 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
145 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 +0100146 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600147
John Kessenich6fccb3c2016-09-19 16:01:41 -0600148 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600149 void makeFunctions(const glslang::TIntermSequence&);
150 void makeGlobalInitializers(const glslang::TIntermSequence&);
151 void visitFunctions(const glslang::TIntermSequence&);
152 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800153 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600154 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
155 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600156 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
157
qining25262b32016-05-06 17:25:16 -0400158 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);
159 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
160 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 +0800161 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 +0800162 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 -0600163 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800164 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 +0800165 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800166 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600167 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 +0800168 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600169 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
170 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700171 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600172 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700173 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400174 spv::Id createSpvConstant(const glslang::TIntermTyped&);
175 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600176 bool isTrivialLeaf(const glslang::TIntermTyped* node);
177 bool isTrivial(const glslang::TIntermTyped* node);
178 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800179 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600180
181 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600182 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700183 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 int sequenceDepth;
185
Lei Zhang17535f72016-05-04 15:55:59 -0400186 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400187
John Kessenich140f3df2015-06-26 16:58:36 -0600188 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
189 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700190 bool inEntryPoint;
191 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700192 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 -0700193 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600194 const glslang::TIntermediate* glslangIntermediate;
195 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800196 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600197
John Kessenich2f273362015-07-18 22:34:27 -0600198 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600199 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600200 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700201 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600202 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 -0600203 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600204};
205
206//
207// Helper functions for translating glslang representations to SPIR-V enumerants.
208//
209
210// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700211spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600212{
John Kessenich66e2faf2016-03-12 18:34:36 -0700213 switch (source) {
214 case glslang::EShSourceGlsl:
215 switch (profile) {
216 case ENoProfile:
217 case ECoreProfile:
218 case ECompatibilityProfile:
219 return spv::SourceLanguageGLSL;
220 case EEsProfile:
221 return spv::SourceLanguageESSL;
222 default:
223 return spv::SourceLanguageUnknown;
224 }
225 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600226 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 default:
228 return spv::SourceLanguageUnknown;
229 }
230}
231
232// Translate glslang language (stage) to SPIR-V execution model.
233spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
234{
235 switch (stage) {
236 case EShLangVertex: return spv::ExecutionModelVertex;
237 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
238 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
239 case EShLangGeometry: return spv::ExecutionModelGeometry;
240 case EShLangFragment: return spv::ExecutionModelFragment;
241 case EShLangCompute: return spv::ExecutionModelGLCompute;
242 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700243 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600244 return spv::ExecutionModelFragment;
245 }
246}
247
248// Translate glslang type to SPIR-V storage class.
John Kessenich67027182017-04-19 18:34:49 -0600249spv::StorageClass TranslateStorageClass(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600250{
251 if (type.getQualifier().isPipeInput())
252 return spv::StorageClassInput;
253 else if (type.getQualifier().isPipeOutput())
254 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700255 else if (type.getBasicType() == glslang::EbtAtomicUint)
256 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700257 else if (type.containsOpaque())
258 return spv::StorageClassUniformConstant;
John Kessenich67027182017-04-19 18:34:49 -0600259 else if (useStorageBuffer && type.getQualifier().storage == glslang::EvqBuffer)
260 return spv::StorageClassStorageBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700262 if (type.getQualifier().layoutPushConstant)
263 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 if (type.getBasicType() == glslang::EbtBlock)
265 return spv::StorageClassUniform;
266 else
267 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600268 } else {
269 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700270 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
271 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
273 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400274 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700275 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::StorageClassFunction;
277 }
278 }
279}
280
281// Translate glslang sampler type to SPIR-V dimensionality.
282spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
283{
284 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700285 case glslang::Esd1D: return spv::Dim1D;
286 case glslang::Esd2D: return spv::Dim2D;
287 case glslang::Esd3D: return spv::Dim3D;
288 case glslang::EsdCube: return spv::DimCube;
289 case glslang::EsdRect: return spv::DimRect;
290 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700291 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 return spv::Dim2D;
295 }
296}
297
John Kessenichf6640762016-08-01 19:44:00 -0600298// Translate glslang precision to SPIR-V precision decorations.
299spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600300{
John Kessenichf6640762016-08-01 19:44:00 -0600301 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700302 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600303 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::NoPrecision;
306 }
307}
308
John Kessenichf6640762016-08-01 19:44:00 -0600309// Translate glslang type to SPIR-V precision decorations.
310spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
311{
312 return TranslatePrecisionDecoration(type.getQualifier().precision);
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600316spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600317{
318 if (type.getBasicType() == glslang::EbtBlock) {
319 switch (type.getQualifier().storage) {
320 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600321 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case glslang::EvqVaryingIn: return spv::DecorationBlock;
323 case glslang::EvqVaryingOut: return spv::DecorationBlock;
324 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700325 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600326 break;
327 }
328 }
329
John Kessenich4016e382016-07-15 11:53:56 -0600330 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600331}
332
Rex Xu1da878f2016-02-21 20:59:01 +0800333// Translate glslang type to SPIR-V memory decorations.
334void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
335{
336 if (qualifier.coherent)
337 memory.push_back(spv::DecorationCoherent);
338 if (qualifier.volatil)
339 memory.push_back(spv::DecorationVolatile);
340 if (qualifier.restrict)
341 memory.push_back(spv::DecorationRestrict);
342 if (qualifier.readonly)
343 memory.push_back(spv::DecorationNonWritable);
344 if (qualifier.writeonly)
345 memory.push_back(spv::DecorationNonReadable);
346}
347
John Kessenich140f3df2015-06-26 16:58:36 -0600348// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700349spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600350{
351 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600353 case glslang::ElmRowMajor:
354 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600356 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700357 default:
358 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 }
361 } else {
362 switch (type.getBasicType()) {
363 default:
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 break;
366 case glslang::EbtBlock:
367 switch (type.getQualifier().storage) {
368 case glslang::EvqUniform:
369 case glslang::EvqBuffer:
370 switch (type.getQualifier().layoutPacking) {
371 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
373 default:
John Kessenich4016e382016-07-15 11:53:56 -0600374 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600375 }
376 case glslang::EvqVaryingIn:
377 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700381 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600382 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600383 }
384 }
385 }
386}
387
388// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600389// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700390// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800391spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600392{
Rex Xubbceed72016-05-21 09:40:44 +0800393 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600395 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800396 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700397 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700398 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600399 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800400#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800401 else if (qualifier.explicitInterp) {
402 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800403 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800404 }
Rex Xu9d93a232016-05-05 12:30:44 +0800405#endif
Rex Xubbceed72016-05-21 09:40:44 +0800406 else
John Kessenich4016e382016-07-15 11:53:56 -0600407 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800408}
409
410// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600411// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800412// should be applied.
413spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
414{
415 if (qualifier.patch)
416 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700417 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700419 else if (qualifier.sample) {
420 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600421 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700422 } else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424}
425
John Kessenich92187592016-02-01 13:45:25 -0700426// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600428{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700429 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600430 return spv::DecorationInvariant;
431 else
John Kessenich4016e382016-07-15 11:53:56 -0600432 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600433}
434
qining9220dbb2016-05-04 17:34:38 -0400435// If glslang type is noContraction, return SPIR-V NoContraction decoration.
436spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
437{
438 if (qualifier.noContraction)
439 return spv::DecorationNoContraction;
440 else
John Kessenich4016e382016-07-15 11:53:56 -0600441 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400442}
443
David Netoa901ffe2016-06-08 14:11:40 +0100444// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
445// associated capabilities when required. For some built-in variables, a capability
446// is generated only when using the variable in an executable instruction, but not when
447// just declaring a struct member variable with it. This is true for PointSize,
448// ClipDistance, and CullDistance.
449spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600450{
451 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700452 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600453 // Defer adding the capability until the built-in is actually used.
454 if (! memberDeclaration) {
455 switch (glslangIntermediate->getStage()) {
456 case EShLangGeometry:
457 builder.addCapability(spv::CapabilityGeometryPointSize);
458 break;
459 case EShLangTessControl:
460 case EShLangTessEvaluation:
461 builder.addCapability(spv::CapabilityTessellationPointSize);
462 break;
463 default:
464 break;
465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 }
467 return spv::BuiltInPointSize;
468
John Kessenichebb50532016-05-16 19:22:05 -0600469 // These *Distance capabilities logically belong here, but if the member is declared and
470 // then never used, consumers of SPIR-V prefer the capability not be declared.
471 // They are now generated when used, rather than here when declared.
472 // Potentially, the specification should be more clear what the minimum
473 // use needed is to trigger the capability.
474 //
John Kessenich92187592016-02-01 13:45:25 -0700475 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100476 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800477 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700478 return spv::BuiltInClipDistance;
479
480 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100481 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800482 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700483 return spv::BuiltInCullDistance;
484
485 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 if (!memberDeclaration) {
487 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800488#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800489 if (glslangIntermediate->getStage() == EShLangVertex ||
490 glslangIntermediate->getStage() == EShLangTessControl ||
491 glslangIntermediate->getStage() == EShLangTessEvaluation) {
492
493 builder.addExtension(spv::E_SPV_NV_viewport_array2);
494 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
495 }
chaoc771d89f2017-01-13 01:10:53 -0800496#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800497 }
John Kessenich92187592016-02-01 13:45:25 -0700498 return spv::BuiltInViewportIndex;
499
John Kessenich5e801132016-02-15 11:09:46 -0700500 case glslang::EbvSampleId:
501 builder.addCapability(spv::CapabilitySampleRateShading);
502 return spv::BuiltInSampleId;
503
504 case glslang::EbvSamplePosition:
505 builder.addCapability(spv::CapabilitySampleRateShading);
506 return spv::BuiltInSamplePosition;
507
508 case glslang::EbvSampleMask:
509 builder.addCapability(spv::CapabilitySampleRateShading);
510 return spv::BuiltInSampleMask;
511
John Kessenich78a45572016-07-08 14:05:15 -0600512 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800513 if (!memberDeclaration) {
514 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800515#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800516 if (glslangIntermediate->getStage() == EShLangVertex ||
517 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800518 glslangIntermediate->getStage() == EShLangTessEvaluation) {
519
chaoc771d89f2017-01-13 01:10:53 -0800520 builder.addExtension(spv::E_SPV_NV_viewport_array2);
521 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
522 }
chaoc771d89f2017-01-13 01:10:53 -0800523#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800524 }
525
John Kessenich78a45572016-07-08 14:05:15 -0600526 return spv::BuiltInLayer;
527
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvVertexId: return spv::BuiltInVertexId;
530 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700531 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
532 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800533
John Kessenichda581a22015-10-14 14:10:30 -0600534 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
536 builder.addCapability(spv::CapabilityDrawParameters);
537 return spv::BuiltInBaseVertex;
538
John Kessenichda581a22015-10-14 14:10:30 -0600539 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
541 builder.addCapability(spv::CapabilityDrawParameters);
542 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200543
John Kessenichda581a22015-10-14 14:10:30 -0600544 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
546 builder.addCapability(spv::CapabilityDrawParameters);
547 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200548
549 case glslang::EbvPrimitiveId:
550 if (glslangIntermediate->getStage() == EShLangFragment)
551 builder.addCapability(spv::CapabilityGeometry);
552 return spv::BuiltInPrimitiveId;
553
John Kessenich140f3df2015-06-26 16:58:36 -0600554 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600555 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
556 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
557 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
558 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
559 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
560 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
561 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600562 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
563 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
564 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
565 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
566 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
567 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
568 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
569 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupSize;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupLocalInvocationId;
580
Rex Xu574ab042016-04-14 16:53:07 +0800581 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800582 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
583 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
584 return spv::BuiltInSubgroupEqMaskKHR;
585
Rex Xu574ab042016-04-14 16:53:07 +0800586 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800587 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
588 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
589 return spv::BuiltInSubgroupGeMaskKHR;
590
Rex Xu574ab042016-04-14 16:53:07 +0800591 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800592 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
593 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
594 return spv::BuiltInSubgroupGtMaskKHR;
595
Rex Xu574ab042016-04-14 16:53:07 +0800596 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800597 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
598 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
599 return spv::BuiltInSubgroupLeMaskKHR;
600
Rex Xu574ab042016-04-14 16:53:07 +0800601 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800602 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
603 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
604 return spv::BuiltInSubgroupLtMaskKHR;
605
Rex Xu9d93a232016-05-05 12:30:44 +0800606#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800607 case glslang::EbvBaryCoordNoPersp:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordNoPerspAMD;
610
611 case glslang::EbvBaryCoordNoPerspCentroid:
612 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
613 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
614
615 case glslang::EbvBaryCoordNoPerspSample:
616 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
617 return spv::BuiltInBaryCoordNoPerspSampleAMD;
618
619 case glslang::EbvBaryCoordSmooth:
620 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
621 return spv::BuiltInBaryCoordSmoothAMD;
622
623 case glslang::EbvBaryCoordSmoothCentroid:
624 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
625 return spv::BuiltInBaryCoordSmoothCentroidAMD;
626
627 case glslang::EbvBaryCoordSmoothSample:
628 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
629 return spv::BuiltInBaryCoordSmoothSampleAMD;
630
631 case glslang::EbvBaryCoordPullModel:
632 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
633 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800634#endif
chaoc771d89f2017-01-13 01:10:53 -0800635
John Kessenich6c8aaac2017-02-27 01:20:51 -0700636 case glslang::EbvDeviceIndex:
637 builder.addExtension(spv::E_SPV_KHR_device_group);
638 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700639 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700640
641 case glslang::EbvViewIndex:
642 builder.addExtension(spv::E_SPV_KHR_multiview);
643 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700644 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700645
chaoc771d89f2017-01-13 01:10:53 -0800646#ifdef NV_EXTENSIONS
647 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800648 if (!memberDeclaration) {
649 builder.addExtension(spv::E_SPV_NV_viewport_array2);
650 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
651 }
chaoc771d89f2017-01-13 01:10:53 -0800652 return spv::BuiltInViewportMaskNV;
653 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800654 if (!memberDeclaration) {
655 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
656 builder.addCapability(spv::CapabilityShaderStereoViewNV);
657 }
chaoc771d89f2017-01-13 01:10:53 -0800658 return spv::BuiltInSecondaryPositionNV;
659 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800660 if (!memberDeclaration) {
661 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
662 builder.addCapability(spv::CapabilityShaderStereoViewNV);
663 }
chaoc771d89f2017-01-13 01:10:53 -0800664 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800665 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800666 if (!memberDeclaration) {
667 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
668 builder.addCapability(spv::CapabilityPerViewAttributesNV);
669 }
chaocdf3956c2017-02-14 14:52:34 -0800670 return spv::BuiltInPositionPerViewNV;
671 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800672 if (!memberDeclaration) {
673 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
674 builder.addCapability(spv::CapabilityPerViewAttributesNV);
675 }
chaocdf3956c2017-02-14 14:52:34 -0800676 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800677#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800678 default:
679 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600680 }
681}
682
Rex Xufc618912015-09-09 16:42:49 +0800683// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700684spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800685{
686 assert(type.getBasicType() == glslang::EbtSampler);
687
John Kessenich5d0fa972016-02-15 11:57:00 -0700688 // Check for capabilities
689 switch (type.getQualifier().layoutFormat) {
690 case glslang::ElfRg32f:
691 case glslang::ElfRg16f:
692 case glslang::ElfR11fG11fB10f:
693 case glslang::ElfR16f:
694 case glslang::ElfRgba16:
695 case glslang::ElfRgb10A2:
696 case glslang::ElfRg16:
697 case glslang::ElfRg8:
698 case glslang::ElfR16:
699 case glslang::ElfR8:
700 case glslang::ElfRgba16Snorm:
701 case glslang::ElfRg16Snorm:
702 case glslang::ElfRg8Snorm:
703 case glslang::ElfR16Snorm:
704 case glslang::ElfR8Snorm:
705
706 case glslang::ElfRg32i:
707 case glslang::ElfRg16i:
708 case glslang::ElfRg8i:
709 case glslang::ElfR16i:
710 case glslang::ElfR8i:
711
712 case glslang::ElfRgb10a2ui:
713 case glslang::ElfRg32ui:
714 case glslang::ElfRg16ui:
715 case glslang::ElfRg8ui:
716 case glslang::ElfR16ui:
717 case glslang::ElfR8ui:
718 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
719 break;
720
721 default:
722 break;
723 }
724
725 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800726 switch (type.getQualifier().layoutFormat) {
727 case glslang::ElfNone: return spv::ImageFormatUnknown;
728 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
729 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
730 case glslang::ElfR32f: return spv::ImageFormatR32f;
731 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
732 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
733 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
734 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
735 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
736 case glslang::ElfR16f: return spv::ImageFormatR16f;
737 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
738 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
739 case glslang::ElfRg16: return spv::ImageFormatRg16;
740 case glslang::ElfRg8: return spv::ImageFormatRg8;
741 case glslang::ElfR16: return spv::ImageFormatR16;
742 case glslang::ElfR8: return spv::ImageFormatR8;
743 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
744 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
745 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
746 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
747 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
748 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
749 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
750 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
751 case glslang::ElfR32i: return spv::ImageFormatR32i;
752 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
753 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
754 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
755 case glslang::ElfR16i: return spv::ImageFormatR16i;
756 case glslang::ElfR8i: return spv::ImageFormatR8i;
757 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
758 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
759 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
760 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
761 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
762 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
763 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
764 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
765 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
766 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600767 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800768 }
769}
770
steve-lunargf1709e72017-05-02 20:14:50 -0600771spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
772{
773 switch (loopControl) {
774 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
775 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
776 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
777 // TODO: DependencyInfinite
778 // TODO: DependencyLength
779 default: return spv::LoopControlMaskNone;
780 }
781}
782
qining25262b32016-05-06 17:25:16 -0400783// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700784// descriptor set.
785bool IsDescriptorResource(const glslang::TType& type)
786{
John Kessenichf7497e22016-03-08 21:36:22 -0700787 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700788 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700789 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700790
791 // non block...
792 // basically samplerXXX/subpass/sampler/texture are all included
793 // if they are the global-scope-class, not the function parameter
794 // (or local, if they ever exist) class.
795 if (type.getBasicType() == glslang::EbtSampler)
796 return type.getQualifier().isUniformOrBuffer();
797
798 // None of the above.
799 return false;
800}
801
John Kesseniche0b6cad2015-12-24 10:30:13 -0700802void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
803{
804 if (child.layoutMatrix == glslang::ElmNone)
805 child.layoutMatrix = parent.layoutMatrix;
806
807 if (parent.invariant)
808 child.invariant = true;
809 if (parent.nopersp)
810 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800811#ifdef AMD_EXTENSIONS
812 if (parent.explicitInterp)
813 child.explicitInterp = true;
814#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700815 if (parent.flat)
816 child.flat = true;
817 if (parent.centroid)
818 child.centroid = true;
819 if (parent.patch)
820 child.patch = true;
821 if (parent.sample)
822 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800823 if (parent.coherent)
824 child.coherent = true;
825 if (parent.volatil)
826 child.volatil = true;
827 if (parent.restrict)
828 child.restrict = true;
829 if (parent.readonly)
830 child.readonly = true;
831 if (parent.writeonly)
832 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833}
834
John Kessenichf2b7f332016-09-01 17:05:23 -0600835bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700836{
John Kessenich7b9fa252016-01-21 18:56:57 -0700837 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600838 // - struct members might inherit from a struct declaration
839 // (note that non-block structs don't explicitly inherit,
840 // only implicitly, meaning no decoration involved)
841 // - affect decorations on the struct members
842 // (note smooth does not, and expecting something like volatile
843 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700844 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600845 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846}
847
John Kessenich140f3df2015-06-26 16:58:36 -0600848//
849// Implement the TGlslangToSpvTraverser class.
850//
851
Lei Zhang17535f72016-05-04 15:55:59 -0400852TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600853 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
854 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400855 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700856 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600857 glslangIntermediate(glslangIntermediate)
858{
859 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
860
861 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700862 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600863 stdBuiltins = builder.import("GLSL.std.450");
864 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600865 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
866 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600867
868 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600869 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
870 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600871 builder.addSourceExtension(it->c_str());
872
873 // Add the top-level modes for this shader.
874
John Kessenich92187592016-02-01 13:45:25 -0700875 if (glslangIntermediate->getXfbMode()) {
876 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600877 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700878 }
John Kessenich140f3df2015-06-26 16:58:36 -0600879
880 unsigned int mode;
881 switch (glslangIntermediate->getStage()) {
882 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600883 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600884 break;
885
steve-lunarge7412492017-03-23 11:56:07 -0600886 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600887 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600888 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600889
steve-lunarge7412492017-03-23 11:56:07 -0600890 glslang::TLayoutGeometry primitive;
891
892 if (glslangIntermediate->getStage() == EShLangTessControl) {
893 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
894 primitive = glslangIntermediate->getOutputPrimitive();
895 } else {
896 primitive = glslangIntermediate->getInputPrimitive();
897 }
898
899 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700900 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
901 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
902 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600903 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600904 }
John Kessenich4016e382016-07-15 11:53:56 -0600905 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600906 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
907
John Kesseniche6903322015-10-13 16:29:02 -0600908 switch (glslangIntermediate->getVertexSpacing()) {
909 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
910 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
911 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600912 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600913 }
John Kessenich4016e382016-07-15 11:53:56 -0600914 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600915 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
916
917 switch (glslangIntermediate->getVertexOrder()) {
918 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
919 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600920 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600921 }
John Kessenich4016e382016-07-15 11:53:56 -0600922 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600923 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
924
925 if (glslangIntermediate->getPointMode())
926 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600927 break;
928
929 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600930 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600931 switch (glslangIntermediate->getInputPrimitive()) {
932 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
933 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
934 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700935 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600936 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600937 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600938 }
John Kessenich4016e382016-07-15 11:53:56 -0600939 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600940 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600941
John Kessenich140f3df2015-06-26 16:58:36 -0600942 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
943
944 switch (glslangIntermediate->getOutputPrimitive()) {
945 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
946 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
947 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600948 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600949 }
John Kessenich4016e382016-07-15 11:53:56 -0600950 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600951 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
953 break;
954
955 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 if (glslangIntermediate->getPixelCenterInteger())
958 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600959
John Kessenich140f3df2015-06-26 16:58:36 -0600960 if (glslangIntermediate->getOriginUpperLeft())
961 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600962 else
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600964
965 if (glslangIntermediate->getEarlyFragmentTests())
966 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
967
968 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600969 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
970 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600971 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600972 }
John Kessenich4016e382016-07-15 11:53:56 -0600973 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600974 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
975
976 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
977 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600978 break;
979
980 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600981 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600982 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
983 glslangIntermediate->getLocalSize(1),
984 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600985 break;
986
987 default:
988 break;
989 }
John Kessenich140f3df2015-06-26 16:58:36 -0600990}
991
John Kessenichfca82622016-11-26 13:23:20 -0700992// Finish creating SPV, after the traversal is complete.
993void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700994{
John Kessenich517fe7a2016-11-26 13:31:47 -0700995 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700996 builder.setBuildPoint(shaderEntry->getLastBlock());
997 builder.leaveFunction();
998 }
999
John Kessenich7ba63412015-12-20 17:37:07 -07001000 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001001 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1002 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001003
qiningda397332016-03-09 19:54:03 -05001004 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001005}
1006
John Kessenichfca82622016-11-26 13:23:20 -07001007// Write the SPV into 'out'.
1008void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001009{
John Kessenichfca82622016-11-26 13:23:20 -07001010 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001011}
1012
1013//
1014// Implement the traversal functions.
1015//
1016// Return true from interior nodes to have the external traversal
1017// continue on to children. Return false if children were
1018// already processed.
1019//
1020
1021//
qining25262b32016-05-06 17:25:16 -04001022// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001023// - uniform/input reads
1024// - output writes
1025// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1026// - something simple that degenerates into the last bullet
1027//
1028void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1029{
qining75d1d802016-04-06 14:42:01 -04001030 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1031 if (symbol->getType().getQualifier().isSpecConstant())
1032 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1033
John Kessenich140f3df2015-06-26 16:58:36 -06001034 // getSymbolId() will set up all the IO decorations on the first call.
1035 // Formal function parameters were mapped during makeFunctions().
1036 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001037
1038 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1039 if (builder.isPointer(id)) {
1040 spv::StorageClass sc = builder.getStorageClass(id);
1041 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1042 iOSet.insert(id);
1043 }
1044
1045 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001046 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001047 // Prepare to generate code for the access
1048
1049 // L-value chains will be computed left to right. We're on the symbol now,
1050 // which is the left-most part of the access chain, so now is "clear" time,
1051 // followed by setting the base.
1052 builder.clearAccessChain();
1053
1054 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001055 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001056 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001057 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001058 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001059 // These are also pure R-values.
1060 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001061 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001062 builder.setAccessChainRValue(id);
1063 else
1064 builder.setAccessChainLValue(id);
1065 }
1066}
1067
1068bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1069{
qining40887662016-04-03 22:20:42 -04001070 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1071 if (node->getType().getQualifier().isSpecConstant())
1072 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1073
John Kessenich140f3df2015-06-26 16:58:36 -06001074 // First, handle special cases
1075 switch (node->getOp()) {
1076 case glslang::EOpAssign:
1077 case glslang::EOpAddAssign:
1078 case glslang::EOpSubAssign:
1079 case glslang::EOpMulAssign:
1080 case glslang::EOpVectorTimesMatrixAssign:
1081 case glslang::EOpVectorTimesScalarAssign:
1082 case glslang::EOpMatrixTimesScalarAssign:
1083 case glslang::EOpMatrixTimesMatrixAssign:
1084 case glslang::EOpDivAssign:
1085 case glslang::EOpModAssign:
1086 case glslang::EOpAndAssign:
1087 case glslang::EOpInclusiveOrAssign:
1088 case glslang::EOpExclusiveOrAssign:
1089 case glslang::EOpLeftShiftAssign:
1090 case glslang::EOpRightShiftAssign:
1091 // A bin-op assign "a += b" means the same thing as "a = a + b"
1092 // where a is evaluated before b. For a simple assignment, GLSL
1093 // says to evaluate the left before the right. So, always, left
1094 // node then right node.
1095 {
1096 // get the left l-value, save it away
1097 builder.clearAccessChain();
1098 node->getLeft()->traverse(this);
1099 spv::Builder::AccessChain lValue = builder.getAccessChain();
1100
1101 // evaluate the right
1102 builder.clearAccessChain();
1103 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001104 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001105
1106 if (node->getOp() != glslang::EOpAssign) {
1107 // the left is also an r-value
1108 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001109 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001110
1111 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001112 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001113 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001114 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1115 node->getType().getBasicType());
1116
1117 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001118 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001119 }
1120
1121 // store the result
1122 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001123 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001124
1125 // assignments are expressions having an rValue after they are evaluated...
1126 builder.clearAccessChain();
1127 builder.setAccessChainRValue(rValue);
1128 }
1129 return false;
1130 case glslang::EOpIndexDirect:
1131 case glslang::EOpIndexDirectStruct:
1132 {
1133 // Get the left part of the access chain.
1134 node->getLeft()->traverse(this);
1135
1136 // Add the next element in the chain
1137
David Netoa901ffe2016-06-08 14:11:40 +01001138 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001139 if (! node->getLeft()->getType().isArray() &&
1140 node->getLeft()->getType().isVector() &&
1141 node->getOp() == glslang::EOpIndexDirect) {
1142 // This is essentially a hard-coded vector swizzle of size 1,
1143 // so short circuit the access-chain stuff with a swizzle.
1144 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001145 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001146 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001147 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001148 int spvIndex = glslangIndex;
1149 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1150 node->getOp() == glslang::EOpIndexDirectStruct)
1151 {
1152 // This may be, e.g., an anonymous block-member selection, which generally need
1153 // index remapping due to hidden members in anonymous blocks.
1154 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1155 assert(remapper.size() > 0);
1156 spvIndex = remapper[glslangIndex];
1157 }
John Kessenichebb50532016-05-16 19:22:05 -06001158
David Netoa901ffe2016-06-08 14:11:40 +01001159 // normal case for indexing array or structure or block
1160 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1161
1162 // Add capabilities here for accessing PointSize and clip/cull distance.
1163 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001164 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001165 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001166 }
1167 }
1168 return false;
1169 case glslang::EOpIndexIndirect:
1170 {
1171 // Structure or array or vector indirection.
1172 // Will use native SPIR-V access-chain for struct and array indirection;
1173 // matrices are arrays of vectors, so will also work for a matrix.
1174 // Will use the access chain's 'component' for variable index into a vector.
1175
1176 // This adapter is building access chains left to right.
1177 // Set up the access chain to the left.
1178 node->getLeft()->traverse(this);
1179
1180 // save it so that computing the right side doesn't trash it
1181 spv::Builder::AccessChain partial = builder.getAccessChain();
1182
1183 // compute the next index in the chain
1184 builder.clearAccessChain();
1185 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001186 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001187
1188 // restore the saved access chain
1189 builder.setAccessChain(partial);
1190
1191 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001192 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001193 else
John Kessenichfa668da2015-09-13 14:46:30 -06001194 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001195 }
1196 return false;
1197 case glslang::EOpVectorSwizzle:
1198 {
1199 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001200 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001201 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001202 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001203 }
1204 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001205 case glslang::EOpMatrixSwizzle:
1206 logger->missingFunctionality("matrix swizzle");
1207 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001208 case glslang::EOpLogicalOr:
1209 case glslang::EOpLogicalAnd:
1210 {
1211
1212 // These may require short circuiting, but can sometimes be done as straight
1213 // binary operations. The right operand must be short circuited if it has
1214 // side effects, and should probably be if it is complex.
1215 if (isTrivial(node->getRight()->getAsTyped()))
1216 break; // handle below as a normal binary operation
1217 // otherwise, we need to do dynamic short circuiting on the right operand
1218 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1219 builder.clearAccessChain();
1220 builder.setAccessChainRValue(result);
1221 }
1222 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001223 default:
1224 break;
1225 }
1226
1227 // Assume generic binary op...
1228
John Kessenich32cfd492016-02-02 12:37:46 -07001229 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001230 builder.clearAccessChain();
1231 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001232 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001233
John Kessenich32cfd492016-02-02 12:37:46 -07001234 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001235 builder.clearAccessChain();
1236 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001237 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001238
John Kessenich32cfd492016-02-02 12:37:46 -07001239 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001240 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001241 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001242 convertGlslangToSpvType(node->getType()), left, right,
1243 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001244
John Kessenich50e57562015-12-21 21:21:11 -07001245 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001246 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001247 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001248 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001249 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001250 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001251 return false;
1252 }
John Kessenich140f3df2015-06-26 16:58:36 -06001253}
1254
1255bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1256{
qining40887662016-04-03 22:20:42 -04001257 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1258 if (node->getType().getQualifier().isSpecConstant())
1259 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1260
John Kessenichfc51d282015-08-19 13:34:18 -06001261 spv::Id result = spv::NoResult;
1262
1263 // try texturing first
1264 result = createImageTextureFunctionCall(node);
1265 if (result != spv::NoResult) {
1266 builder.clearAccessChain();
1267 builder.setAccessChainRValue(result);
1268
1269 return false; // done with this node
1270 }
1271
1272 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001273
1274 if (node->getOp() == glslang::EOpArrayLength) {
1275 // Quite special; won't want to evaluate the operand.
1276
1277 // Normal .length() would have been constant folded by the front-end.
1278 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001279 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001280 assert(node->getOperand()->getType().isRuntimeSizedArray());
1281 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1282 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001283 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1284 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001285
1286 builder.clearAccessChain();
1287 builder.setAccessChainRValue(length);
1288
1289 return false;
1290 }
1291
John Kessenichfc51d282015-08-19 13:34:18 -06001292 // Start by evaluating the operand
1293
John Kessenich8c8505c2016-07-26 12:50:38 -06001294 // Does it need a swizzle inversion? If so, evaluation is inverted;
1295 // operate first on the swizzle base, then apply the swizzle.
1296 spv::Id invertedType = spv::NoType;
1297 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1298 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1299 invertedType = getInvertedSwizzleType(*node->getOperand());
1300
John Kessenich140f3df2015-06-26 16:58:36 -06001301 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001302 if (invertedType != spv::NoType)
1303 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1304 else
1305 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001306
Rex Xufc618912015-09-09 16:42:49 +08001307 spv::Id operand = spv::NoResult;
1308
1309 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1310 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001311 node->getOp() == glslang::EOpAtomicCounter ||
1312 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001313 operand = builder.accessChainGetLValue(); // Special case l-value operands
1314 else
John Kessenich32cfd492016-02-02 12:37:46 -07001315 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001316
John Kessenichf6640762016-08-01 19:44:00 -06001317 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001318 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001319
1320 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001321 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001322 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001323
1324 // if not, then possibly an operation
1325 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001326 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001327
1328 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001329 if (invertedType)
1330 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1331
John Kessenich140f3df2015-06-26 16:58:36 -06001332 builder.clearAccessChain();
1333 builder.setAccessChainRValue(result);
1334
1335 return false; // done with this node
1336 }
1337
1338 // it must be a special case, check...
1339 switch (node->getOp()) {
1340 case glslang::EOpPostIncrement:
1341 case glslang::EOpPostDecrement:
1342 case glslang::EOpPreIncrement:
1343 case glslang::EOpPreDecrement:
1344 {
1345 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001346 spv::Id one = 0;
1347 if (node->getBasicType() == glslang::EbtFloat)
1348 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001349 else if (node->getBasicType() == glslang::EbtDouble)
1350 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001351#ifdef AMD_EXTENSIONS
1352 else if (node->getBasicType() == glslang::EbtFloat16)
1353 one = builder.makeFloat16Constant(1.0F);
1354#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001355 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1356 one = builder.makeInt64Constant(1);
1357 else
1358 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001359 glslang::TOperator op;
1360 if (node->getOp() == glslang::EOpPreIncrement ||
1361 node->getOp() == glslang::EOpPostIncrement)
1362 op = glslang::EOpAdd;
1363 else
1364 op = glslang::EOpSub;
1365
John Kessenichf6640762016-08-01 19:44:00 -06001366 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001367 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001368 convertGlslangToSpvType(node->getType()), operand, one,
1369 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001370 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001371
1372 // The result of operation is always stored, but conditionally the
1373 // consumed result. The consumed result is always an r-value.
1374 builder.accessChainStore(result);
1375 builder.clearAccessChain();
1376 if (node->getOp() == glslang::EOpPreIncrement ||
1377 node->getOp() == glslang::EOpPreDecrement)
1378 builder.setAccessChainRValue(result);
1379 else
1380 builder.setAccessChainRValue(operand);
1381 }
1382
1383 return false;
1384
1385 case glslang::EOpEmitStreamVertex:
1386 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1387 return false;
1388 case glslang::EOpEndStreamPrimitive:
1389 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1390 return false;
1391
1392 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001393 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001394 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001395 }
John Kessenich140f3df2015-06-26 16:58:36 -06001396}
1397
1398bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1399{
qining27e04a02016-04-14 16:40:20 -04001400 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1401 if (node->getType().getQualifier().isSpecConstant())
1402 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1403
John Kessenichfc51d282015-08-19 13:34:18 -06001404 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001405 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1406 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001407
1408 // try texturing
1409 result = createImageTextureFunctionCall(node);
1410 if (result != spv::NoResult) {
1411 builder.clearAccessChain();
1412 builder.setAccessChainRValue(result);
1413
1414 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001415 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001416 // "imageStore" is a special case, which has no result
1417 return false;
1418 }
John Kessenichfc51d282015-08-19 13:34:18 -06001419
John Kessenich140f3df2015-06-26 16:58:36 -06001420 glslang::TOperator binOp = glslang::EOpNull;
1421 bool reduceComparison = true;
1422 bool isMatrix = false;
1423 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001424 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001425
1426 assert(node->getOp());
1427
John Kessenichf6640762016-08-01 19:44:00 -06001428 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001429
1430 switch (node->getOp()) {
1431 case glslang::EOpSequence:
1432 {
1433 if (preVisit)
1434 ++sequenceDepth;
1435 else
1436 --sequenceDepth;
1437
1438 if (sequenceDepth == 1) {
1439 // If this is the parent node of all the functions, we want to see them
1440 // early, so all call points have actual SPIR-V functions to reference.
1441 // In all cases, still let the traverser visit the children for us.
1442 makeFunctions(node->getAsAggregate()->getSequence());
1443
John Kessenich6fccb3c2016-09-19 16:01:41 -06001444 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001445 // anything else gets there, so visit out of order, doing them all now.
1446 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1447
John Kessenich6a60c2f2016-12-08 21:01:59 -07001448 // 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 -06001449 // so do them manually.
1450 visitFunctions(node->getAsAggregate()->getSequence());
1451
1452 return false;
1453 }
1454
1455 return true;
1456 }
1457 case glslang::EOpLinkerObjects:
1458 {
1459 if (visit == glslang::EvPreVisit)
1460 linkageOnly = true;
1461 else
1462 linkageOnly = false;
1463
1464 return true;
1465 }
1466 case glslang::EOpComma:
1467 {
1468 // processing from left to right naturally leaves the right-most
1469 // lying around in the access chain
1470 glslang::TIntermSequence& glslangOperands = node->getSequence();
1471 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1472 glslangOperands[i]->traverse(this);
1473
1474 return false;
1475 }
1476 case glslang::EOpFunction:
1477 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001478 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001479 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001480 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001481 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001482 } else {
1483 handleFunctionEntry(node);
1484 }
1485 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001486 if (inEntryPoint)
1487 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001488 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001489 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001490 }
1491
1492 return true;
1493 case glslang::EOpParameters:
1494 // Parameters will have been consumed by EOpFunction processing, but not
1495 // the body, so we still visited the function node's children, making this
1496 // child redundant.
1497 return false;
1498 case glslang::EOpFunctionCall:
1499 {
1500 if (node->isUserDefined())
1501 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001502 // 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 -07001503 if (result) {
1504 builder.clearAccessChain();
1505 builder.setAccessChainRValue(result);
1506 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001507 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001508
1509 return false;
1510 }
1511 case glslang::EOpConstructMat2x2:
1512 case glslang::EOpConstructMat2x3:
1513 case glslang::EOpConstructMat2x4:
1514 case glslang::EOpConstructMat3x2:
1515 case glslang::EOpConstructMat3x3:
1516 case glslang::EOpConstructMat3x4:
1517 case glslang::EOpConstructMat4x2:
1518 case glslang::EOpConstructMat4x3:
1519 case glslang::EOpConstructMat4x4:
1520 case glslang::EOpConstructDMat2x2:
1521 case glslang::EOpConstructDMat2x3:
1522 case glslang::EOpConstructDMat2x4:
1523 case glslang::EOpConstructDMat3x2:
1524 case glslang::EOpConstructDMat3x3:
1525 case glslang::EOpConstructDMat3x4:
1526 case glslang::EOpConstructDMat4x2:
1527 case glslang::EOpConstructDMat4x3:
1528 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001529#ifdef AMD_EXTENSIONS
1530 case glslang::EOpConstructF16Mat2x2:
1531 case glslang::EOpConstructF16Mat2x3:
1532 case glslang::EOpConstructF16Mat2x4:
1533 case glslang::EOpConstructF16Mat3x2:
1534 case glslang::EOpConstructF16Mat3x3:
1535 case glslang::EOpConstructF16Mat3x4:
1536 case glslang::EOpConstructF16Mat4x2:
1537 case glslang::EOpConstructF16Mat4x3:
1538 case glslang::EOpConstructF16Mat4x4:
1539#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001540 isMatrix = true;
1541 // fall through
1542 case glslang::EOpConstructFloat:
1543 case glslang::EOpConstructVec2:
1544 case glslang::EOpConstructVec3:
1545 case glslang::EOpConstructVec4:
1546 case glslang::EOpConstructDouble:
1547 case glslang::EOpConstructDVec2:
1548 case glslang::EOpConstructDVec3:
1549 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001550#ifdef AMD_EXTENSIONS
1551 case glslang::EOpConstructFloat16:
1552 case glslang::EOpConstructF16Vec2:
1553 case glslang::EOpConstructF16Vec3:
1554 case glslang::EOpConstructF16Vec4:
1555#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case glslang::EOpConstructBool:
1557 case glslang::EOpConstructBVec2:
1558 case glslang::EOpConstructBVec3:
1559 case glslang::EOpConstructBVec4:
1560 case glslang::EOpConstructInt:
1561 case glslang::EOpConstructIVec2:
1562 case glslang::EOpConstructIVec3:
1563 case glslang::EOpConstructIVec4:
1564 case glslang::EOpConstructUint:
1565 case glslang::EOpConstructUVec2:
1566 case glslang::EOpConstructUVec3:
1567 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001568 case glslang::EOpConstructInt64:
1569 case glslang::EOpConstructI64Vec2:
1570 case glslang::EOpConstructI64Vec3:
1571 case glslang::EOpConstructI64Vec4:
1572 case glslang::EOpConstructUint64:
1573 case glslang::EOpConstructU64Vec2:
1574 case glslang::EOpConstructU64Vec3:
1575 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001576 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001577 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001578 {
1579 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001580 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001581 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001582 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001583 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001584 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001585 std::vector<spv::Id> constituents;
1586 for (int c = 0; c < (int)arguments.size(); ++c)
1587 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001588 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001589 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001590 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001591 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001593
1594 builder.clearAccessChain();
1595 builder.setAccessChainRValue(constructed);
1596
1597 return false;
1598 }
1599
1600 // These six are component-wise compares with component-wise results.
1601 // Forward on to createBinaryOperation(), requesting a vector result.
1602 case glslang::EOpLessThan:
1603 case glslang::EOpGreaterThan:
1604 case glslang::EOpLessThanEqual:
1605 case glslang::EOpGreaterThanEqual:
1606 case glslang::EOpVectorEqual:
1607 case glslang::EOpVectorNotEqual:
1608 {
1609 // Map the operation to a binary
1610 binOp = node->getOp();
1611 reduceComparison = false;
1612 switch (node->getOp()) {
1613 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1614 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1615 default: binOp = node->getOp(); break;
1616 }
1617
1618 break;
1619 }
1620 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001621 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001622 binOp = glslang::EOpMul;
1623 break;
1624 case glslang::EOpOuterProduct:
1625 // two vectors multiplied to make a matrix
1626 binOp = glslang::EOpOuterProduct;
1627 break;
1628 case glslang::EOpDot:
1629 {
qining25262b32016-05-06 17:25:16 -04001630 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001631 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001632 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001633 binOp = glslang::EOpMul;
1634 break;
1635 }
1636 case glslang::EOpMod:
1637 // when an aggregate, this is the floating-point mod built-in function,
1638 // which can be emitted by the one in createBinaryOperation()
1639 binOp = glslang::EOpMod;
1640 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001641 case glslang::EOpEmitVertex:
1642 case glslang::EOpEndPrimitive:
1643 case glslang::EOpBarrier:
1644 case glslang::EOpMemoryBarrier:
1645 case glslang::EOpMemoryBarrierAtomicCounter:
1646 case glslang::EOpMemoryBarrierBuffer:
1647 case glslang::EOpMemoryBarrierImage:
1648 case glslang::EOpMemoryBarrierShared:
1649 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001650 case glslang::EOpAllMemoryBarrierWithGroupSync:
1651 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1652 case glslang::EOpWorkgroupMemoryBarrier:
1653 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001654 noReturnValue = true;
1655 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1656 break;
1657
John Kessenich426394d2015-07-23 10:22:48 -06001658 case glslang::EOpAtomicAdd:
1659 case glslang::EOpAtomicMin:
1660 case glslang::EOpAtomicMax:
1661 case glslang::EOpAtomicAnd:
1662 case glslang::EOpAtomicOr:
1663 case glslang::EOpAtomicXor:
1664 case glslang::EOpAtomicExchange:
1665 case glslang::EOpAtomicCompSwap:
1666 atomic = true;
1667 break;
1668
John Kessenich140f3df2015-06-26 16:58:36 -06001669 default:
1670 break;
1671 }
1672
1673 //
1674 // See if it maps to a regular operation.
1675 //
John Kessenich140f3df2015-06-26 16:58:36 -06001676 if (binOp != glslang::EOpNull) {
1677 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1678 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1679 assert(left && right);
1680
1681 builder.clearAccessChain();
1682 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001683 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 builder.clearAccessChain();
1686 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001687 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001688
qining25262b32016-05-06 17:25:16 -04001689 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001690 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001691 left->getType().getBasicType(), reduceComparison);
1692
1693 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001694 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001695 builder.clearAccessChain();
1696 builder.setAccessChainRValue(result);
1697
1698 return false;
1699 }
1700
John Kessenich426394d2015-07-23 10:22:48 -06001701 //
1702 // Create the list of operands.
1703 //
John Kessenich140f3df2015-06-26 16:58:36 -06001704 glslang::TIntermSequence& glslangOperands = node->getSequence();
1705 std::vector<spv::Id> operands;
1706 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001707 // special case l-value operands; there are just a few
1708 bool lvalue = false;
1709 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001710 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001711 case glslang::EOpModf:
1712 if (arg == 1)
1713 lvalue = true;
1714 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001715 case glslang::EOpInterpolateAtSample:
1716 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001717#ifdef AMD_EXTENSIONS
1718 case glslang::EOpInterpolateAtVertex:
1719#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001720 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001721 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001722
1723 // Does it need a swizzle inversion? If so, evaluation is inverted;
1724 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001725 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001726 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1727 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1728 }
Rex Xu7a26c172015-12-08 17:12:09 +08001729 break;
Rex Xud4782c12015-09-06 16:30:11 +08001730 case glslang::EOpAtomicAdd:
1731 case glslang::EOpAtomicMin:
1732 case glslang::EOpAtomicMax:
1733 case glslang::EOpAtomicAnd:
1734 case glslang::EOpAtomicOr:
1735 case glslang::EOpAtomicXor:
1736 case glslang::EOpAtomicExchange:
1737 case glslang::EOpAtomicCompSwap:
1738 if (arg == 0)
1739 lvalue = true;
1740 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001741 case glslang::EOpAddCarry:
1742 case glslang::EOpSubBorrow:
1743 if (arg == 2)
1744 lvalue = true;
1745 break;
1746 case glslang::EOpUMulExtended:
1747 case glslang::EOpIMulExtended:
1748 if (arg >= 2)
1749 lvalue = true;
1750 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001751 default:
1752 break;
1753 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001754 builder.clearAccessChain();
1755 if (invertedType != spv::NoType && arg == 0)
1756 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1757 else
1758 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001759 if (lvalue)
1760 operands.push_back(builder.accessChainGetLValue());
1761 else
John Kessenich32cfd492016-02-02 12:37:46 -07001762 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
John Kessenich426394d2015-07-23 10:22:48 -06001764
1765 if (atomic) {
1766 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001767 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001768 } else {
1769 // Pass through to generic operations.
1770 switch (glslangOperands.size()) {
1771 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001772 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001773 break;
1774 case 1:
qining25262b32016-05-06 17:25:16 -04001775 result = createUnaryOperation(
1776 node->getOp(), precision,
1777 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001778 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001779 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001780 break;
1781 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001782 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001783 break;
1784 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001785 if (invertedType)
1786 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001787 }
1788
1789 if (noReturnValue)
1790 return false;
1791
1792 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001793 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001794 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001795 } else {
1796 builder.clearAccessChain();
1797 builder.setAccessChainRValue(result);
1798 return false;
1799 }
1800}
1801
John Kessenich433e9ff2017-01-26 20:31:11 -07001802// This path handles both if-then-else and ?:
1803// The if-then-else has a node type of void, while
1804// ?: has either a void or a non-void node type
1805//
1806// Leaving the result, when not void:
1807// GLSL only has r-values as the result of a :?, but
1808// if we have an l-value, that can be more efficient if it will
1809// become the base of a complex r-value expression, because the
1810// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001811bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1812{
John Kessenich433e9ff2017-01-26 20:31:11 -07001813 // See if it simple and safe to generate OpSelect instead of using control flow.
1814 // Crucially, side effects must be avoided, and there are performance trade-offs.
1815 // Return true if good idea (and safe) for OpSelect, false otherwise.
1816 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001817 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1818 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001819 return false;
1820
1821 if (node->getTrueBlock() == nullptr ||
1822 node->getFalseBlock() == nullptr)
1823 return false;
1824
1825 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1826 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1827
1828 // return true if a single operand to ? : is okay for OpSelect
1829 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001830 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001831 };
1832
1833 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1834 operandOkay(node->getFalseBlock()->getAsTyped());
1835 };
1836
1837 // Emit OpSelect for this selection.
1838 const auto handleAsOpSelect = [&]() {
1839 node->getCondition()->traverse(this);
1840 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1841 node->getTrueBlock()->traverse(this);
1842 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1843 node->getFalseBlock()->traverse(this);
1844 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1845
John Kesseniche434ad92017-03-30 10:09:28 -06001846 // smear condition to vector, if necessary (AST is always scalar)
1847 if (builder.isVector(trueValue))
1848 condition = builder.smearScalar(spv::NoPrecision, condition,
1849 builder.makeVectorType(builder.makeBoolType(),
1850 builder.getNumComponents(trueValue)));
1851
1852 spv::Id select = builder.createTriOp(spv::OpSelect,
1853 convertGlslangToSpvType(node->getType()), condition,
1854 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001855 builder.clearAccessChain();
1856 builder.setAccessChainRValue(select);
1857 };
1858
1859 // Try for OpSelect
1860
1861 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001862 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1863 if (node->getType().getQualifier().isSpecConstant())
1864 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1865
John Kessenich433e9ff2017-01-26 20:31:11 -07001866 handleAsOpSelect();
1867 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001868 }
1869
John Kessenich433e9ff2017-01-26 20:31:11 -07001870 // Instead, emit control flow...
1871
1872 // Don't handle results as temporaries, because there will be two names
1873 // and better to leave SSA to later passes.
1874 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1875 ? spv::NoResult
1876 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1877
John Kessenich140f3df2015-06-26 16:58:36 -06001878 // emit the condition before doing anything with selection
1879 node->getCondition()->traverse(this);
1880
1881 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001882 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001883
John Kessenich433e9ff2017-01-26 20:31:11 -07001884 // emit the "then" statement
1885 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001886 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001887 if (result != spv::NoResult)
1888 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001889 }
1890
John Kessenich433e9ff2017-01-26 20:31:11 -07001891 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001892 ifBuilder.makeBeginElse();
1893 // emit the "else" statement
1894 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001895 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001896 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001897 }
1898
John Kessenich433e9ff2017-01-26 20:31:11 -07001899 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001900 ifBuilder.makeEndIf();
1901
John Kessenich433e9ff2017-01-26 20:31:11 -07001902 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001903 // GLSL only has r-values as the result of a :?, but
1904 // if we have an l-value, that can be more efficient if it will
1905 // become the base of a complex r-value expression, because the
1906 // next layer copies r-values into memory to use the access-chain mechanism
1907 builder.clearAccessChain();
1908 builder.setAccessChainLValue(result);
1909 }
1910
1911 return false;
1912}
1913
1914bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1915{
1916 // emit and get the condition before doing anything with switch
1917 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001918 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001919
1920 // browse the children to sort out code segments
1921 int defaultSegment = -1;
1922 std::vector<TIntermNode*> codeSegments;
1923 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1924 std::vector<int> caseValues;
1925 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1926 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1927 TIntermNode* child = *c;
1928 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001929 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001930 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001931 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001932 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1933 } else
1934 codeSegments.push_back(child);
1935 }
1936
qining25262b32016-05-06 17:25:16 -04001937 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001938 // statements between the last case and the end of the switch statement
1939 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1940 (int)codeSegments.size() == defaultSegment)
1941 codeSegments.push_back(nullptr);
1942
1943 // make the switch statement
1944 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001945 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001946
1947 // emit all the code in the segments
1948 breakForLoop.push(false);
1949 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1950 builder.nextSwitchSegment(segmentBlocks, s);
1951 if (codeSegments[s])
1952 codeSegments[s]->traverse(this);
1953 else
1954 builder.addSwitchBreak();
1955 }
1956 breakForLoop.pop();
1957
1958 builder.endSwitch(segmentBlocks);
1959
1960 return false;
1961}
1962
1963void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1964{
1965 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001966 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001967
1968 builder.clearAccessChain();
1969 builder.setAccessChainRValue(constant);
1970}
1971
1972bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1973{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001974 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001975 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001976
1977 // Loop control:
1978 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
1979
1980 // TODO: dependency length
1981
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001982 // Spec requires back edges to target header blocks, and every header block
1983 // must dominate its merge block. Make a header block first to ensure these
1984 // conditions are met. By definition, it will contain OpLoopMerge, followed
1985 // by a block-ending branch. But we don't want to put any other body/test
1986 // instructions in it, since the body/test may have arbitrary instructions,
1987 // including merges of its own.
1988 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001989 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001990 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001991 spv::Block& test = builder.makeNewBlock();
1992 builder.createBranch(&test);
1993
1994 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001995 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001996 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001997 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001998 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1999
2000 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002001 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002002 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002003 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002004 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002005 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002006
2007 builder.setBuildPoint(&blocks.continue_target);
2008 if (node->getTerminal())
2009 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002010 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002011 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002012 builder.createBranch(&blocks.body);
2013
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002014 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002015 builder.setBuildPoint(&blocks.body);
2016 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002017 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002018 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002019 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002020
2021 builder.setBuildPoint(&blocks.continue_target);
2022 if (node->getTerminal())
2023 node->getTerminal()->traverse(this);
2024 if (node->getTest()) {
2025 node->getTest()->traverse(this);
2026 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002027 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002028 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002029 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002030 // TODO: unless there was a break/return/discard instruction
2031 // somewhere in the body, this is an infinite loop, so we should
2032 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002033 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002034 }
John Kessenich140f3df2015-06-26 16:58:36 -06002035 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002036 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002037 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002038 return false;
2039}
2040
2041bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2042{
2043 if (node->getExpression())
2044 node->getExpression()->traverse(this);
2045
2046 switch (node->getFlowOp()) {
2047 case glslang::EOpKill:
2048 builder.makeDiscard();
2049 break;
2050 case glslang::EOpBreak:
2051 if (breakForLoop.top())
2052 builder.createLoopExit();
2053 else
2054 builder.addSwitchBreak();
2055 break;
2056 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002057 builder.createLoopContinue();
2058 break;
2059 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002060 if (node->getExpression()) {
2061 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2062 spv::Id returnId = accessChainLoad(glslangReturnType);
2063 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2064 builder.clearAccessChain();
2065 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2066 builder.setAccessChainLValue(copyId);
2067 multiTypeStore(glslangReturnType, returnId);
2068 returnId = builder.createLoad(copyId);
2069 }
2070 builder.makeReturn(false, returnId);
2071 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002072 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002073
2074 builder.clearAccessChain();
2075 break;
2076
2077 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002078 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 break;
2080 }
2081
2082 return false;
2083}
2084
2085spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2086{
qining25262b32016-05-06 17:25:16 -04002087 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002088 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002089 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002090 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002091 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002092 }
2093
2094 // Now, handle actual variables
John Kessenich67027182017-04-19 18:34:49 -06002095 spv::StorageClass storageClass = TranslateStorageClass(node->getType(), glslangIntermediate->usingStorageBuffer());
John Kessenich140f3df2015-06-26 16:58:36 -06002096 spv::Id spvType = convertGlslangToSpvType(node->getType());
2097
Rex Xuf89ad982017-04-07 23:22:33 +08002098#ifdef AMD_EXTENSIONS
2099 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2100 if (contains16BitType) {
2101 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2102 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2103 builder.addCapability(spv::CapabilityStorageInputOutput16);
2104 } else if (storageClass == spv::StorageClassPushConstant) {
2105 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2106 builder.addCapability(spv::CapabilityStoragePushConstant16);
2107 } else if (storageClass == spv::StorageClassUniform) {
2108 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2109 builder.addCapability(spv::CapabilityStorageUniform16);
2110 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2111 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2112 }
2113 }
2114#endif
2115
John Kessenich140f3df2015-06-26 16:58:36 -06002116 const char* name = node->getName().c_str();
2117 if (glslang::IsAnonymous(name))
2118 name = "";
2119
2120 return builder.createVariable(storageClass, spvType, name);
2121}
2122
2123// Return type Id of the sampled type.
2124spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2125{
2126 switch (sampler.type) {
2127 case glslang::EbtFloat: return builder.makeFloatType(32);
2128 case glslang::EbtInt: return builder.makeIntType(32);
2129 case glslang::EbtUint: return builder.makeUintType(32);
2130 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002131 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002132 return builder.makeFloatType(32);
2133 }
2134}
2135
John Kessenich8c8505c2016-07-26 12:50:38 -06002136// If node is a swizzle operation, return the type that should be used if
2137// the swizzle base is first consumed by another operation, before the swizzle
2138// is applied.
2139spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2140{
John Kessenichecba76f2017-01-06 00:34:48 -07002141 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002142 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2143 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2144 else
2145 return spv::NoType;
2146}
2147
2148// When inverting a swizzle with a parent op, this function
2149// will apply the swizzle operation to a completed parent operation.
2150spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2151{
2152 std::vector<unsigned> swizzle;
2153 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2154 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2155}
2156
John Kessenich8c8505c2016-07-26 12:50:38 -06002157// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2158void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2159{
2160 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2161 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2162 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2163}
2164
John Kessenich3ac051e2015-12-20 11:29:16 -07002165// Convert from a glslang type to an SPV type, by calling into a
2166// recursive version of this function. This establishes the inherited
2167// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002168spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2169{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002170 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002171}
2172
2173// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002174// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002175// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002176spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002177{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002178 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002179
2180 switch (type.getBasicType()) {
2181 case glslang::EbtVoid:
2182 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002183 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002184 break;
2185 case glslang::EbtFloat:
2186 spvType = builder.makeFloatType(32);
2187 break;
2188 case glslang::EbtDouble:
2189 spvType = builder.makeFloatType(64);
2190 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002191#ifdef AMD_EXTENSIONS
2192 case glslang::EbtFloat16:
2193 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002194 spvType = builder.makeFloatType(16);
2195 break;
2196#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002197 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002198 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2199 // a 32-bit int where non-0 means true.
2200 if (explicitLayout != glslang::ElpNone)
2201 spvType = builder.makeUintType(32);
2202 else
2203 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002204 break;
2205 case glslang::EbtInt:
2206 spvType = builder.makeIntType(32);
2207 break;
2208 case glslang::EbtUint:
2209 spvType = builder.makeUintType(32);
2210 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002211 case glslang::EbtInt64:
2212 builder.addCapability(spv::CapabilityInt64);
2213 spvType = builder.makeIntType(64);
2214 break;
2215 case glslang::EbtUint64:
2216 builder.addCapability(spv::CapabilityInt64);
2217 spvType = builder.makeUintType(64);
2218 break;
John Kessenich426394d2015-07-23 10:22:48 -06002219 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002220 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002221 spvType = builder.makeUintType(32);
2222 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002223 case glslang::EbtSampler:
2224 {
2225 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002226 if (sampler.sampler) {
2227 // pure sampler
2228 spvType = builder.makeSamplerType();
2229 } else {
2230 // an image is present, make its type
2231 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2232 sampler.image ? 2 : 1, TranslateImageFormat(type));
2233 if (sampler.combined) {
2234 // already has both image and sampler, make the combined type
2235 spvType = builder.makeSampledImageType(spvType);
2236 }
John Kessenich55e7d112015-11-15 21:33:39 -07002237 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002238 }
John Kessenich140f3df2015-06-26 16:58:36 -06002239 break;
2240 case glslang::EbtStruct:
2241 case glslang::EbtBlock:
2242 {
2243 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002244 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002245
2246 // Try to share structs for different layouts, but not yet for other
2247 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002248 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002249 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002250 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002251 break;
2252
2253 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002254 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002255 memberRemapper[glslangMembers].resize(glslangMembers->size());
2256 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002257 }
2258 break;
2259 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002260 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002261 break;
2262 }
2263
2264 if (type.isMatrix())
2265 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2266 else {
2267 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2268 if (type.getVectorSize() > 1)
2269 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2270 }
2271
2272 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002273 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2274
John Kessenichc9a80832015-09-12 12:17:44 -06002275 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002276 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002277 // We need to decorate array strides for types needing explicit layout, except blocks.
2278 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002279 // Use a dummy glslang type for querying internal strides of
2280 // arrays of arrays, but using just a one-dimensional array.
2281 glslang::TType simpleArrayType(type, 0); // deference type of the array
2282 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2283 simpleArrayType.getArraySizes().dereference();
2284
2285 // Will compute the higher-order strides here, rather than making a whole
2286 // pile of types and doing repetitive recursion on their contents.
2287 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2288 }
John Kessenichf8842e52016-01-04 19:22:56 -07002289
2290 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002291 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002292 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002293 if (stride > 0)
2294 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002295 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002296 }
2297 } else {
2298 // single-dimensional array, and don't yet have stride
2299
John Kessenichf8842e52016-01-04 19:22:56 -07002300 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002301 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2302 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002303 }
John Kessenich31ed4832015-09-09 17:51:38 -06002304
John Kessenichc9a80832015-09-12 12:17:44 -06002305 // Do the outer dimension, which might not be known for a runtime-sized array
2306 if (type.isRuntimeSizedArray()) {
2307 spvType = builder.makeRuntimeArray(spvType);
2308 } else {
2309 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002310 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002311 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002312 if (stride > 0)
2313 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002314 }
2315
2316 return spvType;
2317}
2318
John Kessenich0e737842017-03-24 18:38:16 -06002319// TODO: this functionality should exist at a higher level, in creating the AST
2320//
2321// Identify interface members that don't have their required extension turned on.
2322//
2323bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2324{
2325 auto& extensions = glslangIntermediate->getRequestedExtensions();
2326
Rex Xubcf291a2017-03-29 23:01:36 +08002327 if (member.getFieldName() == "gl_ViewportMask" &&
2328 extensions.find("GL_NV_viewport_array2") == extensions.end())
2329 return true;
2330 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2331 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2332 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002333 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2334 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2335 return true;
2336 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2337 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2338 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002339 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2340 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2341 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002342
2343 return false;
2344};
2345
John Kessenich6090df02016-06-30 21:18:02 -06002346// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2347// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2348// Mutually recursive with convertGlslangToSpvType().
2349spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2350 const glslang::TTypeList* glslangMembers,
2351 glslang::TLayoutPacking explicitLayout,
2352 const glslang::TQualifier& qualifier)
2353{
2354 // Create a vector of struct types for SPIR-V to consume
2355 std::vector<spv::Id> spvMembers;
2356 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2357 int locationOffset = 0; // for use across struct members, when they are called recursively
2358 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2359 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2360 if (glslangMember.hiddenMember()) {
2361 ++memberDelta;
2362 if (type.getBasicType() == glslang::EbtBlock)
2363 memberRemapper[glslangMembers][i] = -1;
2364 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002365 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002366 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002367 if (filterMember(glslangMember))
2368 continue;
2369 }
John Kessenich6090df02016-06-30 21:18:02 -06002370 // modify just this child's view of the qualifier
2371 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2372 InheritQualifiers(memberQualifier, qualifier);
2373
2374 // manually inherit location; it's more complex
2375 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2376 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2377 if (qualifier.hasLocation())
2378 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2379
2380 // recurse
2381 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2382 }
2383 }
2384
2385 // Make the SPIR-V type
2386 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002387 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002388 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2389
2390 // Decorate it
2391 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2392
2393 return spvType;
2394}
2395
2396void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2397 const glslang::TTypeList* glslangMembers,
2398 glslang::TLayoutPacking explicitLayout,
2399 const glslang::TQualifier& qualifier,
2400 spv::Id spvType)
2401{
2402 // Name and decorate the non-hidden members
2403 int offset = -1;
2404 int locationOffset = 0; // for use within the members of this struct
2405 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2406 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2407 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002408 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002409 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002410 if (filterMember(glslangMember))
2411 continue;
2412 }
John Kessenich6090df02016-06-30 21:18:02 -06002413
2414 // modify just this child's view of the qualifier
2415 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2416 InheritQualifiers(memberQualifier, qualifier);
2417
2418 // using -1 above to indicate a hidden member
2419 if (member >= 0) {
2420 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2421 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2422 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2423 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002424 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2425 type.getQualifier().storage == glslang::EvqVaryingOut) {
2426 if (type.getBasicType() == glslang::EbtBlock ||
2427 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002428 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2429 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2430 }
2431 }
2432 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2433
2434 if (qualifier.storage == glslang::EvqBuffer) {
2435 std::vector<spv::Decoration> memory;
2436 TranslateMemoryDecoration(memberQualifier, memory);
2437 for (unsigned int i = 0; i < memory.size(); ++i)
2438 addMemberDecoration(spvType, member, memory[i]);
2439 }
2440
John Kessenich2f47bc92016-06-30 21:47:35 -06002441 // Compute location decoration; tricky based on whether inheritance is at play and
2442 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002443 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2444 // probably move to the linker stage of the front end proper, and just have the
2445 // answer sitting already distributed throughout the individual member locations.
2446 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002447 // Ignore member locations if the container is an array, as that's
2448 // ill-specified and decisions have been made to not allow this anyway.
2449 // The object itself must have a location, and that comes out from decorating the object,
2450 // not the type (this code decorates types).
2451 if (! type.isArray()) {
2452 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2453 // struct members should not have explicit locations
2454 assert(type.getBasicType() != glslang::EbtStruct);
2455 location = memberQualifier.layoutLocation;
2456 } else if (type.getBasicType() != glslang::EbtBlock) {
2457 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2458 // The members, and their nested types, must not themselves have Location decorations.
2459 } else if (qualifier.hasLocation()) // inheritance
2460 location = qualifier.layoutLocation + locationOffset;
2461 }
John Kessenich6090df02016-06-30 21:18:02 -06002462 if (location >= 0)
2463 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2464
John Kessenich2f47bc92016-06-30 21:47:35 -06002465 if (qualifier.hasLocation()) // track for upcoming inheritance
2466 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2467
John Kessenich6090df02016-06-30 21:18:02 -06002468 // component, XFB, others
2469 if (glslangMember.getQualifier().hasComponent())
2470 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2471 if (glslangMember.getQualifier().hasXfbOffset())
2472 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2473 else if (explicitLayout != glslang::ElpNone) {
2474 // figure out what to do with offset, which is accumulating
2475 int nextOffset;
2476 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2477 if (offset >= 0)
2478 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2479 offset = nextOffset;
2480 }
2481
2482 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2483 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2484
2485 // built-in variable decorations
2486 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002487 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002488 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002489
2490#ifdef NV_EXTENSIONS
2491 if (builtIn == spv::BuiltInLayer) {
2492 // SPV_NV_viewport_array2 extension
2493 if (glslangMember.getQualifier().layoutViewportRelative){
2494 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2495 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2496 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2497 }
2498 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2499 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2500 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2501 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2502 }
2503 }
chaocdf3956c2017-02-14 14:52:34 -08002504 if (glslangMember.getQualifier().layoutPassthrough) {
2505 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2506 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2507 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2508 }
chaoc771d89f2017-01-13 01:10:53 -08002509#endif
John Kessenich6090df02016-06-30 21:18:02 -06002510 }
2511 }
2512
2513 // Decorate the structure
2514 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002515 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002516 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2517 builder.addCapability(spv::CapabilityGeometryStreams);
2518 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2519 }
2520 if (glslangIntermediate->getXfbMode()) {
2521 builder.addCapability(spv::CapabilityTransformFeedback);
2522 if (type.getQualifier().hasXfbStride())
2523 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2524 if (type.getQualifier().hasXfbBuffer())
2525 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2526 }
2527}
2528
John Kessenich6c292d32016-02-15 20:58:50 -07002529// Turn the expression forming the array size into an id.
2530// This is not quite trivial, because of specialization constants.
2531// Sometimes, a raw constant is turned into an Id, and sometimes
2532// a specialization constant expression is.
2533spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2534{
2535 // First, see if this is sized with a node, meaning a specialization constant:
2536 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2537 if (specNode != nullptr) {
2538 builder.clearAccessChain();
2539 specNode->traverse(this);
2540 return accessChainLoad(specNode->getAsTyped()->getType());
2541 }
qining25262b32016-05-06 17:25:16 -04002542
John Kessenich6c292d32016-02-15 20:58:50 -07002543 // Otherwise, need a compile-time (front end) size, get it:
2544 int size = arraySizes.getDimSize(dim);
2545 assert(size > 0);
2546 return builder.makeUintConstant(size);
2547}
2548
John Kessenich103bef92016-02-08 21:38:15 -07002549// Wrap the builder's accessChainLoad to:
2550// - localize handling of RelaxedPrecision
2551// - use the SPIR-V inferred type instead of another conversion of the glslang type
2552// (avoids unnecessary work and possible type punning for structures)
2553// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002554spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2555{
John Kessenich103bef92016-02-08 21:38:15 -07002556 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2557 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2558
2559 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002560 if (type.getBasicType() == glslang::EbtBool) {
2561 if (builder.isScalarType(nominalTypeId)) {
2562 // Conversion for bool
2563 spv::Id boolType = builder.makeBoolType();
2564 if (nominalTypeId != boolType)
2565 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2566 } else if (builder.isVectorType(nominalTypeId)) {
2567 // Conversion for bvec
2568 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2569 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2570 if (nominalTypeId != bvecType)
2571 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2572 }
2573 }
John Kessenich103bef92016-02-08 21:38:15 -07002574
2575 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002576}
2577
Rex Xu27253232016-02-23 17:51:09 +08002578// Wrap the builder's accessChainStore to:
2579// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002580//
2581// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002582void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2583{
2584 // Need to convert to abstract types when necessary
2585 if (type.getBasicType() == glslang::EbtBool) {
2586 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2587
2588 if (builder.isScalarType(nominalTypeId)) {
2589 // Conversion for bool
2590 spv::Id boolType = builder.makeBoolType();
2591 if (nominalTypeId != boolType) {
2592 spv::Id zero = builder.makeUintConstant(0);
2593 spv::Id one = builder.makeUintConstant(1);
2594 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2595 }
2596 } else if (builder.isVectorType(nominalTypeId)) {
2597 // Conversion for bvec
2598 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2599 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2600 if (nominalTypeId != bvecType) {
2601 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2602 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2603 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2604 }
2605 }
2606 }
2607
2608 builder.accessChainStore(rvalue);
2609}
2610
John Kessenich4bf71552016-09-02 11:20:21 -06002611// For storing when types match at the glslang level, but not might match at the
2612// SPIR-V level.
2613//
2614// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002615// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002616// as in a member-decorated way.
2617//
2618// NOTE: This function can handle any store request; if it's not special it
2619// simplifies to a simple OpStore.
2620//
2621// Implicitly uses the existing builder.accessChain as the storage target.
2622void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2623{
John Kessenichb3e24e42016-09-11 12:33:43 -06002624 // we only do the complex path here if it's an aggregate
2625 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002626 accessChainStore(type, rValue);
2627 return;
2628 }
2629
John Kessenichb3e24e42016-09-11 12:33:43 -06002630 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002631 spv::Id rType = builder.getTypeId(rValue);
2632 spv::Id lValue = builder.accessChainGetLValue();
2633 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2634 if (lType == rType) {
2635 accessChainStore(type, rValue);
2636 return;
2637 }
2638
John Kessenichb3e24e42016-09-11 12:33:43 -06002639 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002640 // where the two types were the same type in GLSL. This requires member
2641 // by member copy, recursively.
2642
John Kessenichb3e24e42016-09-11 12:33:43 -06002643 // If an array, copy element by element.
2644 if (type.isArray()) {
2645 glslang::TType glslangElementType(type, 0);
2646 spv::Id elementRType = builder.getContainedTypeId(rType);
2647 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2648 // get the source member
2649 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002650
John Kessenichb3e24e42016-09-11 12:33:43 -06002651 // set up the target storage
2652 builder.clearAccessChain();
2653 builder.setAccessChainLValue(lValue);
2654 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002655
John Kessenichb3e24e42016-09-11 12:33:43 -06002656 // store the member
2657 multiTypeStore(glslangElementType, elementRValue);
2658 }
2659 } else {
2660 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002661
John Kessenichb3e24e42016-09-11 12:33:43 -06002662 // loop over structure members
2663 const glslang::TTypeList& members = *type.getStruct();
2664 for (int m = 0; m < (int)members.size(); ++m) {
2665 const glslang::TType& glslangMemberType = *members[m].type;
2666
2667 // get the source member
2668 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2669 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2670
2671 // set up the target storage
2672 builder.clearAccessChain();
2673 builder.setAccessChainLValue(lValue);
2674 builder.accessChainPush(builder.makeIntConstant(m));
2675
2676 // store the member
2677 multiTypeStore(glslangMemberType, memberRValue);
2678 }
John Kessenich4bf71552016-09-02 11:20:21 -06002679 }
2680}
2681
John Kessenichf85e8062015-12-19 13:57:10 -07002682// Decide whether or not this type should be
2683// decorated with offsets and strides, and if so
2684// whether std140 or std430 rules should be applied.
2685glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002686{
John Kessenichf85e8062015-12-19 13:57:10 -07002687 // has to be a block
2688 if (type.getBasicType() != glslang::EbtBlock)
2689 return glslang::ElpNone;
2690
2691 // has to be a uniform or buffer block
2692 if (type.getQualifier().storage != glslang::EvqUniform &&
2693 type.getQualifier().storage != glslang::EvqBuffer)
2694 return glslang::ElpNone;
2695
2696 // return the layout to use
2697 switch (type.getQualifier().layoutPacking) {
2698 case glslang::ElpStd140:
2699 case glslang::ElpStd430:
2700 return type.getQualifier().layoutPacking;
2701 default:
2702 return glslang::ElpNone;
2703 }
John Kessenich31ed4832015-09-09 17:51:38 -06002704}
2705
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002706// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002707int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002708{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002709 int size;
John Kessenich49987892015-12-29 17:11:44 -07002710 int stride;
2711 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002712
2713 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002714}
2715
John Kessenich49987892015-12-29 17:11:44 -07002716// 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 -07002717// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002718int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002719{
John Kessenich49987892015-12-29 17:11:44 -07002720 glslang::TType elementType;
2721 elementType.shallowCopy(matrixType);
2722 elementType.clearArraySizes();
2723
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002724 int size;
John Kessenich49987892015-12-29 17:11:44 -07002725 int stride;
2726 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2727
2728 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002729}
2730
John Kessenich5e4b1242015-08-06 22:53:06 -06002731// Given a member type of a struct, realign the current offset for it, and compute
2732// the next (not yet aligned) offset for the next member, which will get aligned
2733// on the next call.
2734// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2735// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2736// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002737void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002738 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002739{
2740 // this will get a positive value when deemed necessary
2741 nextOffset = -1;
2742
John Kessenich5e4b1242015-08-06 22:53:06 -06002743 // override anything in currentOffset with user-set offset
2744 if (memberType.getQualifier().hasOffset())
2745 currentOffset = memberType.getQualifier().layoutOffset;
2746
2747 // It could be that current linker usage in glslang updated all the layoutOffset,
2748 // in which case the following code does not matter. But, that's not quite right
2749 // once cross-compilation unit GLSL validation is done, as the original user
2750 // settings are needed in layoutOffset, and then the following will come into play.
2751
John Kessenichf85e8062015-12-19 13:57:10 -07002752 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002753 if (! memberType.getQualifier().hasOffset())
2754 currentOffset = -1;
2755
2756 return;
2757 }
2758
John Kessenichf85e8062015-12-19 13:57:10 -07002759 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002760 if (currentOffset < 0)
2761 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002762
John Kessenich5e4b1242015-08-06 22:53:06 -06002763 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2764 // but possibly not yet correctly aligned.
2765
2766 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002767 int dummyStride;
2768 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002769
2770 // Adjust alignment for HLSL rules
2771 if (glslangIntermediate->usingHlslOFfsets() &&
2772 ! memberType.isArray() && memberType.isVector()) {
2773 int dummySize;
2774 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2775 if (componentAlignment <= 4)
2776 memberAlignment = componentAlignment;
2777 }
2778
2779 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002780 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002781
2782 // Bump up to vec4 if there is a bad straddle
2783 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2784 glslang::RoundToPow2(currentOffset, 16);
2785
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 nextOffset = currentOffset + memberSize;
2787}
2788
David Netoa901ffe2016-06-08 14:11:40 +01002789void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002790{
David Netoa901ffe2016-06-08 14:11:40 +01002791 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2792 switch (glslangBuiltIn)
2793 {
2794 case glslang::EbvClipDistance:
2795 case glslang::EbvCullDistance:
2796 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002797#ifdef NV_EXTENSIONS
2798 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002799 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002800 case glslang::EbvViewportMaskNV:
2801 case glslang::EbvSecondaryPositionNV:
2802 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002803 case glslang::EbvPositionPerViewNV:
2804 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002805#endif
David Netoa901ffe2016-06-08 14:11:40 +01002806 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2807 // Alternately, we could just call this for any glslang built-in, since the
2808 // capability already guards against duplicates.
2809 TranslateBuiltInDecoration(glslangBuiltIn, false);
2810 break;
2811 default:
2812 // Capabilities were already generated when the struct was declared.
2813 break;
2814 }
John Kessenichebb50532016-05-16 19:22:05 -06002815}
2816
John Kessenich6fccb3c2016-09-19 16:01:41 -06002817bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002818{
John Kessenicheee9d532016-09-19 18:09:30 -06002819 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002820}
2821
2822// Make all the functions, skeletally, without actually visiting their bodies.
2823void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2824{
2825 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2826 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002827 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002828 continue;
2829
2830 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002831 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002832 //
qining25262b32016-05-06 17:25:16 -04002833 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002834 // function. What it is an address of varies:
2835 //
John Kessenich4bf71552016-09-02 11:20:21 -06002836 // - "in" parameters not marked as "const" can be written to without modifying the calling
2837 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002838 //
2839 // - "const in" parameters can just be the r-value, as no writes need occur.
2840 //
John Kessenich4bf71552016-09-02 11:20:21 -06002841 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2842 // 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 -06002843
2844 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002845 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2847
John Kessenich37789792017-03-21 23:56:40 -06002848 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2849
John Kessenich140f3df2015-06-26 16:58:36 -06002850 for (int p = 0; p < (int)parameters.size(); ++p) {
2851 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2852 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002853 // can we pass by reference?
2854 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002855 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002856 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002857 (p == 0 && implicitThis)) // implicit 'this'
John Kessenich67027182017-04-19 18:34:49 -06002858 typeId = builder.makePointer(TranslateStorageClass(paramType, glslangIntermediate->usingStorageBuffer()), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002859 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002860 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2861 else
John Kessenich4bf71552016-09-02 11:20:21 -06002862 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002863 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002864 paramTypes.push_back(typeId);
2865 }
2866
2867 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002868 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2869 convertGlslangToSpvType(glslFunction->getType()),
2870 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002871 if (implicitThis)
2872 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002873
2874 // Track function to emit/call later
2875 functionMap[glslFunction->getName().c_str()] = function;
2876
2877 // Set the parameter id's
2878 for (int p = 0; p < (int)parameters.size(); ++p) {
2879 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2880 // give a name too
2881 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2882 }
2883 }
2884}
2885
2886// Process all the initializers, while skipping the functions and link objects
2887void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2888{
2889 builder.setBuildPoint(shaderEntry->getLastBlock());
2890 for (int i = 0; i < (int)initializers.size(); ++i) {
2891 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2892 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2893
2894 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002895 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002896 initializer->traverse(this);
2897 }
2898 }
2899}
2900
2901// Process all the functions, while skipping initializers.
2902void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2903{
2904 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2905 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002906 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002907 node->traverse(this);
2908 }
2909}
2910
2911void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2912{
qining25262b32016-05-06 17:25:16 -04002913 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002914 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002915 currentFunction = functionMap[node->getName().c_str()];
2916 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002917 builder.setBuildPoint(functionBlock);
2918}
2919
Rex Xu04db3f52015-09-16 11:44:02 +08002920void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002921{
Rex Xufc618912015-09-09 16:42:49 +08002922 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002923
2924 glslang::TSampler sampler = {};
2925 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002926 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002927 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2928 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2929 }
2930
John Kessenich140f3df2015-06-26 16:58:36 -06002931 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2932 builder.clearAccessChain();
2933 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002934
2935 // Special case l-value operands
2936 bool lvalue = false;
2937 switch (node.getOp()) {
2938 case glslang::EOpImageAtomicAdd:
2939 case glslang::EOpImageAtomicMin:
2940 case glslang::EOpImageAtomicMax:
2941 case glslang::EOpImageAtomicAnd:
2942 case glslang::EOpImageAtomicOr:
2943 case glslang::EOpImageAtomicXor:
2944 case glslang::EOpImageAtomicExchange:
2945 case glslang::EOpImageAtomicCompSwap:
2946 if (i == 0)
2947 lvalue = true;
2948 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002949 case glslang::EOpSparseImageLoad:
2950 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2951 lvalue = true;
2952 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002953 case glslang::EOpSparseTexture:
2954 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2955 lvalue = true;
2956 break;
2957 case glslang::EOpSparseTextureClamp:
2958 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2959 lvalue = true;
2960 break;
2961 case glslang::EOpSparseTextureLod:
2962 case glslang::EOpSparseTextureOffset:
2963 if (i == 3)
2964 lvalue = true;
2965 break;
2966 case glslang::EOpSparseTextureFetch:
2967 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2968 lvalue = true;
2969 break;
2970 case glslang::EOpSparseTextureFetchOffset:
2971 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2972 lvalue = true;
2973 break;
2974 case glslang::EOpSparseTextureLodOffset:
2975 case glslang::EOpSparseTextureGrad:
2976 case glslang::EOpSparseTextureOffsetClamp:
2977 if (i == 4)
2978 lvalue = true;
2979 break;
2980 case glslang::EOpSparseTextureGradOffset:
2981 case glslang::EOpSparseTextureGradClamp:
2982 if (i == 5)
2983 lvalue = true;
2984 break;
2985 case glslang::EOpSparseTextureGradOffsetClamp:
2986 if (i == 6)
2987 lvalue = true;
2988 break;
2989 case glslang::EOpSparseTextureGather:
2990 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2991 lvalue = true;
2992 break;
2993 case glslang::EOpSparseTextureGatherOffset:
2994 case glslang::EOpSparseTextureGatherOffsets:
2995 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2996 lvalue = true;
2997 break;
Rex Xufc618912015-09-09 16:42:49 +08002998 default:
2999 break;
3000 }
3001
Rex Xu6b86d492015-09-16 17:48:22 +08003002 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003003 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003004 else
John Kessenich32cfd492016-02-02 12:37:46 -07003005 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003006 }
3007}
3008
John Kessenichfc51d282015-08-19 13:34:18 -06003009void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003010{
John Kessenichfc51d282015-08-19 13:34:18 -06003011 builder.clearAccessChain();
3012 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003013 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003014}
John Kessenich140f3df2015-06-26 16:58:36 -06003015
John Kessenichfc51d282015-08-19 13:34:18 -06003016spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3017{
Rex Xufc618912015-09-09 16:42:49 +08003018 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003019 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003021 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003022
John Kessenichfc51d282015-08-19 13:34:18 -06003023 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003024 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3025 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3026 std::vector<spv::Id> arguments;
3027 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003028 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003029 else
3030 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003031 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003032
3033 spv::Builder::TextureParameters params = { };
3034 params.sampler = arguments[0];
3035
Rex Xu04db3f52015-09-16 11:44:02 +08003036 glslang::TCrackedTextureOp cracked;
3037 node->crackTexture(sampler, cracked);
3038
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003039 const bool isUnsignedResult =
3040 node->getType().getBasicType() == glslang::EbtUint64 ||
3041 node->getType().getBasicType() == glslang::EbtUint;
3042
John Kessenichfc51d282015-08-19 13:34:18 -06003043 // Check for queries
3044 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003045 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3046 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003047 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003048
John Kessenichfc51d282015-08-19 13:34:18 -06003049 switch (node->getOp()) {
3050 case glslang::EOpImageQuerySize:
3051 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003052 if (arguments.size() > 1) {
3053 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003054 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003055 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003056 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003057 case glslang::EOpImageQuerySamples:
3058 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003059 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003060 case glslang::EOpTextureQueryLod:
3061 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003062 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003063 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003064 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003065 case glslang::EOpSparseTexelsResident:
3066 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003067 default:
3068 assert(0);
3069 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003070 }
John Kessenich140f3df2015-06-26 16:58:36 -06003071 }
3072
Rex Xufc618912015-09-09 16:42:49 +08003073 // Check for image functions other than queries
3074 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003075 std::vector<spv::Id> operands;
3076 auto opIt = arguments.begin();
3077 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003078
3079 // Handle subpass operations
3080 // TODO: GLSL should change to have the "MS" only on the type rather than the
3081 // built-in function.
3082 if (cracked.subpass) {
3083 // add on the (0,0) coordinate
3084 spv::Id zero = builder.makeIntConstant(0);
3085 std::vector<spv::Id> comps;
3086 comps.push_back(zero);
3087 comps.push_back(zero);
3088 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3089 if (sampler.ms) {
3090 operands.push_back(spv::ImageOperandsSampleMask);
3091 operands.push_back(*(opIt++));
3092 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003093 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003094 }
3095
John Kessenich56bab042015-09-16 10:54:31 -06003096 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003097 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003098 if (sampler.ms) {
3099 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003100 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003101 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003102 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3103 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003104 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003105 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003106 if (sampler.ms) {
3107 operands.push_back(*(opIt + 1));
3108 operands.push_back(spv::ImageOperandsSampleMask);
3109 operands.push_back(*opIt);
3110 } else
3111 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003112 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003113 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3114 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003115 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003116 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3117 builder.addCapability(spv::CapabilitySparseResidency);
3118 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3119 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3120
3121 if (sampler.ms) {
3122 operands.push_back(spv::ImageOperandsSampleMask);
3123 operands.push_back(*opIt++);
3124 }
3125
3126 // Create the return type that was a special structure
3127 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003128 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003129 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3130 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3131
3132 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3133
3134 // Decode the return type
3135 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3136 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003137 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003138 // Process image atomic operations
3139
3140 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3141 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003142 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003143
John Kessenich8c8505c2016-07-26 12:50:38 -06003144 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003145 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003146
3147 std::vector<spv::Id> operands;
3148 operands.push_back(pointer);
3149 for (; opIt != arguments.end(); ++opIt)
3150 operands.push_back(*opIt);
3151
John Kessenich8c8505c2016-07-26 12:50:38 -06003152 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003153 }
3154 }
3155
3156 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003157 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003158 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3159
John Kessenichfc51d282015-08-19 13:34:18 -06003160 // check for bias argument
3161 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003162 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003163 int nonBiasArgCount = 2;
3164 if (cracked.offset)
3165 ++nonBiasArgCount;
3166 if (cracked.grad)
3167 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003168 if (cracked.lodClamp)
3169 ++nonBiasArgCount;
3170 if (sparse)
3171 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003172
3173 if ((int)arguments.size() > nonBiasArgCount)
3174 bias = true;
3175 }
3176
John Kessenicha5c33d62016-06-02 23:45:21 -06003177 // See if the sampler param should really be just the SPV image part
3178 if (cracked.fetch) {
3179 // a fetch needs to have the image extracted first
3180 if (builder.isSampledImage(params.sampler))
3181 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3182 }
3183
John Kessenichfc51d282015-08-19 13:34:18 -06003184 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003185
John Kessenichfc51d282015-08-19 13:34:18 -06003186 params.coords = arguments[1];
3187 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003188 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003189
3190 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003191 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003192 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003193 ++extraArgs;
3194 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003195 params.Dref = arguments[2];
3196 ++extraArgs;
3197 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003198 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003199 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003200 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003201 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003202 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003203 dRefComp = builder.getNumComponents(params.coords) - 1;
3204 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003205 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3206 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003207
3208 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003209 if (cracked.lod) {
3210 params.lod = arguments[2];
3211 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003212 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3213 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3214 noImplicitLod = true;
3215 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003216
3217 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003218 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003219 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003220 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003221 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003222
3223 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003224 if (cracked.grad) {
3225 params.gradX = arguments[2 + extraArgs];
3226 params.gradY = arguments[3 + extraArgs];
3227 extraArgs += 2;
3228 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003229
3230 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003231 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003232 params.offset = arguments[2 + extraArgs];
3233 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003234 } else if (cracked.offsets) {
3235 params.offsets = arguments[2 + extraArgs];
3236 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003237 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003238
3239 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003240 if (cracked.lodClamp) {
3241 params.lodClamp = arguments[2 + extraArgs];
3242 ++extraArgs;
3243 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003244
3245 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003246 if (sparse) {
3247 params.texelOut = arguments[2 + extraArgs];
3248 ++extraArgs;
3249 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003250
3251 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003252 if (bias) {
3253 params.bias = arguments[2 + extraArgs];
3254 ++extraArgs;
3255 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003256
3257 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003258 if (cracked.gather && ! sampler.shadow) {
3259 // default component is 0, if missing, otherwise an argument
3260 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003261 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003262 ++extraArgs;
3263 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003264 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003265 }
3266 }
John Kessenichfc51d282015-08-19 13:34:18 -06003267
John Kessenich65336482016-06-16 14:06:26 -06003268 // projective component (might not to move)
3269 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3270 // are divided by the last component of P."
3271 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3272 // unused components will appear after all used components."
3273 if (cracked.proj) {
3274 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3275 int projTargetComp;
3276 switch (sampler.dim) {
3277 case glslang::Esd1D: projTargetComp = 1; break;
3278 case glslang::Esd2D: projTargetComp = 2; break;
3279 case glslang::EsdRect: projTargetComp = 2; break;
3280 default: projTargetComp = projSourceComp; break;
3281 }
3282 // copy the projective coordinate if we have to
3283 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003284 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003285 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3286 projSourceComp);
3287 params.coords = builder.createCompositeInsert(projComp, params.coords,
3288 builder.getTypeId(params.coords), projTargetComp);
3289 }
3290 }
3291
John Kessenich8c8505c2016-07-26 12:50:38 -06003292 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003293}
3294
3295spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3296{
3297 // Grab the function's pointer from the previously created function
3298 spv::Function* function = functionMap[node->getName().c_str()];
3299 if (! function)
3300 return 0;
3301
3302 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3303 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3304
3305 // See comments in makeFunctions() for details about the semantics for parameter passing.
3306 //
3307 // These imply we need a four step process:
3308 // 1. Evaluate the arguments
3309 // 2. Allocate and make copies of in, out, and inout arguments
3310 // 3. Make the call
3311 // 4. Copy back the results
3312
3313 // 1. Evaluate the arguments
3314 std::vector<spv::Builder::AccessChain> lValues;
3315 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003316 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003318 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003319 // build l-value
3320 builder.clearAccessChain();
3321 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003322 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003323 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003324 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003325 // save l-value
3326 lValues.push_back(builder.getAccessChain());
3327 } else {
3328 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003329 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003330 }
3331 }
3332
3333 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3334 // copy the original into that space.
3335 //
3336 // Also, build up the list of actual arguments to pass in for the call
3337 int lValueCount = 0;
3338 int rValueCount = 0;
3339 std::vector<spv::Id> spvArgs;
3340 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003341 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003342 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003343 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003344 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3345 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003346 builder.setAccessChain(lValues[lValueCount]);
3347 arg = builder.accessChainGetLValue();
3348 ++lValueCount;
3349 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003350 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003351 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3352 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3353 // need to copy the input into output space
3354 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003355 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003356 builder.clearAccessChain();
3357 builder.setAccessChainLValue(arg);
3358 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003359 }
3360 ++lValueCount;
3361 } else {
3362 arg = rValues[rValueCount];
3363 ++rValueCount;
3364 }
3365 spvArgs.push_back(arg);
3366 }
3367
3368 // 3. Make the call.
3369 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003370 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003371
3372 // 4. Copy back out an "out" arguments.
3373 lValueCount = 0;
3374 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003375 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003376 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3377 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3378 spv::Id copy = builder.createLoad(spvArgs[a]);
3379 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003380 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003381 }
3382 ++lValueCount;
3383 }
3384 }
3385
3386 return result;
3387}
3388
3389// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003390spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3391 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003392 spv::Id typeId, spv::Id left, spv::Id right,
3393 glslang::TBasicType typeProxy, bool reduceComparison)
3394{
Rex Xu8ff43de2016-04-22 16:51:45 +08003395 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003396#ifdef AMD_EXTENSIONS
3397 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3398#else
John Kessenich140f3df2015-06-26 16:58:36 -06003399 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003400#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003401 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003402
3403 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003404 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003405 bool comparison = false;
3406
3407 switch (op) {
3408 case glslang::EOpAdd:
3409 case glslang::EOpAddAssign:
3410 if (isFloat)
3411 binOp = spv::OpFAdd;
3412 else
3413 binOp = spv::OpIAdd;
3414 break;
3415 case glslang::EOpSub:
3416 case glslang::EOpSubAssign:
3417 if (isFloat)
3418 binOp = spv::OpFSub;
3419 else
3420 binOp = spv::OpISub;
3421 break;
3422 case glslang::EOpMul:
3423 case glslang::EOpMulAssign:
3424 if (isFloat)
3425 binOp = spv::OpFMul;
3426 else
3427 binOp = spv::OpIMul;
3428 break;
3429 case glslang::EOpVectorTimesScalar:
3430 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003431 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003432 if (builder.isVector(right))
3433 std::swap(left, right);
3434 assert(builder.isScalar(right));
3435 needMatchingVectors = false;
3436 binOp = spv::OpVectorTimesScalar;
3437 } else
3438 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003439 break;
3440 case glslang::EOpVectorTimesMatrix:
3441 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003442 binOp = spv::OpVectorTimesMatrix;
3443 break;
3444 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003445 binOp = spv::OpMatrixTimesVector;
3446 break;
3447 case glslang::EOpMatrixTimesScalar:
3448 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003449 binOp = spv::OpMatrixTimesScalar;
3450 break;
3451 case glslang::EOpMatrixTimesMatrix:
3452 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003453 binOp = spv::OpMatrixTimesMatrix;
3454 break;
3455 case glslang::EOpOuterProduct:
3456 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003457 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003458 break;
3459
3460 case glslang::EOpDiv:
3461 case glslang::EOpDivAssign:
3462 if (isFloat)
3463 binOp = spv::OpFDiv;
3464 else if (isUnsigned)
3465 binOp = spv::OpUDiv;
3466 else
3467 binOp = spv::OpSDiv;
3468 break;
3469 case glslang::EOpMod:
3470 case glslang::EOpModAssign:
3471 if (isFloat)
3472 binOp = spv::OpFMod;
3473 else if (isUnsigned)
3474 binOp = spv::OpUMod;
3475 else
3476 binOp = spv::OpSMod;
3477 break;
3478 case glslang::EOpRightShift:
3479 case glslang::EOpRightShiftAssign:
3480 if (isUnsigned)
3481 binOp = spv::OpShiftRightLogical;
3482 else
3483 binOp = spv::OpShiftRightArithmetic;
3484 break;
3485 case glslang::EOpLeftShift:
3486 case glslang::EOpLeftShiftAssign:
3487 binOp = spv::OpShiftLeftLogical;
3488 break;
3489 case glslang::EOpAnd:
3490 case glslang::EOpAndAssign:
3491 binOp = spv::OpBitwiseAnd;
3492 break;
3493 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003494 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 binOp = spv::OpLogicalAnd;
3496 break;
3497 case glslang::EOpInclusiveOr:
3498 case glslang::EOpInclusiveOrAssign:
3499 binOp = spv::OpBitwiseOr;
3500 break;
3501 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003502 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 binOp = spv::OpLogicalOr;
3504 break;
3505 case glslang::EOpExclusiveOr:
3506 case glslang::EOpExclusiveOrAssign:
3507 binOp = spv::OpBitwiseXor;
3508 break;
3509 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003510 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 break;
3513
3514 case glslang::EOpLessThan:
3515 case glslang::EOpGreaterThan:
3516 case glslang::EOpLessThanEqual:
3517 case glslang::EOpGreaterThanEqual:
3518 case glslang::EOpEqual:
3519 case glslang::EOpNotEqual:
3520 case glslang::EOpVectorEqual:
3521 case glslang::EOpVectorNotEqual:
3522 comparison = true;
3523 break;
3524 default:
3525 break;
3526 }
3527
John Kessenich7c1aa102015-10-15 13:29:11 -06003528 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003529 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003530 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003531 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003532 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003533
3534 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003535 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003536 builder.promoteScalar(precision, left, right);
3537
qining25262b32016-05-06 17:25:16 -04003538 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3539 addDecoration(result, noContraction);
3540 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003541 }
3542
3543 if (! comparison)
3544 return 0;
3545
John Kessenich7c1aa102015-10-15 13:29:11 -06003546 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003547
John Kessenich4583b612016-08-07 19:14:22 -06003548 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3549 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003550 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003551
3552 switch (op) {
3553 case glslang::EOpLessThan:
3554 if (isFloat)
3555 binOp = spv::OpFOrdLessThan;
3556 else if (isUnsigned)
3557 binOp = spv::OpULessThan;
3558 else
3559 binOp = spv::OpSLessThan;
3560 break;
3561 case glslang::EOpGreaterThan:
3562 if (isFloat)
3563 binOp = spv::OpFOrdGreaterThan;
3564 else if (isUnsigned)
3565 binOp = spv::OpUGreaterThan;
3566 else
3567 binOp = spv::OpSGreaterThan;
3568 break;
3569 case glslang::EOpLessThanEqual:
3570 if (isFloat)
3571 binOp = spv::OpFOrdLessThanEqual;
3572 else if (isUnsigned)
3573 binOp = spv::OpULessThanEqual;
3574 else
3575 binOp = spv::OpSLessThanEqual;
3576 break;
3577 case glslang::EOpGreaterThanEqual:
3578 if (isFloat)
3579 binOp = spv::OpFOrdGreaterThanEqual;
3580 else if (isUnsigned)
3581 binOp = spv::OpUGreaterThanEqual;
3582 else
3583 binOp = spv::OpSGreaterThanEqual;
3584 break;
3585 case glslang::EOpEqual:
3586 case glslang::EOpVectorEqual:
3587 if (isFloat)
3588 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003589 else if (isBool)
3590 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003591 else
3592 binOp = spv::OpIEqual;
3593 break;
3594 case glslang::EOpNotEqual:
3595 case glslang::EOpVectorNotEqual:
3596 if (isFloat)
3597 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003598 else if (isBool)
3599 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003600 else
3601 binOp = spv::OpINotEqual;
3602 break;
3603 default:
3604 break;
3605 }
3606
qining25262b32016-05-06 17:25:16 -04003607 if (binOp != spv::OpNop) {
3608 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3609 addDecoration(result, noContraction);
3610 return builder.setPrecision(result, precision);
3611 }
John Kessenich140f3df2015-06-26 16:58:36 -06003612
3613 return 0;
3614}
3615
John Kessenich04bb8a02015-12-12 12:28:14 -07003616//
3617// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3618// These can be any of:
3619//
3620// matrix * scalar
3621// scalar * matrix
3622// matrix * matrix linear algebraic
3623// matrix * vector
3624// vector * matrix
3625// matrix * matrix componentwise
3626// matrix op matrix op in {+, -, /}
3627// matrix op scalar op in {+, -, /}
3628// scalar op matrix op in {+, -, /}
3629//
qining25262b32016-05-06 17:25:16 -04003630spv::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 -07003631{
3632 bool firstClass = true;
3633
3634 // First, handle first-class matrix operations (* and matrix/scalar)
3635 switch (op) {
3636 case spv::OpFDiv:
3637 if (builder.isMatrix(left) && builder.isScalar(right)) {
3638 // turn matrix / scalar into a multiply...
3639 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3640 op = spv::OpMatrixTimesScalar;
3641 } else
3642 firstClass = false;
3643 break;
3644 case spv::OpMatrixTimesScalar:
3645 if (builder.isMatrix(right))
3646 std::swap(left, right);
3647 assert(builder.isScalar(right));
3648 break;
3649 case spv::OpVectorTimesMatrix:
3650 assert(builder.isVector(left));
3651 assert(builder.isMatrix(right));
3652 break;
3653 case spv::OpMatrixTimesVector:
3654 assert(builder.isMatrix(left));
3655 assert(builder.isVector(right));
3656 break;
3657 case spv::OpMatrixTimesMatrix:
3658 assert(builder.isMatrix(left));
3659 assert(builder.isMatrix(right));
3660 break;
3661 default:
3662 firstClass = false;
3663 break;
3664 }
3665
qining25262b32016-05-06 17:25:16 -04003666 if (firstClass) {
3667 spv::Id result = builder.createBinOp(op, typeId, left, right);
3668 addDecoration(result, noContraction);
3669 return builder.setPrecision(result, precision);
3670 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003671
LoopDawg592860c2016-06-09 08:57:35 -06003672 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003673 // The result type of all of them is the same type as the (a) matrix operand.
3674 // The algorithm is to:
3675 // - break the matrix(es) into vectors
3676 // - smear any scalar to a vector
3677 // - do vector operations
3678 // - make a matrix out the vector results
3679 switch (op) {
3680 case spv::OpFAdd:
3681 case spv::OpFSub:
3682 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003683 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003684 case spv::OpFMul:
3685 {
3686 // one time set up...
3687 bool leftMat = builder.isMatrix(left);
3688 bool rightMat = builder.isMatrix(right);
3689 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3690 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3691 spv::Id scalarType = builder.getScalarTypeId(typeId);
3692 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3693 std::vector<spv::Id> results;
3694 spv::Id smearVec = spv::NoResult;
3695 if (builder.isScalar(left))
3696 smearVec = builder.smearScalar(precision, left, vecType);
3697 else if (builder.isScalar(right))
3698 smearVec = builder.smearScalar(precision, right, vecType);
3699
3700 // do each vector op
3701 for (unsigned int c = 0; c < numCols; ++c) {
3702 std::vector<unsigned int> indexes;
3703 indexes.push_back(c);
3704 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3705 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003706 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3707 addDecoration(result, noContraction);
3708 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003709 }
3710
3711 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003712 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003713 }
3714 default:
3715 assert(0);
3716 return spv::NoResult;
3717 }
3718}
3719
qining25262b32016-05-06 17:25:16 -04003720spv::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 -06003721{
3722 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003723 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003724 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003725 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003726#ifdef AMD_EXTENSIONS
3727 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3728#else
Rex Xu04db3f52015-09-16 11:44:02 +08003729 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003730#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003731
3732 switch (op) {
3733 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003734 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003735 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003736 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003737 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003738 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003739 unaryOp = spv::OpSNegate;
3740 break;
3741
3742 case glslang::EOpLogicalNot:
3743 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 unaryOp = spv::OpLogicalNot;
3745 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 case glslang::EOpBitwiseNot:
3747 unaryOp = spv::OpNot;
3748 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003749
John Kessenich140f3df2015-06-26 16:58:36 -06003750 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756 case glslang::EOpTranspose:
3757 unaryOp = spv::OpTranspose;
3758 break;
3759
3760 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
3769 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
3778 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003779 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003780 break;
3781 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003782 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003783 break;
3784
3785 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003789 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 break;
3791 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003792 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003793 break;
3794 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003795 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003796 break;
3797 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003798 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 break;
3800 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003801 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003802 break;
3803
3804 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003805 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003806 break;
3807 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003808 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003809 break;
3810
3811 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003818 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003822 break;
3823 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003824 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003825 break;
3826 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003827 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003828 break;
3829
3830 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003831 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003834 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003835 break;
3836 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003837 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003841 break;
3842 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003843 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003846 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003847 break;
3848
3849 case glslang::EOpIsNan:
3850 unaryOp = spv::OpIsNan;
3851 break;
3852 case glslang::EOpIsInf:
3853 unaryOp = spv::OpIsInf;
3854 break;
LoopDawg592860c2016-06-09 08:57:35 -06003855 case glslang::EOpIsFinite:
3856 unaryOp = spv::OpIsFinite;
3857 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003858
Rex Xucbc426e2015-12-15 16:03:10 +08003859 case glslang::EOpFloatBitsToInt:
3860 case glslang::EOpFloatBitsToUint:
3861 case glslang::EOpIntBitsToFloat:
3862 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003863 case glslang::EOpDoubleBitsToInt64:
3864 case glslang::EOpDoubleBitsToUint64:
3865 case glslang::EOpInt64BitsToDouble:
3866 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003867 unaryOp = spv::OpBitcast;
3868 break;
3869
John Kessenich140f3df2015-06-26 16:58:36 -06003870 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003871 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003872 break;
3873 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003874 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003875 break;
3876 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003877 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003878 break;
3879 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003884 break;
3885 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003886 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003888 case glslang::EOpPackSnorm4x8:
3889 libCall = spv::GLSLstd450PackSnorm4x8;
3890 break;
3891 case glslang::EOpUnpackSnorm4x8:
3892 libCall = spv::GLSLstd450UnpackSnorm4x8;
3893 break;
3894 case glslang::EOpPackUnorm4x8:
3895 libCall = spv::GLSLstd450PackUnorm4x8;
3896 break;
3897 case glslang::EOpUnpackUnorm4x8:
3898 libCall = spv::GLSLstd450UnpackUnorm4x8;
3899 break;
3900 case glslang::EOpPackDouble2x32:
3901 libCall = spv::GLSLstd450PackDouble2x32;
3902 break;
3903 case glslang::EOpUnpackDouble2x32:
3904 libCall = spv::GLSLstd450UnpackDouble2x32;
3905 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003906
Rex Xu8ff43de2016-04-22 16:51:45 +08003907 case glslang::EOpPackInt2x32:
3908 case glslang::EOpUnpackInt2x32:
3909 case glslang::EOpPackUint2x32:
3910 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003911 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003912 break;
3913
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003914#ifdef AMD_EXTENSIONS
3915 case glslang::EOpPackFloat2x16:
3916 case glslang::EOpUnpackFloat2x16:
3917 unaryOp = spv::OpBitcast;
3918 break;
3919#endif
3920
John Kessenich140f3df2015-06-26 16:58:36 -06003921 case glslang::EOpDPdx:
3922 unaryOp = spv::OpDPdx;
3923 break;
3924 case glslang::EOpDPdy:
3925 unaryOp = spv::OpDPdy;
3926 break;
3927 case glslang::EOpFwidth:
3928 unaryOp = spv::OpFwidth;
3929 break;
3930 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003931 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003932 unaryOp = spv::OpDPdxFine;
3933 break;
3934 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003935 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003936 unaryOp = spv::OpDPdyFine;
3937 break;
3938 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003939 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003940 unaryOp = spv::OpFwidthFine;
3941 break;
3942 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003943 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003944 unaryOp = spv::OpDPdxCoarse;
3945 break;
3946 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003947 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003948 unaryOp = spv::OpDPdyCoarse;
3949 break;
3950 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003951 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003952 unaryOp = spv::OpFwidthCoarse;
3953 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003954 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003955 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003956 libCall = spv::GLSLstd450InterpolateAtCentroid;
3957 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003958 case glslang::EOpAny:
3959 unaryOp = spv::OpAny;
3960 break;
3961 case glslang::EOpAll:
3962 unaryOp = spv::OpAll;
3963 break;
3964
3965 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003966 if (isFloat)
3967 libCall = spv::GLSLstd450FAbs;
3968 else
3969 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003970 break;
3971 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003972 if (isFloat)
3973 libCall = spv::GLSLstd450FSign;
3974 else
3975 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003976 break;
3977
John Kessenichfc51d282015-08-19 13:34:18 -06003978 case glslang::EOpAtomicCounterIncrement:
3979 case glslang::EOpAtomicCounterDecrement:
3980 case glslang::EOpAtomicCounter:
3981 {
3982 // Handle all of the atomics in one place, in createAtomicOperation()
3983 std::vector<spv::Id> operands;
3984 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003985 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003986 }
3987
John Kessenichfc51d282015-08-19 13:34:18 -06003988 case glslang::EOpBitFieldReverse:
3989 unaryOp = spv::OpBitReverse;
3990 break;
3991 case glslang::EOpBitCount:
3992 unaryOp = spv::OpBitCount;
3993 break;
3994 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003995 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003996 break;
3997 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003998 if (isUnsigned)
3999 libCall = spv::GLSLstd450FindUMsb;
4000 else
4001 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004002 break;
4003
Rex Xu574ab042016-04-14 16:53:07 +08004004 case glslang::EOpBallot:
4005 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004006 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004007 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004008 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004009#ifdef AMD_EXTENSIONS
4010 case glslang::EOpMinInvocations:
4011 case glslang::EOpMaxInvocations:
4012 case glslang::EOpAddInvocations:
4013 case glslang::EOpMinInvocationsNonUniform:
4014 case glslang::EOpMaxInvocationsNonUniform:
4015 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004016 case glslang::EOpMinInvocationsInclusiveScan:
4017 case glslang::EOpMaxInvocationsInclusiveScan:
4018 case glslang::EOpAddInvocationsInclusiveScan:
4019 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4020 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4021 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4022 case glslang::EOpMinInvocationsExclusiveScan:
4023 case glslang::EOpMaxInvocationsExclusiveScan:
4024 case glslang::EOpAddInvocationsExclusiveScan:
4025 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4026 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4027 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004028#endif
Rex Xu51596642016-09-21 18:56:12 +08004029 {
4030 std::vector<spv::Id> operands;
4031 operands.push_back(operand);
4032 return createInvocationsOperation(op, typeId, operands, typeProxy);
4033 }
Rex Xu9d93a232016-05-05 12:30:44 +08004034
4035#ifdef AMD_EXTENSIONS
4036 case glslang::EOpMbcnt:
4037 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4038 libCall = spv::MbcntAMD;
4039 break;
4040
4041 case glslang::EOpCubeFaceIndex:
4042 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4043 libCall = spv::CubeFaceIndexAMD;
4044 break;
4045
4046 case glslang::EOpCubeFaceCoord:
4047 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4048 libCall = spv::CubeFaceCoordAMD;
4049 break;
4050#endif
Rex Xu338b1852016-05-05 20:38:33 +08004051
John Kessenich140f3df2015-06-26 16:58:36 -06004052 default:
4053 return 0;
4054 }
4055
4056 spv::Id id;
4057 if (libCall >= 0) {
4058 std::vector<spv::Id> args;
4059 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004060 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004061 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004062 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004063 }
John Kessenich140f3df2015-06-26 16:58:36 -06004064
qining25262b32016-05-06 17:25:16 -04004065 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004066 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004067}
4068
John Kessenich7a53f762016-01-20 11:19:27 -07004069// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004070spv::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 -07004071{
4072 // Handle unary operations vector by vector.
4073 // The result type is the same type as the original type.
4074 // The algorithm is to:
4075 // - break the matrix into vectors
4076 // - apply the operation to each vector
4077 // - make a matrix out the vector results
4078
4079 // get the types sorted out
4080 int numCols = builder.getNumColumns(operand);
4081 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004082 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4083 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004084 std::vector<spv::Id> results;
4085
4086 // do each vector op
4087 for (int c = 0; c < numCols; ++c) {
4088 std::vector<unsigned int> indexes;
4089 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004090 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4091 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4092 addDecoration(destVec, noContraction);
4093 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004094 }
4095
4096 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004097 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004098}
4099
Rex Xu73e3ce72016-04-27 18:48:17 +08004100spv::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 -06004101{
4102 spv::Op convOp = spv::OpNop;
4103 spv::Id zero = 0;
4104 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004105 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004106
4107 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4108
4109 switch (op) {
4110 case glslang::EOpConvIntToBool:
4111 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004112 case glslang::EOpConvInt64ToBool:
4113 case glslang::EOpConvUint64ToBool:
4114 zero = (op == glslang::EOpConvInt64ToBool ||
4115 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004116 zero = makeSmearedConstant(zero, vectorSize);
4117 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4118
4119 case glslang::EOpConvFloatToBool:
4120 zero = builder.makeFloatConstant(0.0F);
4121 zero = makeSmearedConstant(zero, vectorSize);
4122 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4123
4124 case glslang::EOpConvDoubleToBool:
4125 zero = builder.makeDoubleConstant(0.0);
4126 zero = makeSmearedConstant(zero, vectorSize);
4127 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4128
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004129#ifdef AMD_EXTENSIONS
4130 case glslang::EOpConvFloat16ToBool:
4131 zero = builder.makeFloat16Constant(0.0F);
4132 zero = makeSmearedConstant(zero, vectorSize);
4133 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4134#endif
4135
John Kessenich140f3df2015-06-26 16:58:36 -06004136 case glslang::EOpConvBoolToFloat:
4137 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004138 zero = builder.makeFloatConstant(0.0F);
4139 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004141
John Kessenich140f3df2015-06-26 16:58:36 -06004142 case glslang::EOpConvBoolToDouble:
4143 convOp = spv::OpSelect;
4144 zero = builder.makeDoubleConstant(0.0);
4145 one = builder.makeDoubleConstant(1.0);
4146 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004147
4148#ifdef AMD_EXTENSIONS
4149 case glslang::EOpConvBoolToFloat16:
4150 convOp = spv::OpSelect;
4151 zero = builder.makeFloat16Constant(0.0F);
4152 one = builder.makeFloat16Constant(1.0F);
4153 break;
4154#endif
4155
John Kessenich140f3df2015-06-26 16:58:36 -06004156 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004157 case glslang::EOpConvBoolToInt64:
4158 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4159 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004160 convOp = spv::OpSelect;
4161 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004162
John Kessenich140f3df2015-06-26 16:58:36 -06004163 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004164 case glslang::EOpConvBoolToUint64:
4165 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4166 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004167 convOp = spv::OpSelect;
4168 break;
4169
4170 case glslang::EOpConvIntToFloat:
4171 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004172 case glslang::EOpConvInt64ToFloat:
4173 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004174#ifdef AMD_EXTENSIONS
4175 case glslang::EOpConvIntToFloat16:
4176 case glslang::EOpConvInt64ToFloat16:
4177#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004178 convOp = spv::OpConvertSToF;
4179 break;
4180
4181 case glslang::EOpConvUintToFloat:
4182 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004183 case glslang::EOpConvUint64ToFloat:
4184 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004185#ifdef AMD_EXTENSIONS
4186 case glslang::EOpConvUintToFloat16:
4187 case glslang::EOpConvUint64ToFloat16:
4188#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004189 convOp = spv::OpConvertUToF;
4190 break;
4191
4192 case glslang::EOpConvDoubleToFloat:
4193 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004194#ifdef AMD_EXTENSIONS
4195 case glslang::EOpConvDoubleToFloat16:
4196 case glslang::EOpConvFloat16ToDouble:
4197 case glslang::EOpConvFloatToFloat16:
4198 case glslang::EOpConvFloat16ToFloat:
4199#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004200 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004201 if (builder.isMatrixType(destType))
4202 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004203 break;
4204
4205 case glslang::EOpConvFloatToInt:
4206 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004207 case glslang::EOpConvFloatToInt64:
4208 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004209#ifdef AMD_EXTENSIONS
4210 case glslang::EOpConvFloat16ToInt:
4211 case glslang::EOpConvFloat16ToInt64:
4212#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004213 convOp = spv::OpConvertFToS;
4214 break;
4215
4216 case glslang::EOpConvUintToInt:
4217 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004218 case glslang::EOpConvUint64ToInt64:
4219 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004220 if (builder.isInSpecConstCodeGenMode()) {
4221 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004222 zero = (op == glslang::EOpConvUint64ToInt64 ||
4223 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004224 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004225 // Use OpIAdd, instead of OpBitcast to do the conversion when
4226 // generating for OpSpecConstantOp instruction.
4227 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4228 }
4229 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004230 convOp = spv::OpBitcast;
4231 break;
4232
4233 case glslang::EOpConvFloatToUint:
4234 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004235 case glslang::EOpConvFloatToUint64:
4236 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004237#ifdef AMD_EXTENSIONS
4238 case glslang::EOpConvFloat16ToUint:
4239 case glslang::EOpConvFloat16ToUint64:
4240#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004241 convOp = spv::OpConvertFToU;
4242 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004243
4244 case glslang::EOpConvIntToInt64:
4245 case glslang::EOpConvInt64ToInt:
4246 convOp = spv::OpSConvert;
4247 break;
4248
4249 case glslang::EOpConvUintToUint64:
4250 case glslang::EOpConvUint64ToUint:
4251 convOp = spv::OpUConvert;
4252 break;
4253
4254 case glslang::EOpConvIntToUint64:
4255 case glslang::EOpConvInt64ToUint:
4256 case glslang::EOpConvUint64ToInt:
4257 case glslang::EOpConvUintToInt64:
4258 // OpSConvert/OpUConvert + OpBitCast
4259 switch (op) {
4260 case glslang::EOpConvIntToUint64:
4261 convOp = spv::OpSConvert;
4262 type = builder.makeIntType(64);
4263 break;
4264 case glslang::EOpConvInt64ToUint:
4265 convOp = spv::OpSConvert;
4266 type = builder.makeIntType(32);
4267 break;
4268 case glslang::EOpConvUint64ToInt:
4269 convOp = spv::OpUConvert;
4270 type = builder.makeUintType(32);
4271 break;
4272 case glslang::EOpConvUintToInt64:
4273 convOp = spv::OpUConvert;
4274 type = builder.makeUintType(64);
4275 break;
4276 default:
4277 assert(0);
4278 break;
4279 }
4280
4281 if (vectorSize > 0)
4282 type = builder.makeVectorType(type, vectorSize);
4283
4284 operand = builder.createUnaryOp(convOp, type, operand);
4285
4286 if (builder.isInSpecConstCodeGenMode()) {
4287 // Build zero scalar or vector for OpIAdd.
4288 zero = (op == glslang::EOpConvIntToUint64 ||
4289 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4290 zero = makeSmearedConstant(zero, vectorSize);
4291 // Use OpIAdd, instead of OpBitcast to do the conversion when
4292 // generating for OpSpecConstantOp instruction.
4293 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4294 }
4295 // For normal run-time conversion instruction, use OpBitcast.
4296 convOp = spv::OpBitcast;
4297 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004298 default:
4299 break;
4300 }
4301
4302 spv::Id result = 0;
4303 if (convOp == spv::OpNop)
4304 return result;
4305
4306 if (convOp == spv::OpSelect) {
4307 zero = makeSmearedConstant(zero, vectorSize);
4308 one = makeSmearedConstant(one, vectorSize);
4309 result = builder.createTriOp(convOp, destType, operand, one, zero);
4310 } else
4311 result = builder.createUnaryOp(convOp, destType, operand);
4312
John Kessenich32cfd492016-02-02 12:37:46 -07004313 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004314}
4315
4316spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4317{
4318 if (vectorSize == 0)
4319 return constant;
4320
4321 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4322 std::vector<spv::Id> components;
4323 for (int c = 0; c < vectorSize; ++c)
4324 components.push_back(constant);
4325 return builder.makeCompositeConstant(vectorTypeId, components);
4326}
4327
John Kessenich426394d2015-07-23 10:22:48 -06004328// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004329spv::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 -06004330{
4331 spv::Op opCode = spv::OpNop;
4332
4333 switch (op) {
4334 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004335 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004336 opCode = spv::OpAtomicIAdd;
4337 break;
4338 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004339 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004340 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004341 break;
4342 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004343 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004344 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004345 break;
4346 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004347 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004348 opCode = spv::OpAtomicAnd;
4349 break;
4350 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004351 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004352 opCode = spv::OpAtomicOr;
4353 break;
4354 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004355 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004356 opCode = spv::OpAtomicXor;
4357 break;
4358 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004359 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004360 opCode = spv::OpAtomicExchange;
4361 break;
4362 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004363 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004364 opCode = spv::OpAtomicCompareExchange;
4365 break;
4366 case glslang::EOpAtomicCounterIncrement:
4367 opCode = spv::OpAtomicIIncrement;
4368 break;
4369 case glslang::EOpAtomicCounterDecrement:
4370 opCode = spv::OpAtomicIDecrement;
4371 break;
4372 case glslang::EOpAtomicCounter:
4373 opCode = spv::OpAtomicLoad;
4374 break;
4375 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004376 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004377 break;
4378 }
4379
4380 // Sort out the operands
4381 // - mapping from glslang -> SPV
4382 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004383 // - compare-exchange swaps the value and comparator
4384 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004385 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4386 auto opIt = operands.begin(); // walk the glslang operands
4387 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004388 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4389 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4390 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004391 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4392 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004393 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004394 spvAtomicOperands.push_back(*(opIt + 1));
4395 spvAtomicOperands.push_back(*opIt);
4396 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004397 }
John Kessenich426394d2015-07-23 10:22:48 -06004398
John Kessenich3e60a6f2015-09-14 22:45:16 -06004399 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004400 for (; opIt != operands.end(); ++opIt)
4401 spvAtomicOperands.push_back(*opIt);
4402
4403 return builder.createOp(opCode, typeId, spvAtomicOperands);
4404}
4405
John Kessenich91cef522016-05-05 16:45:40 -06004406// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004407spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004408{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004409#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004410 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004411 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004412#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004413
Rex Xu51596642016-09-21 18:56:12 +08004414 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004415 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004416 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4417
chaocf200da82016-12-20 12:44:35 -08004418 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4419 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004420 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4421 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004422 } else if (op == glslang::EOpAnyInvocation ||
4423 op == glslang::EOpAllInvocations ||
4424 op == glslang::EOpAllInvocationsEqual) {
4425 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4426 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004427 } else {
4428 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004429#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004430 if (op == glslang::EOpMinInvocationsNonUniform ||
4431 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004432 op == glslang::EOpAddInvocationsNonUniform ||
4433 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4434 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4435 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4436 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4437 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4438 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004439 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004440#endif
Rex Xu51596642016-09-21 18:56:12 +08004441
4442 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004443#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004444 switch (op) {
4445 case glslang::EOpMinInvocations:
4446 case glslang::EOpMaxInvocations:
4447 case glslang::EOpAddInvocations:
4448 case glslang::EOpMinInvocationsNonUniform:
4449 case glslang::EOpMaxInvocationsNonUniform:
4450 case glslang::EOpAddInvocationsNonUniform:
4451 groupOperation = spv::GroupOperationReduce;
4452 spvGroupOperands.push_back(groupOperation);
4453 break;
4454 case glslang::EOpMinInvocationsInclusiveScan:
4455 case glslang::EOpMaxInvocationsInclusiveScan:
4456 case glslang::EOpAddInvocationsInclusiveScan:
4457 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4458 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4459 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4460 groupOperation = spv::GroupOperationInclusiveScan;
4461 spvGroupOperands.push_back(groupOperation);
4462 break;
4463 case glslang::EOpMinInvocationsExclusiveScan:
4464 case glslang::EOpMaxInvocationsExclusiveScan:
4465 case glslang::EOpAddInvocationsExclusiveScan:
4466 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4467 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4468 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4469 groupOperation = spv::GroupOperationExclusiveScan;
4470 spvGroupOperands.push_back(groupOperation);
4471 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004472 default:
4473 break;
Rex Xu430ef402016-10-14 17:22:23 +08004474 }
Rex Xu9d93a232016-05-05 12:30:44 +08004475#endif
Rex Xu51596642016-09-21 18:56:12 +08004476 }
4477
4478 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4479 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004480
4481 switch (op) {
4482 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004483 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004484 break;
John Kessenich91cef522016-05-05 16:45:40 -06004485 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004486 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004487 break;
John Kessenich91cef522016-05-05 16:45:40 -06004488 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004489 opCode = spv::OpSubgroupAllEqualKHR;
4490 break;
Rex Xu51596642016-09-21 18:56:12 +08004491 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004492 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004493 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004494 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004495 break;
4496 case glslang::EOpReadFirstInvocation:
4497 opCode = spv::OpSubgroupFirstInvocationKHR;
4498 break;
4499 case glslang::EOpBallot:
4500 {
4501 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4502 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4503 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4504 //
4505 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4506 //
4507 spv::Id uintType = builder.makeUintType(32);
4508 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4509 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4510
4511 std::vector<spv::Id> components;
4512 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4513 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4514
4515 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4516 return builder.createUnaryOp(spv::OpBitcast, typeId,
4517 builder.createCompositeConstruct(uvec2Type, components));
4518 }
4519
Rex Xu9d93a232016-05-05 12:30:44 +08004520#ifdef AMD_EXTENSIONS
4521 case glslang::EOpMinInvocations:
4522 case glslang::EOpMaxInvocations:
4523 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004524 case glslang::EOpMinInvocationsInclusiveScan:
4525 case glslang::EOpMaxInvocationsInclusiveScan:
4526 case glslang::EOpAddInvocationsInclusiveScan:
4527 case glslang::EOpMinInvocationsExclusiveScan:
4528 case glslang::EOpMaxInvocationsExclusiveScan:
4529 case glslang::EOpAddInvocationsExclusiveScan:
4530 if (op == glslang::EOpMinInvocations ||
4531 op == glslang::EOpMinInvocationsInclusiveScan ||
4532 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004533 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004534 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004535 else {
4536 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004537 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004538 else
Rex Xu51596642016-09-21 18:56:12 +08004539 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004540 }
Rex Xu430ef402016-10-14 17:22:23 +08004541 } else if (op == glslang::EOpMaxInvocations ||
4542 op == glslang::EOpMaxInvocationsInclusiveScan ||
4543 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004544 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004545 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004546 else {
4547 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004548 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004549 else
Rex Xu51596642016-09-21 18:56:12 +08004550 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004551 }
4552 } else {
4553 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004554 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004555 else
Rex Xu51596642016-09-21 18:56:12 +08004556 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004557 }
4558
Rex Xu2bbbe062016-08-23 15:41:05 +08004559 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004560 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004561
4562 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004563 case glslang::EOpMinInvocationsNonUniform:
4564 case glslang::EOpMaxInvocationsNonUniform:
4565 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004566 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4567 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4568 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4569 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4570 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4571 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4572 if (op == glslang::EOpMinInvocationsNonUniform ||
4573 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4574 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004575 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004576 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004577 else {
4578 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004579 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004580 else
Rex Xu51596642016-09-21 18:56:12 +08004581 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004582 }
4583 }
Rex Xu430ef402016-10-14 17:22:23 +08004584 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4585 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4586 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004587 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004588 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004589 else {
4590 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004591 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004592 else
Rex Xu51596642016-09-21 18:56:12 +08004593 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004594 }
4595 }
4596 else {
4597 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004598 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004599 else
Rex Xu51596642016-09-21 18:56:12 +08004600 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004601 }
4602
Rex Xu2bbbe062016-08-23 15:41:05 +08004603 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004604 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004605
4606 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004607#endif
John Kessenich91cef522016-05-05 16:45:40 -06004608 default:
4609 logger->missingFunctionality("invocation operation");
4610 return spv::NoResult;
4611 }
Rex Xu51596642016-09-21 18:56:12 +08004612
4613 assert(opCode != spv::OpNop);
4614 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004615}
4616
Rex Xu2bbbe062016-08-23 15:41:05 +08004617// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004618spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004619{
Rex Xub7072052016-09-26 15:53:40 +08004620#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004621 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4622 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004623 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004624 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004625 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4626 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4627 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004628#else
4629 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4630 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004631 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4632 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004633#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004634
4635 // Handle group invocation operations scalar by scalar.
4636 // The result type is the same type as the original type.
4637 // The algorithm is to:
4638 // - break the vector into scalars
4639 // - apply the operation to each scalar
4640 // - make a vector out the scalar results
4641
4642 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004643 int numComponents = builder.getNumComponents(operands[0]);
4644 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004645 std::vector<spv::Id> results;
4646
4647 // do each scalar op
4648 for (int comp = 0; comp < numComponents; ++comp) {
4649 std::vector<unsigned int> indexes;
4650 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004651 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004652 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004653 if (op == spv::OpSubgroupReadInvocationKHR) {
4654 spvGroupOperands.push_back(scalar);
4655 spvGroupOperands.push_back(operands[1]);
4656 } else if (op == spv::OpGroupBroadcast) {
4657 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004658 spvGroupOperands.push_back(scalar);
4659 spvGroupOperands.push_back(operands[1]);
4660 } else {
chaocf200da82016-12-20 12:44:35 -08004661 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004662 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004663 spvGroupOperands.push_back(scalar);
4664 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004665
Rex Xub7072052016-09-26 15:53:40 +08004666 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004667 }
4668
4669 // put the pieces together
4670 return builder.createCompositeConstruct(typeId, results);
4671}
Rex Xu2bbbe062016-08-23 15:41:05 +08004672
John Kessenich5e4b1242015-08-06 22:53:06 -06004673spv::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 -06004674{
Rex Xu8ff43de2016-04-22 16:51:45 +08004675 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004676#ifdef AMD_EXTENSIONS
4677 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4678#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004679 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004680#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004681
John Kessenich140f3df2015-06-26 16:58:36 -06004682 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004683 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004684 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004685 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004686 spv::Id typeId0 = 0;
4687 if (consumedOperands > 0)
4688 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004689 spv::Id typeId1 = 0;
4690 if (consumedOperands > 1)
4691 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004692 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004693
4694 switch (op) {
4695 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004696 if (isFloat)
4697 libCall = spv::GLSLstd450FMin;
4698 else if (isUnsigned)
4699 libCall = spv::GLSLstd450UMin;
4700 else
4701 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004702 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004703 break;
4704 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004705 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004706 break;
4707 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004708 if (isFloat)
4709 libCall = spv::GLSLstd450FMax;
4710 else if (isUnsigned)
4711 libCall = spv::GLSLstd450UMax;
4712 else
4713 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004714 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004715 break;
4716 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004717 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004718 break;
4719 case glslang::EOpDot:
4720 opCode = spv::OpDot;
4721 break;
4722 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004723 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004724 break;
4725
4726 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004727 if (isFloat)
4728 libCall = spv::GLSLstd450FClamp;
4729 else if (isUnsigned)
4730 libCall = spv::GLSLstd450UClamp;
4731 else
4732 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004733 builder.promoteScalar(precision, operands.front(), operands[1]);
4734 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004735 break;
4736 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004737 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4738 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004739 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004740 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004741 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004742 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004743 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004744 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004745 break;
4746 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004747 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004748 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004749 break;
4750 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004751 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004752 builder.promoteScalar(precision, operands[0], operands[2]);
4753 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004754 break;
4755
4756 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004757 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004760 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004761 break;
4762 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004763 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004764 break;
4765 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004766 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004767 break;
4768 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004769 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004770 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004771 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004772 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004773 libCall = spv::GLSLstd450InterpolateAtSample;
4774 break;
4775 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004776 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004777 libCall = spv::GLSLstd450InterpolateAtOffset;
4778 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004779 case glslang::EOpAddCarry:
4780 opCode = spv::OpIAddCarry;
4781 typeId = builder.makeStructResultType(typeId0, typeId0);
4782 consumedOperands = 2;
4783 break;
4784 case glslang::EOpSubBorrow:
4785 opCode = spv::OpISubBorrow;
4786 typeId = builder.makeStructResultType(typeId0, typeId0);
4787 consumedOperands = 2;
4788 break;
4789 case glslang::EOpUMulExtended:
4790 opCode = spv::OpUMulExtended;
4791 typeId = builder.makeStructResultType(typeId0, typeId0);
4792 consumedOperands = 2;
4793 break;
4794 case glslang::EOpIMulExtended:
4795 opCode = spv::OpSMulExtended;
4796 typeId = builder.makeStructResultType(typeId0, typeId0);
4797 consumedOperands = 2;
4798 break;
4799 case glslang::EOpBitfieldExtract:
4800 if (isUnsigned)
4801 opCode = spv::OpBitFieldUExtract;
4802 else
4803 opCode = spv::OpBitFieldSExtract;
4804 break;
4805 case glslang::EOpBitfieldInsert:
4806 opCode = spv::OpBitFieldInsert;
4807 break;
4808
4809 case glslang::EOpFma:
4810 libCall = spv::GLSLstd450Fma;
4811 break;
4812 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004813 {
4814 libCall = spv::GLSLstd450FrexpStruct;
4815 assert(builder.isPointerType(typeId1));
4816 typeId1 = builder.getContainedTypeId(typeId1);
4817#ifdef AMD_EXTENSIONS
4818 int width = builder.getScalarTypeWidth(typeId1);
4819#else
4820 int width = 32;
4821#endif
4822 if (builder.getNumComponents(operands[0]) == 1)
4823 frexpIntType = builder.makeIntegerType(width, true);
4824 else
4825 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4826 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4827 consumedOperands = 1;
4828 }
John Kessenich55e7d112015-11-15 21:33:39 -07004829 break;
4830 case glslang::EOpLdexp:
4831 libCall = spv::GLSLstd450Ldexp;
4832 break;
4833
Rex Xu574ab042016-04-14 16:53:07 +08004834 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004835 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004836
Rex Xu9d93a232016-05-05 12:30:44 +08004837#ifdef AMD_EXTENSIONS
4838 case glslang::EOpSwizzleInvocations:
4839 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4840 libCall = spv::SwizzleInvocationsAMD;
4841 break;
4842 case glslang::EOpSwizzleInvocationsMasked:
4843 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4844 libCall = spv::SwizzleInvocationsMaskedAMD;
4845 break;
4846 case glslang::EOpWriteInvocation:
4847 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4848 libCall = spv::WriteInvocationAMD;
4849 break;
4850
4851 case glslang::EOpMin3:
4852 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4853 if (isFloat)
4854 libCall = spv::FMin3AMD;
4855 else {
4856 if (isUnsigned)
4857 libCall = spv::UMin3AMD;
4858 else
4859 libCall = spv::SMin3AMD;
4860 }
4861 break;
4862 case glslang::EOpMax3:
4863 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4864 if (isFloat)
4865 libCall = spv::FMax3AMD;
4866 else {
4867 if (isUnsigned)
4868 libCall = spv::UMax3AMD;
4869 else
4870 libCall = spv::SMax3AMD;
4871 }
4872 break;
4873 case glslang::EOpMid3:
4874 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4875 if (isFloat)
4876 libCall = spv::FMid3AMD;
4877 else {
4878 if (isUnsigned)
4879 libCall = spv::UMid3AMD;
4880 else
4881 libCall = spv::SMid3AMD;
4882 }
4883 break;
4884
4885 case glslang::EOpInterpolateAtVertex:
4886 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4887 libCall = spv::InterpolateAtVertexAMD;
4888 break;
4889#endif
4890
John Kessenich140f3df2015-06-26 16:58:36 -06004891 default:
4892 return 0;
4893 }
4894
4895 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004896 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004897 // Use an extended instruction from the standard library.
4898 // Construct the call arguments, without modifying the original operands vector.
4899 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4900 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004901 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004902 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004903 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004904 case 0:
4905 // should all be handled by visitAggregate and createNoArgOperation
4906 assert(0);
4907 return 0;
4908 case 1:
4909 // should all be handled by createUnaryOperation
4910 assert(0);
4911 return 0;
4912 case 2:
4913 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004915 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004916 // anything 3 or over doesn't have l-value operands, so all should be consumed
4917 assert(consumedOperands == operands.size());
4918 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004919 break;
4920 }
4921 }
4922
John Kessenich55e7d112015-11-15 21:33:39 -07004923 // Decode the return types that were structures
4924 switch (op) {
4925 case glslang::EOpAddCarry:
4926 case glslang::EOpSubBorrow:
4927 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4928 id = builder.createCompositeExtract(id, typeId0, 0);
4929 break;
4930 case glslang::EOpUMulExtended:
4931 case glslang::EOpIMulExtended:
4932 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4933 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4934 break;
4935 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004936 {
4937 assert(operands.size() == 2);
4938 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4939 // "exp" is floating-point type (from HLSL intrinsic)
4940 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4941 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4942 builder.createStore(member1, operands[1]);
4943 } else
4944 // "exp" is integer type (from GLSL built-in function)
4945 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4946 id = builder.createCompositeExtract(id, typeId0, 0);
4947 }
John Kessenich55e7d112015-11-15 21:33:39 -07004948 break;
4949 default:
4950 break;
4951 }
4952
John Kessenich32cfd492016-02-02 12:37:46 -07004953 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004954}
4955
Rex Xu9d93a232016-05-05 12:30:44 +08004956// Intrinsics with no arguments (or no return value, and no precision).
4957spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004958{
4959 // TODO: get the barrier operands correct
4960
4961 switch (op) {
4962 case glslang::EOpEmitVertex:
4963 builder.createNoResultOp(spv::OpEmitVertex);
4964 return 0;
4965 case glslang::EOpEndPrimitive:
4966 builder.createNoResultOp(spv::OpEndPrimitive);
4967 return 0;
4968 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004969 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004970 return 0;
4971 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004972 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004973 return 0;
4974 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004975 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004976 return 0;
4977 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004978 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004979 return 0;
4980 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004981 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004982 return 0;
4983 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004984 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004985 return 0;
4986 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004987 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004988 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004989 case glslang::EOpAllMemoryBarrierWithGroupSync:
4990 // Control barrier with non-"None" semantic is also a memory barrier.
4991 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4992 return 0;
4993 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4994 // Control barrier with non-"None" semantic is also a memory barrier.
4995 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4996 return 0;
4997 case glslang::EOpWorkgroupMemoryBarrier:
4998 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4999 return 0;
5000 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5001 // Control barrier with non-"None" semantic is also a memory barrier.
5002 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5003 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005004#ifdef AMD_EXTENSIONS
5005 case glslang::EOpTime:
5006 {
5007 std::vector<spv::Id> args; // Dummy arguments
5008 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5009 return builder.setPrecision(id, precision);
5010 }
5011#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005012 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005013 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005014 return 0;
5015 }
5016}
5017
5018spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5019{
John Kessenich2f273362015-07-18 22:34:27 -06005020 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005021 spv::Id id;
5022 if (symbolValues.end() != iter) {
5023 id = iter->second;
5024 return id;
5025 }
5026
5027 // it was not found, create it
5028 id = createSpvVariable(symbol);
5029 symbolValues[symbol->getId()] = id;
5030
Rex Xuc884b4a2016-06-29 15:03:44 +08005031 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005032 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005033 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005034 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005035 if (symbol->getType().getQualifier().hasSpecConstantId())
5036 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005037 if (symbol->getQualifier().hasIndex())
5038 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5039 if (symbol->getQualifier().hasComponent())
5040 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5041 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005042 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005043 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005044 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005045 if (symbol->getQualifier().hasXfbBuffer())
5046 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5047 if (symbol->getQualifier().hasXfbOffset())
5048 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5049 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005050 // atomic counters use this:
5051 if (symbol->getQualifier().hasOffset())
5052 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005053 }
5054
scygan2c864272016-05-18 18:09:17 +02005055 if (symbol->getQualifier().hasLocation())
5056 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005057 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005058 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005059 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005060 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005061 }
John Kessenich140f3df2015-06-26 16:58:36 -06005062 if (symbol->getQualifier().hasSet())
5063 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005064 else if (IsDescriptorResource(symbol->getType())) {
5065 // default to 0
5066 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5067 }
John Kessenich140f3df2015-06-26 16:58:36 -06005068 if (symbol->getQualifier().hasBinding())
5069 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005070 if (symbol->getQualifier().hasAttachment())
5071 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005072 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005073 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005074 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005075 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005076 if (symbol->getQualifier().hasXfbBuffer())
5077 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5078 }
5079
Rex Xu1da878f2016-02-21 20:59:01 +08005080 if (symbol->getType().isImage()) {
5081 std::vector<spv::Decoration> memory;
5082 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5083 for (unsigned int i = 0; i < memory.size(); ++i)
5084 addDecoration(id, memory[i]);
5085 }
5086
John Kessenich140f3df2015-06-26 16:58:36 -06005087 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005088 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005089 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005090 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005091
John Kessenichecba76f2017-01-06 00:34:48 -07005092#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005093 if (builtIn == spv::BuiltInSampleMask) {
5094 spv::Decoration decoration;
5095 // GL_NV_sample_mask_override_coverage extension
5096 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005097 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005098 else
5099 decoration = (spv::Decoration)spv::DecorationMax;
5100 addDecoration(id, decoration);
5101 if (decoration != spv::DecorationMax) {
5102 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5103 }
5104 }
chaoc771d89f2017-01-13 01:10:53 -08005105 else if (builtIn == spv::BuiltInLayer) {
5106 // SPV_NV_viewport_array2 extension
5107 if (symbol->getQualifier().layoutViewportRelative)
5108 {
5109 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5110 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5111 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5112 }
5113 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5114 {
5115 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5116 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5117 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5118 }
5119 }
5120
chaoc6e5acae2016-12-20 13:28:52 -08005121 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005122 addDecoration(id, spv::DecorationPassthroughNV);
5123 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005124 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5125 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005126#endif
5127
John Kessenich140f3df2015-06-26 16:58:36 -06005128 return id;
5129}
5130
John Kessenich55e7d112015-11-15 21:33:39 -07005131// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005132void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5133{
John Kessenich4016e382016-07-15 11:53:56 -06005134 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005135 builder.addDecoration(id, dec);
5136}
5137
John Kessenich55e7d112015-11-15 21:33:39 -07005138// If 'dec' is valid, add a one-operand decoration to an object
5139void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5140{
John Kessenich4016e382016-07-15 11:53:56 -06005141 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005142 builder.addDecoration(id, dec, value);
5143}
5144
5145// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005146void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5147{
John Kessenich4016e382016-07-15 11:53:56 -06005148 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005149 builder.addMemberDecoration(id, (unsigned)member, dec);
5150}
5151
John Kessenich92187592016-02-01 13:45:25 -07005152// If 'dec' is valid, add a one-operand decoration to a struct member
5153void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5154{
John Kessenich4016e382016-07-15 11:53:56 -06005155 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005156 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5157}
5158
John Kessenich55e7d112015-11-15 21:33:39 -07005159// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005160// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005161//
5162// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5163//
5164// Recursively walk the nodes. The nodes form a tree whose leaves are
5165// regular constants, which themselves are trees that createSpvConstant()
5166// recursively walks. So, this function walks the "top" of the tree:
5167// - emit specialization constant-building instructions for specConstant
5168// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005169spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005170{
John Kessenich7cc0e282016-03-20 00:46:02 -06005171 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005172
qining4f4bb812016-04-03 23:55:17 -04005173 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005174 if (! node.getQualifier().specConstant) {
5175 // hand off to the non-spec-constant path
5176 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5177 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005178 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005179 nextConst, false);
5180 }
5181
5182 // We now know we have a specialization constant to build
5183
John Kessenichd94c0032016-05-30 19:29:40 -06005184 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005185 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5186 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5187 std::vector<spv::Id> dimConstId;
5188 for (int dim = 0; dim < 3; ++dim) {
5189 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5190 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5191 if (specConst)
5192 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5193 }
5194 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5195 }
5196
5197 // An AST node labelled as specialization constant should be a symbol node.
5198 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5199 if (auto* sn = node.getAsSymbolNode()) {
5200 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005201 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5202 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5203 // will set the builder into spec constant op instruction generating mode.
5204 sub_tree->traverse(this);
5205 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005206 } else if (auto* const_union_array = &sn->getConstArray()){
5207 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005208 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5209 builder.addName(id, sn->getName().c_str());
5210 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005211 }
5212 }
qining4f4bb812016-04-03 23:55:17 -04005213
5214 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5215 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005216 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005217 exit(1);
5218 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005219}
5220
John Kessenich140f3df2015-06-26 16:58:36 -06005221// Use 'consts' as the flattened glslang source of scalar constants to recursively
5222// build the aggregate SPIR-V constant.
5223//
5224// If there are not enough elements present in 'consts', 0 will be substituted;
5225// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5226//
qining08408382016-03-21 09:51:37 -04005227spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005228{
5229 // vector of constants for SPIR-V
5230 std::vector<spv::Id> spvConsts;
5231
5232 // Type is used for struct and array constants
5233 spv::Id typeId = convertGlslangToSpvType(glslangType);
5234
5235 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005236 glslang::TType elementType(glslangType, 0);
5237 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005238 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005239 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005240 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005241 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005242 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005243 } else if (glslangType.getStruct()) {
5244 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5245 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005246 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005247 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005248 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5249 bool zero = nextConst >= consts.size();
5250 switch (glslangType.getBasicType()) {
5251 case glslang::EbtInt:
5252 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5253 break;
5254 case glslang::EbtUint:
5255 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5256 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005257 case glslang::EbtInt64:
5258 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5259 break;
5260 case glslang::EbtUint64:
5261 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5262 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005263 case glslang::EbtFloat:
5264 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5265 break;
5266 case glslang::EbtDouble:
5267 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5268 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005269#ifdef AMD_EXTENSIONS
5270 case glslang::EbtFloat16:
5271 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5272 break;
5273#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005274 case glslang::EbtBool:
5275 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5276 break;
5277 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005278 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005279 break;
5280 }
5281 ++nextConst;
5282 }
5283 } else {
5284 // we have a non-aggregate (scalar) constant
5285 bool zero = nextConst >= consts.size();
5286 spv::Id scalar = 0;
5287 switch (glslangType.getBasicType()) {
5288 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005289 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005290 break;
5291 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005292 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005294 case glslang::EbtInt64:
5295 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5296 break;
5297 case glslang::EbtUint64:
5298 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5299 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005300 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005301 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005302 break;
5303 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005304 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005305 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005306#ifdef AMD_EXTENSIONS
5307 case glslang::EbtFloat16:
5308 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5309 break;
5310#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005311 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005312 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005313 break;
5314 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005315 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005316 break;
5317 }
5318 ++nextConst;
5319 return scalar;
5320 }
5321
5322 return builder.makeCompositeConstant(typeId, spvConsts);
5323}
5324
John Kessenich7c1aa102015-10-15 13:29:11 -06005325// Return true if the node is a constant or symbol whose reading has no
5326// non-trivial observable cost or effect.
5327bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5328{
5329 // don't know what this is
5330 if (node == nullptr)
5331 return false;
5332
5333 // a constant is safe
5334 if (node->getAsConstantUnion() != nullptr)
5335 return true;
5336
5337 // not a symbol means non-trivial
5338 if (node->getAsSymbolNode() == nullptr)
5339 return false;
5340
5341 // a symbol, depends on what's being read
5342 switch (node->getType().getQualifier().storage) {
5343 case glslang::EvqTemporary:
5344 case glslang::EvqGlobal:
5345 case glslang::EvqIn:
5346 case glslang::EvqInOut:
5347 case glslang::EvqConst:
5348 case glslang::EvqConstReadOnly:
5349 case glslang::EvqUniform:
5350 return true;
5351 default:
5352 return false;
5353 }
qining25262b32016-05-06 17:25:16 -04005354}
John Kessenich7c1aa102015-10-15 13:29:11 -06005355
5356// A node is trivial if it is a single operation with no side effects.
5357// Error on the side of saying non-trivial.
5358// Return true if trivial.
5359bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5360{
5361 if (node == nullptr)
5362 return false;
5363
5364 // symbols and constants are trivial
5365 if (isTrivialLeaf(node))
5366 return true;
5367
5368 // otherwise, it needs to be a simple operation or one or two leaf nodes
5369
5370 // not a simple operation
5371 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5372 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5373 if (binaryNode == nullptr && unaryNode == nullptr)
5374 return false;
5375
5376 // not on leaf nodes
5377 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5378 return false;
5379
5380 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5381 return false;
5382 }
5383
5384 switch (node->getAsOperator()->getOp()) {
5385 case glslang::EOpLogicalNot:
5386 case glslang::EOpConvIntToBool:
5387 case glslang::EOpConvUintToBool:
5388 case glslang::EOpConvFloatToBool:
5389 case glslang::EOpConvDoubleToBool:
5390 case glslang::EOpEqual:
5391 case glslang::EOpNotEqual:
5392 case glslang::EOpLessThan:
5393 case glslang::EOpGreaterThan:
5394 case glslang::EOpLessThanEqual:
5395 case glslang::EOpGreaterThanEqual:
5396 case glslang::EOpIndexDirect:
5397 case glslang::EOpIndexDirectStruct:
5398 case glslang::EOpLogicalXor:
5399 case glslang::EOpAny:
5400 case glslang::EOpAll:
5401 return true;
5402 default:
5403 return false;
5404 }
5405}
5406
5407// Emit short-circuiting code, where 'right' is never evaluated unless
5408// the left side is true (for &&) or false (for ||).
5409spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5410{
5411 spv::Id boolTypeId = builder.makeBoolType();
5412
5413 // emit left operand
5414 builder.clearAccessChain();
5415 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005416 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005417
5418 // Operands to accumulate OpPhi operands
5419 std::vector<spv::Id> phiOperands;
5420 // accumulate left operand's phi information
5421 phiOperands.push_back(leftId);
5422 phiOperands.push_back(builder.getBuildPoint()->getId());
5423
5424 // Make the two kinds of operation symmetric with a "!"
5425 // || => emit "if (! left) result = right"
5426 // && => emit "if ( left) result = right"
5427 //
5428 // TODO: this runtime "not" for || could be avoided by adding functionality
5429 // to 'builder' to have an "else" without an "then"
5430 if (op == glslang::EOpLogicalOr)
5431 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5432
5433 // make an "if" based on the left value
5434 spv::Builder::If ifBuilder(leftId, builder);
5435
5436 // emit right operand as the "then" part of the "if"
5437 builder.clearAccessChain();
5438 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005439 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005440
5441 // accumulate left operand's phi information
5442 phiOperands.push_back(rightId);
5443 phiOperands.push_back(builder.getBuildPoint()->getId());
5444
5445 // finish the "if"
5446 ifBuilder.makeEndIf();
5447
5448 // phi together the two results
5449 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5450}
5451
Rex Xu9d93a232016-05-05 12:30:44 +08005452// Return type Id of the imported set of extended instructions corresponds to the name.
5453// Import this set if it has not been imported yet.
5454spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5455{
5456 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5457 return extBuiltinMap[name];
5458 else {
Rex Xu51596642016-09-21 18:56:12 +08005459 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005460 spv::Id extBuiltins = builder.import(name);
5461 extBuiltinMap[name] = extBuiltins;
5462 return extBuiltins;
5463 }
5464}
5465
John Kessenich140f3df2015-06-26 16:58:36 -06005466}; // end anonymous namespace
5467
5468namespace glslang {
5469
John Kessenich68d78fd2015-07-12 19:28:10 -06005470void GetSpirvVersion(std::string& version)
5471{
John Kessenich9e55f632015-07-15 10:03:39 -06005472 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005473 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005474 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005475 version = buf;
5476}
5477
John Kessenich140f3df2015-06-26 16:58:36 -06005478// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005479void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005480{
5481 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005482 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005483 if (out.fail())
5484 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005485 for (int i = 0; i < (int)spirv.size(); ++i) {
5486 unsigned int word = spirv[i];
5487 out.write((const char*)&word, 4);
5488 }
5489 out.close();
5490}
5491
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005492// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005493void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005494{
5495 std::ofstream out;
5496 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005497 if (out.fail())
5498 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005499 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005500 if (varName != nullptr) {
5501 out << "\t #pragma once" << std::endl;
5502 out << "const uint32_t " << varName << "[] = {" << std::endl;
5503 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005504 const int WORDS_PER_LINE = 8;
5505 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5506 out << "\t";
5507 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5508 const unsigned int word = spirv[i + j];
5509 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5510 if (i + j + 1 < (int)spirv.size()) {
5511 out << ",";
5512 }
5513 }
5514 out << std::endl;
5515 }
Flavio15017db2017-02-15 14:29:33 -08005516 if (varName != nullptr) {
5517 out << "};";
5518 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005519 out.close();
5520}
5521
John Kessenich140f3df2015-06-26 16:58:36 -06005522//
5523// Set up the glslang traversal
5524//
5525void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5526{
Lei Zhang17535f72016-05-04 15:55:59 -04005527 spv::SpvBuildLogger logger;
5528 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005529}
5530
Lei Zhang17535f72016-05-04 15:55:59 -04005531void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005532{
John Kessenich140f3df2015-06-26 16:58:36 -06005533 TIntermNode* root = intermediate.getTreeRoot();
5534
5535 if (root == 0)
5536 return;
5537
5538 glslang::GetThreadPoolAllocator().push();
5539
Lei Zhang17535f72016-05-04 15:55:59 -04005540 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005541 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005542 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005543 it.dumpSpv(spirv);
5544
5545 glslang::GetThreadPoolAllocator().pop();
5546}
5547
5548}; // end namespace glslang