blob: 18ef64f41517028857a96a13581ec34317dcbb2b [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.
John Kessenich56364b62020-03-01 04:51:40 -07003// Copyright (C) 2015-2020 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
Torosdagli06c2eee2020-03-19 11:09:57 -04005// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06008//
John Kessenich927608b2017-01-06 12:34:14 -07009// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060012//
13// Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//
16// Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following
18// disclaimer in the documentation and/or other materials provided
19// with the distribution.
20//
21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22// contributors may be used to endorse or promote products derived
23// from this software without specific prior written permission.
24//
John Kessenich927608b2017-01-06 12:34:14 -070025// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060037
38//
John Kessenich140f3df2015-06-26 16:58:36 -060039// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080047 #include "GLSL.std.450.h"
48 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070049 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080051 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050052 #include "NonSemanticDebugPrintf.h"
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"
Ben Claytonfbe9a232020-06-17 11:17:19 +010059
60// Build-time generated includes
61#include "glslang/build_info.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060094 public:
95 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
96 precision(precision)
97#ifndef GLSLANG_WEB
98 ,
99 noContraction(noContraction),
100 nonUniform(nonUniform)
101#endif
102 { }
103
John Kessenichead86222018-03-28 18:01:20 -0600104 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600105
106#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400107 void addNoContraction(spv::Builder&, spv::Id) const { }
108 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600109#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400110 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
111 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600112 protected:
113 spv::Decoration noContraction;
114 spv::Decoration nonUniform;
115#endif
116
John Kessenichead86222018-03-28 18:01:20 -0600117};
118
119} // namespace
qining4c912612016-04-01 10:35:16 -0400120
John Kessenich140f3df2015-06-26 16:58:36 -0600121//
122// The main holder of information for translating glslang to SPIR-V.
123//
124// Derives from the AST walking base class.
125//
126class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
127public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700128 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
129 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700130 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600131
132 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
133 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
134 void visitConstantUnion(glslang::TIntermConstantUnion*);
135 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
136 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
137 void visitSymbol(glslang::TIntermSymbol* symbol);
138 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
139 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
140 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
141
John Kessenichfca82622016-11-26 13:23:20 -0700142 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700143 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600144
145protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700146 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
147 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
148
Rex Xu17ff3432016-10-14 17:41:45 +0800149 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800150 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600151 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
greg-lunarg639f5462020-11-12 11:10:07 -0700152 spv::Decoration TranslateNonUniformDecoration(const spv::Builder::AccessChain::CoherentFlags& coherentFlags);
Jeff Bolz36831c92018-09-05 10:11:41 -0500153 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
154 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
155 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
156 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100157 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700158 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700159 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
160 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700161 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600162 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600163 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600164 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600166 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
167 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
168 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600169 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600170 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600171 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600172 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600173 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
174 glslang::TLayoutPacking, const glslang::TQualifier&);
175 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
176 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700177 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700178 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800179 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600180 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700181 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700182 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
183 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700184 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
185 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100186 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600187
John Kessenich6fccb3c2016-09-19 16:01:41 -0600188 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600189 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600190 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600191 void makeFunctions(const glslang::TIntermSequence&);
192 void makeGlobalInitializers(const glslang::TIntermSequence&);
Daniel Kochffccefd2020-11-23 15:41:27 -0500193 void collectRayTracingLinkerObjects();
John Kessenich140f3df2015-06-26 16:58:36 -0600194 void visitFunctions(const glslang::TIntermSequence&);
195 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700196 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
197 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600198 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
199 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600200 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
201
John Kessenichead86222018-03-28 18:01:20 -0600202 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
203 glslang::TBasicType typeProxy, bool reduceComparison = true);
204 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
205 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700206 glslang::TBasicType typeProxy,
207 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600208 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
209 glslang::TBasicType typeProxy);
210 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
211 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600212 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700214 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
215 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
216 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
217 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
218 glslang::TBasicType typeProxy);
219 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
220 spv::Id typeId, std::vector<spv::Id>& operands);
221 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
222 glslang::TBasicType typeProxy);
223 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
224 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800225 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600226 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700227 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400228 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700229 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
230 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600231 bool isTrivialLeaf(const glslang::TIntermTyped* node);
232 bool isTrivial(const glslang::TIntermTyped* node);
233 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800234 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400235 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600236 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500237 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600238
John Kessenich121853f2017-05-31 17:11:16 -0600239 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600241 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700242 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600243 int sequenceDepth;
244
Lei Zhang17535f72016-05-04 15:55:59 -0400245 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400246
John Kessenich140f3df2015-06-26 16:58:36 -0600247 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
248 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700249 bool inEntryPoint;
250 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700251 bool linkageOnly; // true when visiting the set of objects in the AST present only for
252 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700253 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600254 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600255 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600256 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500257 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800258 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600259
John Kessenich2f273362015-07-18 22:34:27 -0600260 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700261 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
262 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600263 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700264 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700265 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800266 std::unordered_map<int, std::vector<int>> memberRemapper;
267 // for mapping glslang symbol struct to symbol Id
268 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700270 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600271 // Map pointee types for EbtReference to their forward pointers
272 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600273 // Type forcing, for when SPIR-V wants a different type than the AST,
274 // requiring local translation to and from SPIR-V type on every access.
275 // Maps <builtin-variable-id -> AST-required-type-id>
276 std::unordered_map<spv::Id, spv::Id> forceType;
Daniel Kochffccefd2020-11-23 15:41:27 -0500277
278 // Used later for generating OpTraceKHR/OpExecuteCallableKHR
279 std::unordered_map<unsigned int, glslang::TIntermSymbol *> locationToSymbol[2];
John Kessenich140f3df2015-06-26 16:58:36 -0600280};
281
282//
283// Helper functions for translating glslang representations to SPIR-V enumerants.
284//
285
286// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700287spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600288{
John Kessenich155d3512019-08-08 23:29:20 -0600289#ifdef GLSLANG_WEB
290 return spv::SourceLanguageESSL;
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -0400291#elif defined(GLSLANG_ANGLE)
292 return spv::SourceLanguageGLSL;
John Kessenich155d3512019-08-08 23:29:20 -0600293#endif
294
John Kessenich66e2faf2016-03-12 18:34:36 -0700295 switch (source) {
296 case glslang::EShSourceGlsl:
297 switch (profile) {
298 case ENoProfile:
299 case ECoreProfile:
300 case ECompatibilityProfile:
301 return spv::SourceLanguageGLSL;
302 case EEsProfile:
303 return spv::SourceLanguageESSL;
304 default:
305 return spv::SourceLanguageUnknown;
306 }
307 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600308 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
310 return spv::SourceLanguageUnknown;
311 }
312}
313
314// Translate glslang language (stage) to SPIR-V execution model.
315spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
316{
317 switch (stage) {
318 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600319 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600320 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600321#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
323 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
324 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400325 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
326 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
327 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
328 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
329 case EShLangMiss: return spv::ExecutionModelMissKHR;
330 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700331 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
332 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
333#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600334 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700335 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::ExecutionModelFragment;
337 }
338}
339
John Kessenich140f3df2015-06-26 16:58:36 -0600340// Translate glslang sampler type to SPIR-V dimensionality.
341spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
342{
343 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700344 case glslang::Esd1D: return spv::Dim1D;
345 case glslang::Esd2D: return spv::Dim2D;
346 case glslang::Esd3D: return spv::Dim3D;
347 case glslang::EsdCube: return spv::DimCube;
348 case glslang::EsdRect: return spv::DimRect;
349 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700350 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700352 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::Dim2D;
354 }
355}
356
John Kessenichf6640762016-08-01 19:44:00 -0600357// Translate glslang precision to SPIR-V precision decorations.
358spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600359{
John Kessenichf6640762016-08-01 19:44:00 -0600360 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700361 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600362 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 default:
364 return spv::NoPrecision;
365 }
366}
367
John Kessenichf6640762016-08-01 19:44:00 -0600368// Translate glslang type to SPIR-V precision decorations.
369spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
370{
371 return TranslatePrecisionDecoration(type.getQualifier().precision);
372}
373
John Kessenich140f3df2015-06-26 16:58:36 -0600374// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600375spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600376{
377 if (type.getBasicType() == glslang::EbtBlock) {
378 switch (type.getQualifier().storage) {
379 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600380 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 case glslang::EvqVaryingIn: return spv::DecorationBlock;
382 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600383#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400384 case glslang::EvqPayload: return spv::DecorationBlock;
385 case glslang::EvqPayloadIn: return spv::DecorationBlock;
386 case glslang::EvqHitAttr: return spv::DecorationBlock;
387 case glslang::EvqCallableData: return spv::DecorationBlock;
388 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700389#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600390 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700391 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600392 break;
393 }
394 }
395
John Kessenich4016e382016-07-15 11:53:56 -0600396 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600397}
398
Rex Xu1da878f2016-02-21 20:59:01 +0800399// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700400void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
401 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800402{
Jeff Bolz36831c92018-09-05 10:11:41 -0500403 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600404 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500405 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600406 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500407 memory.push_back(spv::DecorationVolatile);
408 memory.push_back(spv::DecorationCoherent);
409 }
John Kessenich14b85d32018-06-04 15:36:03 -0600410 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600411 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800412 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600413 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800414 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600415 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800416 memory.push_back(spv::DecorationNonReadable);
417}
418
John Kessenich140f3df2015-06-26 16:58:36 -0600419// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700420spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600421{
422 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700423 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600424 case glslang::ElmRowMajor:
425 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700426 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700428 default:
429 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 }
432 } else {
433 switch (type.getBasicType()) {
434 default:
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600436 break;
437 case glslang::EbtBlock:
438 switch (type.getQualifier().storage) {
439 case glslang::EvqUniform:
440 case glslang::EvqBuffer:
441 switch (type.getQualifier().layoutPacking) {
442 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600443 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
444 default:
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600446 }
447 case glslang::EvqVaryingIn:
448 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700449 if (type.getQualifier().isTaskMemory()) {
450 switch (type.getQualifier().layoutPacking) {
451 case glslang::ElpShared: return spv::DecorationGLSLShared;
452 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
453 default: break;
454 }
455 } else {
456 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
457 }
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600459#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400460 case glslang::EvqPayload:
461 case glslang::EvqPayloadIn:
462 case glslang::EvqHitAttr:
463 case glslang::EvqCallableData:
464 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700465 return spv::DecorationMax;
466#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600467 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700468 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600469 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600470 }
471 }
472 }
473}
474
475// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600476// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700477// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800478spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600479{
Rex Xubbceed72016-05-21 09:40:44 +0800480 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700481 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600482 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600483 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700484 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700485 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600486 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600487 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800488 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800489 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800490 }
Rex Xubbceed72016-05-21 09:40:44 +0800491 else
John Kessenich4016e382016-07-15 11:53:56 -0600492 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800493}
494
495// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600496// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800497// should be applied.
498spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
499{
John Kessenichb9197c82019-08-11 07:41:45 -0600500 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600501 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600502#ifndef GLSLANG_WEB
503 else if (qualifier.patch)
504 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700505 else if (qualifier.sample) {
506 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600507 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600508 }
509#endif
510
511 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600512}
513
John Kessenich92187592016-02-01 13:45:25 -0700514// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700515spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600516{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700517 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600518 return spv::DecorationInvariant;
519 else
John Kessenich4016e382016-07-15 11:53:56 -0600520 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600521}
522
qining9220dbb2016-05-04 17:34:38 -0400523// If glslang type is noContraction, return SPIR-V NoContraction decoration.
524spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
525{
John Kessenichb9197c82019-08-11 07:41:45 -0600526#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600527 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400528 return spv::DecorationNoContraction;
529 else
John Kessenichb9197c82019-08-11 07:41:45 -0600530#endif
John Kessenich4016e382016-07-15 11:53:56 -0600531 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400532}
533
John Kessenich5611c6d2018-04-05 11:25:02 -0600534// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
535spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
536{
John Kessenichb9197c82019-08-11 07:41:45 -0600537#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600538 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600539 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600540 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
541 return spv::DecorationNonUniformEXT;
542 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600543#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600544 return spv::DecorationMax;
545}
546
greg-lunarg639f5462020-11-12 11:10:07 -0700547// If lvalue flags contains nonUniform, return SPIR-V NonUniform decoration.
548spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(
549 const spv::Builder::AccessChain::CoherentFlags& coherentFlags)
550{
551#ifndef GLSLANG_WEB
552 if (coherentFlags.isNonUniform()) {
553 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
554 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
555 return spv::DecorationNonUniformEXT;
556 } else
557#endif
558 return spv::DecorationMax;
559}
560
John Kessenichb9197c82019-08-11 07:41:45 -0600561spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
562 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500563{
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600565
566#ifndef GLSLANG_WEB
567 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
568 return mask;
569
Daniel Kochdb32b242020-03-17 20:42:47 -0400570 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500571 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
572 spv::MemoryAccessMakePointerVisibleKHRMask;
573 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400574
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 if (coherentFlags.nonprivate) {
576 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
577 }
578 if (coherentFlags.volatil) {
579 mask = mask | spv::MemoryAccessVolatileMask;
580 }
581 if (mask != spv::MemoryAccessMaskNone) {
582 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
583 }
John Kessenichb9197c82019-08-11 07:41:45 -0600584#endif
585
Jeff Bolz36831c92018-09-05 10:11:41 -0500586 return mask;
587}
588
John Kessenichb9197c82019-08-11 07:41:45 -0600589spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
590 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500591{
Jeff Bolz36831c92018-09-05 10:11:41 -0500592 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600593
594#ifndef GLSLANG_WEB
595 if (!glslangIntermediate->usingVulkanMemoryModel())
596 return mask;
597
Jeff Bolz36831c92018-09-05 10:11:41 -0500598 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400599 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500600 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
601 spv::ImageOperandsMakeTexelVisibleKHRMask;
602 }
603 if (coherentFlags.nonprivate) {
604 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
605 }
606 if (coherentFlags.volatil) {
607 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
608 }
609 if (mask != spv::ImageOperandsMaskNone) {
610 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
611 }
John Kessenichb9197c82019-08-11 07:41:45 -0600612#endif
613
Jeff Bolz36831c92018-09-05 10:11:41 -0500614 return mask;
615}
616
617spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
618{
John Kessenichb9197c82019-08-11 07:41:45 -0600619 spv::Builder::AccessChain::CoherentFlags flags = {};
620#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500621 flags.coherent = type.getQualifier().coherent;
622 flags.devicecoherent = type.getQualifier().devicecoherent;
623 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
624 // shared variables are implicitly workgroupcoherent in GLSL.
625 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
626 type.getQualifier().storage == glslang::EvqShared;
627 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400628 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600629 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500630 // *coherent variables are implicitly nonprivate in GLSL
631 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400632 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600633 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500634 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600635#endif
greg-lunarg639f5462020-11-12 11:10:07 -0700636 flags.nonUniform = type.getQualifier().nonUniform;
Jeff Bolz36831c92018-09-05 10:11:41 -0500637 return flags;
638}
639
John Kessenichb9197c82019-08-11 07:41:45 -0600640spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
641 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500642{
John Kessenichb9197c82019-08-11 07:41:45 -0600643 spv::Scope scope = spv::ScopeMax;
644
645#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600646 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500647 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
648 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
649 } else if (coherentFlags.devicecoherent) {
650 scope = spv::ScopeDevice;
651 } else if (coherentFlags.queuefamilycoherent) {
652 scope = spv::ScopeQueueFamilyKHR;
653 } else if (coherentFlags.workgroupcoherent) {
654 scope = spv::ScopeWorkgroup;
655 } else if (coherentFlags.subgroupcoherent) {
656 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400657 } else if (coherentFlags.shadercallcoherent) {
658 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500659 }
660 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
661 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
662 }
John Kessenichb9197c82019-08-11 07:41:45 -0600663#endif
664
Jeff Bolz36831c92018-09-05 10:11:41 -0500665 return scope;
666}
667
David Netoa901ffe2016-06-08 14:11:40 +0100668// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
669// associated capabilities when required. For some built-in variables, a capability
670// is generated only when using the variable in an executable instruction, but not when
671// just declaring a struct member variable with it. This is true for PointSize,
672// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700673spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
674 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600675{
676 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700677 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600678#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600679 // Defer adding the capability until the built-in is actually used.
680 if (! memberDeclaration) {
681 switch (glslangIntermediate->getStage()) {
682 case EShLangGeometry:
683 builder.addCapability(spv::CapabilityGeometryPointSize);
684 break;
685 case EShLangTessControl:
686 case EShLangTessEvaluation:
687 builder.addCapability(spv::CapabilityTessellationPointSize);
688 break;
689 default:
690 break;
691 }
John Kessenich92187592016-02-01 13:45:25 -0700692 }
John Kessenich155d3512019-08-08 23:29:20 -0600693#endif
John Kessenich92187592016-02-01 13:45:25 -0700694 return spv::BuiltInPointSize;
695
John Kessenicha28f7a72019-08-06 07:00:58 -0600696 case glslang::EbvPosition: return spv::BuiltInPosition;
697 case glslang::EbvVertexId: return spv::BuiltInVertexId;
698 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
699 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
700 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
701
702 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
703 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
704 case glslang::EbvFace: return spv::BuiltInFrontFacing;
705 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
706
John Kessenich3dd1ce52019-10-17 07:08:40 -0600707 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
708 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
709 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
710 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
711 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
712 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
713
John Kessenicha28f7a72019-08-06 07:00:58 -0600714#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600715 // These *Distance capabilities logically belong here, but if the member is declared and
716 // then never used, consumers of SPIR-V prefer the capability not be declared.
717 // They are now generated when used, rather than here when declared.
718 // Potentially, the specification should be more clear what the minimum
719 // use needed is to trigger the capability.
720 //
John Kessenich92187592016-02-01 13:45:25 -0700721 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100722 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800723 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700724 return spv::BuiltInClipDistance;
725
726 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100727 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800728 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700729 return spv::BuiltInCullDistance;
730
731 case glslang::EbvViewportIndex:
David Netofb53f832020-11-12 15:00:16 -0500732 if (glslangIntermediate->getStage() == EShLangGeometry ||
733 glslangIntermediate->getStage() == EShLangFragment) {
734 builder.addCapability(spv::CapabilityMultiViewport);
735 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600736 if (glslangIntermediate->getStage() == EShLangVertex ||
737 glslangIntermediate->getStage() == EShLangTessControl ||
738 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800739
Sidney Just56350ca2020-11-02 11:27:40 -0800740 if (builder.getSpvVersion() < spv::Spv_1_5) {
741 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
742 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
743 }
744 else
745 builder.addCapability(spv::CapabilityShaderViewportIndex);
Rex Xu5e317ff2017-03-16 23:02:39 +0800746 }
John Kessenich92187592016-02-01 13:45:25 -0700747 return spv::BuiltInViewportIndex;
748
John Kessenich5e801132016-02-15 11:09:46 -0700749 case glslang::EbvSampleId:
750 builder.addCapability(spv::CapabilitySampleRateShading);
751 return spv::BuiltInSampleId;
752
753 case glslang::EbvSamplePosition:
754 builder.addCapability(spv::CapabilitySampleRateShading);
755 return spv::BuiltInSamplePosition;
756
757 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700758 return spv::BuiltInSampleMask;
759
John Kessenich78a45572016-07-08 14:05:15 -0600760 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700761 if (glslangIntermediate->getStage() == EShLangMeshNV) {
762 return spv::BuiltInLayer;
763 }
David Netofb53f832020-11-12 15:00:16 -0500764 if (glslangIntermediate->getStage() == EShLangGeometry ||
765 glslangIntermediate->getStage() == EShLangFragment) {
766 builder.addCapability(spv::CapabilityGeometry);
767 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600768 if (glslangIntermediate->getStage() == EShLangVertex ||
769 glslangIntermediate->getStage() == EShLangTessControl ||
770 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800771
Sidney Just56350ca2020-11-02 11:27:40 -0800772 if (builder.getSpvVersion() < spv::Spv_1_5) {
773 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
774 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
775 } else
776 builder.addCapability(spv::CapabilityShaderLayer);
Rex Xu5e317ff2017-03-16 23:02:39 +0800777 }
John Kessenich78a45572016-07-08 14:05:15 -0600778 return spv::BuiltInLayer;
779
John Kessenichda581a22015-10-14 14:10:30 -0600780 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600781 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800782 builder.addCapability(spv::CapabilityDrawParameters);
783 return spv::BuiltInBaseVertex;
784
John Kessenichda581a22015-10-14 14:10:30 -0600785 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600786 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800787 builder.addCapability(spv::CapabilityDrawParameters);
788 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200789
John Kessenichda581a22015-10-14 14:10:30 -0600790 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600791 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800792 builder.addCapability(spv::CapabilityDrawParameters);
793 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200794
795 case glslang::EbvPrimitiveId:
796 if (glslangIntermediate->getStage() == EShLangFragment)
797 builder.addCapability(spv::CapabilityGeometry);
798 return spv::BuiltInPrimitiveId;
799
Rex Xu37cdcee2017-06-29 17:46:34 +0800800 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800801 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
802 builder.addCapability(spv::CapabilityStencilExportEXT);
803 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800804
Chowa315b562020-07-02 15:50:36 +0800805 case glslang::EbvShadingRateKHR:
806 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
807 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
808 return spv::BuiltInShadingRateKHR;
809
810 case glslang::EbvPrimitiveShadingRateKHR:
811 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
812 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
813 return spv::BuiltInPrimitiveShadingRateKHR;
814
John Kessenich140f3df2015-06-26 16:58:36 -0600815 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600816 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
817 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
818 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
819 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600820 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800821
Rex Xu574ab042016-04-14 16:53:07 +0800822 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800823 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800824 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
825 return spv::BuiltInSubgroupSize;
826
Rex Xu574ab042016-04-14 16:53:07 +0800827 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800828 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800829 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
830 return spv::BuiltInSubgroupLocalInvocationId;
831
Rex Xu574ab042016-04-14 16:53:07 +0800832 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800833 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
834 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600835 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800836
Rex Xu574ab042016-04-14 16:53:07 +0800837 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800838 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
839 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600840 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800841
Rex Xu574ab042016-04-14 16:53:07 +0800842 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800843 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
844 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600845 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800846
Rex Xu574ab042016-04-14 16:53:07 +0800847 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800848 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
849 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600850 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800851
Rex Xu574ab042016-04-14 16:53:07 +0800852 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800853 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
854 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600855 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800856
John Kessenich66011cb2018-03-06 16:12:04 -0700857 case glslang::EbvNumSubgroups:
858 builder.addCapability(spv::CapabilityGroupNonUniform);
859 return spv::BuiltInNumSubgroups;
860
861 case glslang::EbvSubgroupID:
862 builder.addCapability(spv::CapabilityGroupNonUniform);
863 return spv::BuiltInSubgroupId;
864
865 case glslang::EbvSubgroupSize2:
866 builder.addCapability(spv::CapabilityGroupNonUniform);
867 return spv::BuiltInSubgroupSize;
868
869 case glslang::EbvSubgroupInvocation2:
870 builder.addCapability(spv::CapabilityGroupNonUniform);
871 return spv::BuiltInSubgroupLocalInvocationId;
872
873 case glslang::EbvSubgroupEqMask2:
874 builder.addCapability(spv::CapabilityGroupNonUniform);
875 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
876 return spv::BuiltInSubgroupEqMask;
877
878 case glslang::EbvSubgroupGeMask2:
879 builder.addCapability(spv::CapabilityGroupNonUniform);
880 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
881 return spv::BuiltInSubgroupGeMask;
882
883 case glslang::EbvSubgroupGtMask2:
884 builder.addCapability(spv::CapabilityGroupNonUniform);
885 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
886 return spv::BuiltInSubgroupGtMask;
887
888 case glslang::EbvSubgroupLeMask2:
889 builder.addCapability(spv::CapabilityGroupNonUniform);
890 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
891 return spv::BuiltInSubgroupLeMask;
892
893 case glslang::EbvSubgroupLtMask2:
894 builder.addCapability(spv::CapabilityGroupNonUniform);
895 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
896 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600897
Rex Xu17ff3432016-10-14 17:41:45 +0800898 case glslang::EbvBaryCoordNoPersp:
899 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
900 return spv::BuiltInBaryCoordNoPerspAMD;
901
902 case glslang::EbvBaryCoordNoPerspCentroid:
903 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
904 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
905
906 case glslang::EbvBaryCoordNoPerspSample:
907 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
908 return spv::BuiltInBaryCoordNoPerspSampleAMD;
909
910 case glslang::EbvBaryCoordSmooth:
911 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
912 return spv::BuiltInBaryCoordSmoothAMD;
913
914 case glslang::EbvBaryCoordSmoothCentroid:
915 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
916 return spv::BuiltInBaryCoordSmoothCentroidAMD;
917
918 case glslang::EbvBaryCoordSmoothSample:
919 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
920 return spv::BuiltInBaryCoordSmoothSampleAMD;
921
922 case glslang::EbvBaryCoordPullModel:
923 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
924 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800925
John Kessenich6c8aaac2017-02-27 01:20:51 -0700926 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600927 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700928 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700929 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700930
931 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600932 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700933 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700934 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700935
Daniel Koch5154db52018-11-26 10:01:58 -0500936 case glslang::EbvFragSizeEXT:
937 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
938 builder.addCapability(spv::CapabilityFragmentDensityEXT);
939 return spv::BuiltInFragSizeEXT;
940
941 case glslang::EbvFragInvocationCountEXT:
942 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
943 builder.addCapability(spv::CapabilityFragmentDensityEXT);
944 return spv::BuiltInFragInvocationCountEXT;
945
chaoc771d89f2017-01-13 01:10:53 -0800946 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800947 if (!memberDeclaration) {
948 builder.addExtension(spv::E_SPV_NV_viewport_array2);
949 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
950 }
chaoc771d89f2017-01-13 01:10:53 -0800951 return spv::BuiltInViewportMaskNV;
952 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800953 if (!memberDeclaration) {
954 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
955 builder.addCapability(spv::CapabilityShaderStereoViewNV);
956 }
chaoc771d89f2017-01-13 01:10:53 -0800957 return spv::BuiltInSecondaryPositionNV;
958 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800959 if (!memberDeclaration) {
960 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
961 builder.addCapability(spv::CapabilityShaderStereoViewNV);
962 }
chaoc771d89f2017-01-13 01:10:53 -0800963 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800964 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800965 if (!memberDeclaration) {
966 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
967 builder.addCapability(spv::CapabilityPerViewAttributesNV);
968 }
chaocdf3956c2017-02-14 14:52:34 -0800969 return spv::BuiltInPositionPerViewNV;
970 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800971 if (!memberDeclaration) {
972 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
973 builder.addCapability(spv::CapabilityPerViewAttributesNV);
974 }
chaocdf3956c2017-02-14 14:52:34 -0800975 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700976 case glslang::EbvFragFullyCoveredNV:
977 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
978 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
979 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700980 case glslang::EbvFragmentSizeNV:
981 builder.addExtension(spv::E_SPV_NV_shading_rate);
982 builder.addCapability(spv::CapabilityShadingRateNV);
983 return spv::BuiltInFragmentSizeNV;
984 case glslang::EbvInvocationsPerPixelNV:
985 builder.addExtension(spv::E_SPV_NV_shading_rate);
986 builder.addCapability(spv::CapabilityShadingRateNV);
987 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700988
Daniel Koch593a4e02019-05-27 16:46:31 -0400989 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400990 case glslang::EbvLaunchId:
991 return spv::BuiltInLaunchIdKHR;
992 case glslang::EbvLaunchSize:
993 return spv::BuiltInLaunchSizeKHR;
994 case glslang::EbvWorldRayOrigin:
995 return spv::BuiltInWorldRayOriginKHR;
996 case glslang::EbvWorldRayDirection:
997 return spv::BuiltInWorldRayDirectionKHR;
998 case glslang::EbvObjectRayOrigin:
999 return spv::BuiltInObjectRayOriginKHR;
1000 case glslang::EbvObjectRayDirection:
1001 return spv::BuiltInObjectRayDirectionKHR;
1002 case glslang::EbvRayTmin:
1003 return spv::BuiltInRayTminKHR;
1004 case glslang::EbvRayTmax:
1005 return spv::BuiltInRayTmaxKHR;
1006 case glslang::EbvInstanceCustomIndex:
1007 return spv::BuiltInInstanceCustomIndexKHR;
1008 case glslang::EbvHitT:
1009 return spv::BuiltInHitTKHR;
1010 case glslang::EbvHitKind:
1011 return spv::BuiltInHitKindKHR;
1012 case glslang::EbvObjectToWorld:
1013 case glslang::EbvObjectToWorld3x4:
1014 return spv::BuiltInObjectToWorldKHR;
1015 case glslang::EbvWorldToObject:
1016 case glslang::EbvWorldToObject3x4:
1017 return spv::BuiltInWorldToObjectKHR;
1018 case glslang::EbvIncomingRayFlags:
1019 return spv::BuiltInIncomingRayFlagsKHR;
1020 case glslang::EbvGeometryIndex:
1021 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -04001022
1023 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -07001024 case glslang::EbvBaryCoordNV:
1025 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1026 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1027 return spv::BuiltInBaryCoordNV;
1028 case glslang::EbvBaryCoordNoPerspNV:
1029 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1030 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1031 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001032
1033 // mesh shaders
1034 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001035 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001036 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001037 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001038 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001039 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001040 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001041 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001042 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001043 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001044 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001045 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001046 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001047 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001048 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001049 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001050
1051 // sm builtins
1052 case glslang::EbvWarpsPerSM:
1053 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1054 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1055 return spv::BuiltInWarpsPerSMNV;
1056 case glslang::EbvSMCount:
1057 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1058 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1059 return spv::BuiltInSMCountNV;
1060 case glslang::EbvWarpID:
1061 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1062 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1063 return spv::BuiltInWarpIDNV;
1064 case glslang::EbvSMID:
1065 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1066 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1067 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001068#endif
1069
Rex Xu3e783f92017-02-22 16:44:48 +08001070 default:
1071 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001072 }
1073}
1074
Rex Xufc618912015-09-09 16:42:49 +08001075// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001076spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001077{
1078 assert(type.getBasicType() == glslang::EbtSampler);
1079
John Kessenichb9197c82019-08-11 07:41:45 -06001080#ifdef GLSLANG_WEB
1081 return spv::ImageFormatUnknown;
1082#endif
1083
John Kessenich5d0fa972016-02-15 11:57:00 -07001084 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001085 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001086 case glslang::ElfRg32f:
1087 case glslang::ElfRg16f:
1088 case glslang::ElfR11fG11fB10f:
1089 case glslang::ElfR16f:
1090 case glslang::ElfRgba16:
1091 case glslang::ElfRgb10A2:
1092 case glslang::ElfRg16:
1093 case glslang::ElfRg8:
1094 case glslang::ElfR16:
1095 case glslang::ElfR8:
1096 case glslang::ElfRgba16Snorm:
1097 case glslang::ElfRg16Snorm:
1098 case glslang::ElfRg8Snorm:
1099 case glslang::ElfR16Snorm:
1100 case glslang::ElfR8Snorm:
1101
1102 case glslang::ElfRg32i:
1103 case glslang::ElfRg16i:
1104 case glslang::ElfRg8i:
1105 case glslang::ElfR16i:
1106 case glslang::ElfR8i:
1107
1108 case glslang::ElfRgb10a2ui:
1109 case glslang::ElfRg32ui:
1110 case glslang::ElfRg16ui:
1111 case glslang::ElfRg8ui:
1112 case glslang::ElfR16ui:
1113 case glslang::ElfR8ui:
1114 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1115 break;
1116
Tobski8c1a3a02020-11-04 16:24:23 +00001117 case glslang::ElfR64ui:
1118 case glslang::ElfR64i:
1119 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
1120 builder.addCapability(spv::CapabilityInt64ImageEXT);
John Kessenich5d0fa972016-02-15 11:57:00 -07001121 default:
1122 break;
1123 }
1124
1125 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001126 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001127 case glslang::ElfNone: return spv::ImageFormatUnknown;
1128 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1129 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1130 case glslang::ElfR32f: return spv::ImageFormatR32f;
1131 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1132 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1133 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1134 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1135 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1136 case glslang::ElfR16f: return spv::ImageFormatR16f;
1137 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1138 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1139 case glslang::ElfRg16: return spv::ImageFormatRg16;
1140 case glslang::ElfRg8: return spv::ImageFormatRg8;
1141 case glslang::ElfR16: return spv::ImageFormatR16;
1142 case glslang::ElfR8: return spv::ImageFormatR8;
1143 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1144 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1145 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1146 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1147 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1148 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1149 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1150 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1151 case glslang::ElfR32i: return spv::ImageFormatR32i;
1152 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1153 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1154 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1155 case glslang::ElfR16i: return spv::ImageFormatR16i;
1156 case glslang::ElfR8i: return spv::ImageFormatR8i;
1157 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1158 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1159 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1160 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1161 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1162 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1163 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1164 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1165 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1166 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
Tobski8c1a3a02020-11-04 16:24:23 +00001167 case glslang::ElfR64ui: return spv::ImageFormatR64ui;
1168 case glslang::ElfR64i: return spv::ImageFormatR64i;
John Kessenich4016e382016-07-15 11:53:56 -06001169 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001170 }
1171}
1172
John Kessenich8985fc92020-03-03 10:25:07 -07001173spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1174 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001175{
John Kesseniche18fd202018-01-30 11:01:39 -07001176 if (selectionNode.getFlatten())
1177 return spv::SelectionControlFlattenMask;
1178 if (selectionNode.getDontFlatten())
1179 return spv::SelectionControlDontFlattenMask;
1180 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001181}
1182
John Kessenich8985fc92020-03-03 10:25:07 -07001183spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1184 const
steve-lunargf1709e72017-05-02 20:14:50 -06001185{
John Kesseniche18fd202018-01-30 11:01:39 -07001186 if (switchNode.getFlatten())
1187 return spv::SelectionControlFlattenMask;
1188 if (switchNode.getDontFlatten())
1189 return spv::SelectionControlDontFlattenMask;
1190 return spv::SelectionControlMaskNone;
1191}
1192
John Kessenicha2858d92018-01-31 08:11:18 -07001193// return a non-0 dependency if the dependency argument must be set
1194spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001195 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001196{
1197 spv::LoopControlMask control = spv::LoopControlMaskNone;
1198
1199 if (loopNode.getDontUnroll())
1200 control = control | spv::LoopControlDontUnrollMask;
1201 if (loopNode.getUnroll())
1202 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001203 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001204 control = control | spv::LoopControlDependencyInfiniteMask;
1205 else if (loopNode.getLoopDependency() > 0) {
1206 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001207 operands.push_back((unsigned int)loopNode.getLoopDependency());
1208 }
1209 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1210 if (loopNode.getMinIterations() > 0) {
1211 control = control | spv::LoopControlMinIterationsMask;
1212 operands.push_back(loopNode.getMinIterations());
1213 }
1214 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1215 control = control | spv::LoopControlMaxIterationsMask;
1216 operands.push_back(loopNode.getMaxIterations());
1217 }
1218 if (loopNode.getIterationMultiple() > 1) {
1219 control = control | spv::LoopControlIterationMultipleMask;
1220 operands.push_back(loopNode.getIterationMultiple());
1221 }
1222 if (loopNode.getPeelCount() > 0) {
1223 control = control | spv::LoopControlPeelCountMask;
1224 operands.push_back(loopNode.getPeelCount());
1225 }
1226 if (loopNode.getPartialCount() > 0) {
1227 control = control | spv::LoopControlPartialCountMask;
1228 operands.push_back(loopNode.getPartialCount());
1229 }
John Kessenicha2858d92018-01-31 08:11:18 -07001230 }
John Kesseniche18fd202018-01-30 11:01:39 -07001231
1232 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001233}
1234
John Kessenicha5c5fb62017-05-05 05:09:58 -06001235// Translate glslang type to SPIR-V storage class.
1236spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1237{
Torosdagli06c2eee2020-03-19 11:09:57 -04001238 if (type.getBasicType() == glslang::EbtRayQuery)
Daniel Kochffccefd2020-11-23 15:41:27 -05001239 return spv::StorageClassPrivate;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001240 if (type.getQualifier().isPipeInput())
1241 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001242 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001243 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001244
1245 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001246 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001247 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001248 return spv::StorageClassAtomicCounter;
1249 if (type.containsOpaque())
1250 return spv::StorageClassUniformConstant;
1251 }
1252
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001253 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001254 type.getQualifier().isShaderRecord()) {
1255 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001256 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001257
John Kessenichbed4e4f2017-09-08 02:38:07 -06001258 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001259 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001260 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001261 }
1262
1263 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001264 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001265 return spv::StorageClassPushConstant;
1266 if (type.getBasicType() == glslang::EbtBlock)
1267 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001268 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001269 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001270
1271 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001272 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1273 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1274 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001275 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001276#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001277 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1278 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1279 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1280 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1281 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001282#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001283 default:
1284 assert(0);
1285 break;
1286 }
1287
1288 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001289}
1290
John Kessenich5611c6d2018-04-05 11:25:02 -06001291// Add capabilities pertaining to how an array is indexed.
1292void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1293 const glslang::TType& indexType)
1294{
John Kessenichb9197c82019-08-11 07:41:45 -06001295#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001296 if (indexType.getQualifier().isNonUniform()) {
1297 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001298 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001299 if (baseType.getBasicType() == glslang::EbtSampler) {
1300 if (baseType.getQualifier().hasAttachment())
1301 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001302 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001303 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001304 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001305 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1306 else if (baseType.isImage())
1307 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1308 else if (baseType.isTexture())
1309 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1310 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1311 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1312 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1313 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1314 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1315 }
1316 } else {
1317 // assume a dynamically uniform index
1318 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001319 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001320 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001321 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001322 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001323 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001324 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001325 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001326 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001327 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001328 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001329 }
1330 }
John Kessenichb9197c82019-08-11 07:41:45 -06001331#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001332}
1333
qining25262b32016-05-06 17:25:16 -04001334// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001335// descriptor set.
1336bool IsDescriptorResource(const glslang::TType& type)
1337{
John Kessenichf7497e22016-03-08 21:36:22 -07001338 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001339 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001340 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001341 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001342 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001343
1344 // non block...
1345 // basically samplerXXX/subpass/sampler/texture are all included
1346 // if they are the global-scope-class, not the function parameter
1347 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001348 if (type.getBasicType() == glslang::EbtSampler ||
1349 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001350 return type.getQualifier().isUniformOrBuffer();
1351
1352 // None of the above.
1353 return false;
1354}
1355
John Kesseniche0b6cad2015-12-24 10:30:13 -07001356void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1357{
1358 if (child.layoutMatrix == glslang::ElmNone)
1359 child.layoutMatrix = parent.layoutMatrix;
1360
1361 if (parent.invariant)
1362 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001363 if (parent.flat)
1364 child.flat = true;
1365 if (parent.centroid)
1366 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001367#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001368 if (parent.nopersp)
1369 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001370 if (parent.explicitInterp)
1371 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001372 if (parent.perPrimitiveNV)
1373 child.perPrimitiveNV = true;
1374 if (parent.perViewNV)
1375 child.perViewNV = true;
1376 if (parent.perTaskNV)
1377 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001378 if (parent.patch)
1379 child.patch = true;
1380 if (parent.sample)
1381 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001382 if (parent.coherent)
1383 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001384 if (parent.devicecoherent)
1385 child.devicecoherent = true;
1386 if (parent.queuefamilycoherent)
1387 child.queuefamilycoherent = true;
1388 if (parent.workgroupcoherent)
1389 child.workgroupcoherent = true;
1390 if (parent.subgroupcoherent)
1391 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001392 if (parent.shadercallcoherent)
1393 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001394 if (parent.nonprivate)
1395 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001396 if (parent.volatil)
1397 child.volatil = true;
1398 if (parent.restrict)
1399 child.restrict = true;
1400 if (parent.readonly)
1401 child.readonly = true;
1402 if (parent.writeonly)
1403 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001404#endif
greg-lunarg639f5462020-11-12 11:10:07 -07001405 if (parent.nonUniform)
1406 child.nonUniform = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001407}
1408
John Kessenichf2b7f332016-09-01 17:05:23 -06001409bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001410{
John Kessenich7b9fa252016-01-21 18:56:57 -07001411 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001412 // - struct members might inherit from a struct declaration
1413 // (note that non-block structs don't explicitly inherit,
1414 // only implicitly, meaning no decoration involved)
1415 // - affect decorations on the struct members
1416 // (note smooth does not, and expecting something like volatile
1417 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001418 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001419 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001420}
1421
John Kessenich140f3df2015-06-26 16:58:36 -06001422//
1423// Implement the TGlslangToSpvTraverser class.
1424//
1425
John Kessenich8985fc92020-03-03 10:25:07 -07001426TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1427 const glslang::TIntermediate* glslangIntermediate,
1428 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1429 TIntermTraverser(true, false, true),
1430 options(options),
1431 shaderEntry(nullptr), currentFunction(nullptr),
1432 sequenceDepth(0), logger(buildLogger),
1433 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1434 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1435 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001436 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1437 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001438{
1439 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1440
1441 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001442 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1443 glslangIntermediate->getVersion());
1444
John Kessenich121853f2017-05-31 17:11:16 -06001445 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001446 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001447 builder.setSourceFile(glslangIntermediate->getSourceFile());
1448
1449 // Set the source shader's text. If for SPV version 1.0, include
1450 // a preamble in comments stating the OpModuleProcessed instructions.
1451 // Otherwise, emit those as actual instructions.
1452 std::string text;
1453 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1454 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001455 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001456 text.append("// OpModuleProcessed ");
1457 text.append(processes[p]);
1458 text.append("\n");
1459 } else
1460 builder.addModuleProcessed(processes[p]);
1461 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001462 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001463 text.append("#line 1\n");
1464 text.append(glslangIntermediate->getSourceText());
1465 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001466 // Pass name and text for all included files
1467 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1468 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1469 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001470 }
John Kessenich140f3df2015-06-26 16:58:36 -06001471 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001472
1473 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1474 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1475
1476 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1477 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001478 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001479 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001480 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001481 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001482 memoryModel = spv::MemoryModelVulkanKHR;
1483 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001484 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001485 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001486 builder.setMemoryModel(addressingModel, memoryModel);
1487
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001488 if (glslangIntermediate->usingVariablePointers()) {
1489 builder.addCapability(spv::CapabilityVariablePointers);
1490 }
1491
John Kessenicheee9d532016-09-19 18:09:30 -06001492 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1493 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001494
1495 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001496 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1497 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001498 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001499
1500 // Add the top-level modes for this shader.
1501
John Kessenich92187592016-02-01 13:45:25 -07001502 if (glslangIntermediate->getXfbMode()) {
1503 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001504 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001505 }
John Kessenich140f3df2015-06-26 16:58:36 -06001506
alelenv59216d52020-05-21 04:38:41 -07001507 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
Daniel Kochffccefd2020-11-23 15:41:27 -05001508 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingKHR);
alelenv75de1962020-04-08 21:09:20 -07001509 }
1510
John Kessenich140f3df2015-06-26 16:58:36 -06001511 unsigned int mode;
1512 switch (glslangIntermediate->getStage()) {
1513 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001514 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001515 break;
1516
John Kessenicha28f7a72019-08-06 07:00:58 -06001517 case EShLangFragment:
1518 builder.addCapability(spv::CapabilityShader);
1519 if (glslangIntermediate->getPixelCenterInteger())
1520 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1521
1522 if (glslangIntermediate->getOriginUpperLeft())
1523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1524 else
1525 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1526
1527 if (glslangIntermediate->getEarlyFragmentTests())
1528 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1529
1530 if (glslangIntermediate->getPostDepthCoverage()) {
1531 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1532 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1533 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1534 }
1535
John Kessenichb9197c82019-08-11 07:41:45 -06001536 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1537 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1538
1539#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001540
John Kessenicha28f7a72019-08-06 07:00:58 -06001541 switch(glslangIntermediate->getDepth()) {
1542 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1543 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1544 default: mode = spv::ExecutionModeMax; break;
1545 }
1546 if (mode != spv::ExecutionModeMax)
1547 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001548 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001549 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1550 break;
1551 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1552 break;
1553 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1554 break;
1555 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1556 break;
1557 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1558 break;
1559 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1560 break;
1561 default: mode = spv::ExecutionModeMax;
1562 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001563 }
1564 if (mode != spv::ExecutionModeMax) {
1565 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1566 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1567 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1568 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1569 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1570 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1571 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1572 } else {
1573 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1574 }
1575 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1576 }
John Kessenichb9197c82019-08-11 07:41:45 -06001577#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001578 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001579
John Kessenicha28f7a72019-08-06 07:00:58 -06001580 case EShLangCompute:
1581 builder.addCapability(spv::CapabilityShader);
1582 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1583 glslangIntermediate->getLocalSize(1),
1584 glslangIntermediate->getLocalSize(2));
1585 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1586 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1587 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1588 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1589 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1590 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1591 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1592 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1593 }
1594 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001595#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001596 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001597 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001598 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001599
steve-lunarge7412492017-03-23 11:56:07 -06001600 glslang::TLayoutGeometry primitive;
1601
1602 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001603 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1604 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001605 primitive = glslangIntermediate->getOutputPrimitive();
1606 } else {
1607 primitive = glslangIntermediate->getInputPrimitive();
1608 }
1609
1610 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001611 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1612 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1613 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001614 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001615 }
John Kessenich4016e382016-07-15 11:53:56 -06001616 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001617 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1618
John Kesseniche6903322015-10-13 16:29:02 -06001619 switch (glslangIntermediate->getVertexSpacing()) {
1620 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1621 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1622 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001623 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001624 }
John Kessenich4016e382016-07-15 11:53:56 -06001625 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001626 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1627
1628 switch (glslangIntermediate->getVertexOrder()) {
1629 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1630 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001631 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001632 }
John Kessenich4016e382016-07-15 11:53:56 -06001633 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001634 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1635
1636 if (glslangIntermediate->getPointMode())
1637 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001638 break;
1639
1640 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001641 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001642 switch (glslangIntermediate->getInputPrimitive()) {
1643 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1644 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1645 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001646 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001647 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001648 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001649 }
John Kessenich4016e382016-07-15 11:53:56 -06001650 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001651 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001652
John Kessenich140f3df2015-06-26 16:58:36 -06001653 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1654
1655 switch (glslangIntermediate->getOutputPrimitive()) {
1656 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1657 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1658 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001659 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001660 }
John Kessenich4016e382016-07-15 11:53:56 -06001661 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001662 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1663 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1664 break;
1665
Daniel Kochdb32b242020-03-17 20:42:47 -04001666 case EShLangRayGen:
1667 case EShLangIntersect:
1668 case EShLangAnyHit:
1669 case EShLangClosestHit:
1670 case EShLangMiss:
1671 case EShLangCallable:
1672 {
1673 auto& extensions = glslangIntermediate->getRequestedExtensions();
1674 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
Daniel Kochffccefd2020-11-23 15:41:27 -05001675 builder.addCapability(spv::CapabilityRayTracingKHR);
Daniel Kochdb32b242020-03-17 20:42:47 -04001676 builder.addExtension("SPV_KHR_ray_tracing");
1677 }
1678 else {
1679 builder.addCapability(spv::CapabilityRayTracingNV);
1680 builder.addExtension("SPV_NV_ray_tracing");
1681 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001682 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001683 }
Chao Chen3c366992018-09-19 11:41:59 -07001684 case EShLangTaskNV:
1685 case EShLangMeshNV:
1686 builder.addCapability(spv::CapabilityMeshShadingNV);
1687 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1688 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1689 glslangIntermediate->getLocalSize(1),
1690 glslangIntermediate->getLocalSize(2));
1691 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001692 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1693 glslangIntermediate->getVertices());
1694 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1695 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001696
1697 switch (glslangIntermediate->getOutputPrimitive()) {
1698 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1699 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1700 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1701 default: mode = spv::ExecutionModeMax; break;
1702 }
1703 if (mode != spv::ExecutionModeMax)
1704 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1705 }
1706 break;
1707#endif
1708
John Kessenich140f3df2015-06-26 16:58:36 -06001709 default:
1710 break;
1711 }
John Kessenich140f3df2015-06-26 16:58:36 -06001712}
1713
John Kessenichfca82622016-11-26 13:23:20 -07001714// Finish creating SPV, after the traversal is complete.
1715void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001716{
John Kessenichf04c51b2018-08-03 15:56:12 -06001717 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001718 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001719 builder.setBuildPoint(shaderEntry->getLastBlock());
1720 builder.leaveFunction();
1721 }
1722
John Kessenich7ba63412015-12-20 17:37:07 -07001723 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001724 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1725 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001726
David Neto8c3d5b42019-10-21 14:50:31 -04001727 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001728 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001729 // Note: WebGPU code generation must have the opportunity to aggressively
1730 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001731 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001732}
1733
John Kessenichfca82622016-11-26 13:23:20 -07001734// Write the SPV into 'out'.
1735void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001736{
John Kessenichfca82622016-11-26 13:23:20 -07001737 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001738}
1739
1740//
1741// Implement the traversal functions.
1742//
1743// Return true from interior nodes to have the external traversal
1744// continue on to children. Return false if children were
1745// already processed.
1746//
1747
1748//
qining25262b32016-05-06 17:25:16 -04001749// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001750// - uniform/input reads
1751// - output writes
1752// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1753// - something simple that degenerates into the last bullet
1754//
1755void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1756{
qining75d1d802016-04-06 14:42:01 -04001757 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001758 if (symbol->getType().isStruct())
1759 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1760
qining75d1d802016-04-06 14:42:01 -04001761 if (symbol->getType().getQualifier().isSpecConstant())
1762 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1763
Rex Xuf6e0fe82020-10-23 22:54:35 +08001764#ifdef ENABLE_HLSL
1765 // Skip symbol handling if it is string-typed
1766 if (symbol->getBasicType() == glslang::EbtString)
1767 return;
1768#endif
1769
John Kessenich140f3df2015-06-26 16:58:36 -06001770 // getSymbolId() will set up all the IO decorations on the first call.
1771 // Formal function parameters were mapped during makeFunctions().
1772 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001773
John Kessenich7ba63412015-12-20 17:37:07 -07001774 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001775 if (!symbol->getType().getQualifier().isParamInput() &&
1776 !symbol->getType().getQualifier().isParamOutput()) {
1777 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1778 // Consider adding to the OpEntryPoint interface list.
1779 // Only looking at structures if they have at least one member.
1780 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1781 spv::StorageClass sc = builder.getStorageClass(id);
1782 // Before SPIR-V 1.4, we only want to include Input and Output.
1783 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001784 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001785 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1786 iOSet.insert(id);
1787 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001788 }
John Kessenich5f77d862017-09-19 11:09:59 -06001789 }
John Kessenich9c14f772019-06-17 08:38:35 -06001790
Daniel Kochdb32b242020-03-17 20:42:47 -04001791 // If the SPIR-V type is required to be different than the AST type
1792 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001793 // translate now from the SPIR-V type to the AST type, for the consuming
1794 // operation.
1795 // Note this turns it from an l-value to an r-value.
1796 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1797 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1798 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001799 }
1800
1801 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001802 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001803 // Prepare to generate code for the access
1804
1805 // L-value chains will be computed left to right. We're on the symbol now,
1806 // which is the left-most part of the access chain, so now is "clear" time,
1807 // followed by setting the base.
1808 builder.clearAccessChain();
1809
1810 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001811 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001812 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001813 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001814 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001815 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001816 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001817 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001818 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1819 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001820 builder.setAccessChainRValue(id);
1821 else
1822 builder.setAccessChainLValue(id);
1823 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001824
John Kessenichb9197c82019-08-11 07:41:45 -06001825#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001826 // Process linkage-only nodes for any special additional interface work.
1827 if (linkageOnly) {
1828 if (glslangIntermediate->getHlslFunctionality1()) {
1829 // Map implicit counter buffers to their originating buffers, which should have been
1830 // seen by now, given earlier pruning of unused counters, and preservation of order
1831 // of declaration.
1832 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1833 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1834 // Save possible originating buffers for counter buffers, keyed by
1835 // making the potential counter-buffer name.
1836 std::string keyName = symbol->getName().c_str();
1837 keyName = glslangIntermediate->addCounterBufferName(keyName);
1838 counterOriginator[keyName] = symbol;
1839 } else {
1840 // Handle a counter buffer, by finding the saved originating buffer.
1841 std::string keyName = symbol->getName().c_str();
1842 auto it = counterOriginator.find(keyName);
1843 if (it != counterOriginator.end()) {
1844 id = getSymbolId(it->second);
1845 if (id != spv::NoResult) {
1846 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001847 if (counterId != spv::NoResult) {
1848 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001849 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001850 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001851 }
1852 }
1853 }
1854 }
1855 }
1856 }
John Kessenich155d3512019-08-08 23:29:20 -06001857#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001858}
1859
1860bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1861{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001862 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001863 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1864 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1865 }
1866 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1867 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1868 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001869
qining40887662016-04-03 22:20:42 -04001870 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1871 if (node->getType().getQualifier().isSpecConstant())
1872 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1873
John Kessenich140f3df2015-06-26 16:58:36 -06001874 // First, handle special cases
1875 switch (node->getOp()) {
1876 case glslang::EOpAssign:
1877 case glslang::EOpAddAssign:
1878 case glslang::EOpSubAssign:
1879 case glslang::EOpMulAssign:
1880 case glslang::EOpVectorTimesMatrixAssign:
1881 case glslang::EOpVectorTimesScalarAssign:
1882 case glslang::EOpMatrixTimesScalarAssign:
1883 case glslang::EOpMatrixTimesMatrixAssign:
1884 case glslang::EOpDivAssign:
1885 case glslang::EOpModAssign:
1886 case glslang::EOpAndAssign:
1887 case glslang::EOpInclusiveOrAssign:
1888 case glslang::EOpExclusiveOrAssign:
1889 case glslang::EOpLeftShiftAssign:
1890 case glslang::EOpRightShiftAssign:
1891 // A bin-op assign "a += b" means the same thing as "a = a + b"
1892 // where a is evaluated before b. For a simple assignment, GLSL
1893 // says to evaluate the left before the right. So, always, left
1894 // node then right node.
1895 {
1896 // get the left l-value, save it away
1897 builder.clearAccessChain();
1898 node->getLeft()->traverse(this);
1899 spv::Builder::AccessChain lValue = builder.getAccessChain();
1900
1901 // evaluate the right
1902 builder.clearAccessChain();
1903 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001904 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001905
1906 if (node->getOp() != glslang::EOpAssign) {
1907 // the left is also an r-value
1908 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001909 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001910
1911 // do the operation
greg-lunarg639f5462020-11-12 11:10:07 -07001912 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1913 coherentFlags |= TranslateCoherent(node->getRight()->getType());
John Kessenichead86222018-03-28 18:01:20 -06001914 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001915 TranslateNoContractionDecoration(node->getType().getQualifier()),
greg-lunarg639f5462020-11-12 11:10:07 -07001916 TranslateNonUniformDecoration(coherentFlags) };
John Kessenichead86222018-03-28 18:01:20 -06001917 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001918 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1919 node->getType().getBasicType());
1920
1921 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001922 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001923 }
1924
1925 // store the result
1926 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001927 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001928
1929 // assignments are expressions having an rValue after they are evaluated...
1930 builder.clearAccessChain();
1931 builder.setAccessChainRValue(rValue);
1932 }
1933 return false;
1934 case glslang::EOpIndexDirect:
1935 case glslang::EOpIndexDirectStruct:
1936 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001937 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001938 // Get the left part of the access chain.
1939 node->getLeft()->traverse(this);
1940
1941 // Add the next element in the chain
1942
David Netoa901ffe2016-06-08 14:11:40 +01001943 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001944 if (! node->getLeft()->getType().isArray() &&
1945 node->getLeft()->getType().isVector() &&
1946 node->getOp() == glslang::EOpIndexDirect) {
greg-lunarg639f5462020-11-12 11:10:07 -07001947 // Swizzle is uniform so propagate uniform into access chain
1948 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1949 coherentFlags.nonUniform = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06001950 // This is essentially a hard-coded vector swizzle of size 1,
1951 // so short circuit the access-chain stuff with a swizzle.
1952 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001953 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001954 int dummySize;
1955 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
greg-lunarg639f5462020-11-12 11:10:07 -07001956 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07001957 glslangIntermediate->getBaseAlignmentScalar(
1958 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001959 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001960
1961 // Load through a block reference is performed with a dot operator that
1962 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1963 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001964 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001965 !node->getLeft()->getType().isArray() &&
1966 node->getOp() == glslang::EOpIndexDirectStruct)
1967 {
1968 spv::Id left = accessChainLoad(node->getLeft()->getType());
1969 builder.clearAccessChain();
1970 builder.setAccessChainLValue(left);
1971 }
1972
David Netoa901ffe2016-06-08 14:11:40 +01001973 int spvIndex = glslangIndex;
1974 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1975 node->getOp() == glslang::EOpIndexDirectStruct)
1976 {
1977 // This may be, e.g., an anonymous block-member selection, which generally need
1978 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001979 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1980 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1981 std::vector<int>& remapper = memberRemapper[glslangId];
1982 assert(remapper.size() > 0);
1983 spvIndex = remapper[glslangIndex];
1984 }
David Netoa901ffe2016-06-08 14:11:40 +01001985 }
John Kessenichebb50532016-05-16 19:22:05 -06001986
greg-lunarg639f5462020-11-12 11:10:07 -07001987 // Struct reference propagates uniform lvalue
1988 spv::Builder::AccessChain::CoherentFlags coherentFlags =
1989 TranslateCoherent(node->getLeft()->getType());
1990 coherentFlags.nonUniform = 0;
1991
David Netoa901ffe2016-06-08 14:11:40 +01001992 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001993 builder.accessChainPush(builder.makeIntConstant(spvIndex),
greg-lunarg639f5462020-11-12 11:10:07 -07001994 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07001995 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001996
1997 // Add capabilities here for accessing PointSize and clip/cull distance.
1998 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001999 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01002000 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06002001 }
2002 }
2003 return false;
2004 case glslang::EOpIndexIndirect:
2005 {
John Kessenich61a5ce12019-02-07 08:04:12 -07002006 // Array, matrix, or vector indirection with variable index.
2007 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06002008 // matrices are arrays of vectors, so will also work for a matrix.
2009 // Will use the access chain's 'component' for variable index into a vector.
2010
2011 // This adapter is building access chains left to right.
2012 // Set up the access chain to the left.
2013 node->getLeft()->traverse(this);
2014
2015 // save it so that computing the right side doesn't trash it
2016 spv::Builder::AccessChain partial = builder.getAccessChain();
2017
2018 // compute the next index in the chain
2019 builder.clearAccessChain();
2020 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002021 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002022
John Kessenich5611c6d2018-04-05 11:25:02 -06002023 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
2024
John Kessenich140f3df2015-06-26 16:58:36 -06002025 // restore the saved access chain
2026 builder.setAccessChain(partial);
2027
greg-lunarg639f5462020-11-12 11:10:07 -07002028 // Only if index is nonUniform should we propagate nonUniform into access chain
2029 spv::Builder::AccessChain::CoherentFlags index_flags = TranslateCoherent(node->getRight()->getType());
2030 spv::Builder::AccessChain::CoherentFlags coherent_flags = TranslateCoherent(node->getLeft()->getType());
2031 coherent_flags.nonUniform = index_flags.nonUniform;
2032
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002033 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
2034 int dummySize;
greg-lunarg639f5462020-11-12 11:10:07 -07002035 builder.accessChainPushComponent(
2036 index, convertGlslangToSpvType(node->getLeft()->getType()), coherent_flags,
John Kessenich8985fc92020-03-03 10:25:07 -07002037 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2038 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002039 } else
greg-lunarg639f5462020-11-12 11:10:07 -07002040 builder.accessChainPush(index, coherent_flags,
2041 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06002042 }
2043 return false;
2044 case glslang::EOpVectorSwizzle:
2045 {
2046 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002047 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06002048 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002049 int dummySize;
2050 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2051 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002052 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2053 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002054 }
2055 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002056 case glslang::EOpMatrixSwizzle:
2057 logger->missingFunctionality("matrix swizzle");
2058 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002059 case glslang::EOpLogicalOr:
2060 case glslang::EOpLogicalAnd:
2061 {
2062
2063 // These may require short circuiting, but can sometimes be done as straight
2064 // binary operations. The right operand must be short circuited if it has
2065 // side effects, and should probably be if it is complex.
2066 if (isTrivial(node->getRight()->getAsTyped()))
2067 break; // handle below as a normal binary operation
2068 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002069 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2070 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002071 builder.clearAccessChain();
2072 builder.setAccessChainRValue(result);
2073 }
2074 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002075 default:
2076 break;
2077 }
2078
2079 // Assume generic binary op...
2080
John Kessenich32cfd492016-02-02 12:37:46 -07002081 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002082 builder.clearAccessChain();
2083 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002084 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002085
John Kessenich32cfd492016-02-02 12:37:46 -07002086 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002087 builder.clearAccessChain();
2088 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002089 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002090
John Kessenich32cfd492016-02-02 12:37:46 -07002091 // get result
John Kessenichead86222018-03-28 18:01:20 -06002092 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002093 TranslateNoContractionDecoration(node->getType().getQualifier()),
2094 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002095 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002096 convertGlslangToSpvType(node->getType()), left, right,
2097 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002098
John Kessenich50e57562015-12-21 21:21:11 -07002099 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002100 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002101 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002102 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002103 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002104 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002105 return false;
2106 }
John Kessenich140f3df2015-06-26 16:58:36 -06002107}
2108
John Kessenich9c14f772019-06-17 08:38:35 -06002109// Figure out what, if any, type changes are needed when accessing a specific built-in.
2110// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2111// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002112std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002113 const glslang::TType& glslangType)
2114{
Daniel Kochdb32b242020-03-17 20:42:47 -04002115 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002116 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002117 case glslang::EbvSubGroupEqMask:
2118 case glslang::EbvSubGroupGeMask:
2119 case glslang::EbvSubGroupGtMask:
2120 case glslang::EbvSubGroupLeMask:
2121 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002122 // these require changing a 64-bit scaler -> a vector of 32-bit components
2123 if (glslangType.isVector())
2124 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05002125 spv::Id ivec4_type = builder.makeVectorType(builder.makeUintType(32), 4);
2126 spv::Id uint64_type = builder.makeUintType(64);
2127 std::pair<spv::Id, spv::Id> ret(ivec4_type, uint64_type);
John Kessenich9c14f772019-06-17 08:38:35 -06002128 return ret;
2129 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002130 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2131 // builtins. During visitBinary we insert a transpose
2132 case glslang::EbvWorldToObject3x4:
2133 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002134 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2135 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2136 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002137 return ret;
2138 }
John Kessenich9c14f772019-06-17 08:38:35 -06002139 default:
2140 break;
2141 }
2142
2143 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2144 return ret;
2145}
2146
2147// For an object previously identified (see getForcedType() and forceType)
2148// as needing type translations, do the translation needed for a load, turning
2149// an L-value into in R-value.
2150spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2151{
2152 const auto forceIt = forceType.find(object);
2153 if (forceIt == forceType.end())
2154 return object;
2155
2156 spv::Id desiredTypeId = forceIt->second;
2157 spv::Id objectTypeId = builder.getTypeId(object);
2158 assert(builder.isPointerType(objectTypeId));
2159 objectTypeId = builder.getContainedTypeId(objectTypeId);
2160 if (builder.isVectorType(objectTypeId) &&
2161 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2162 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2163 // handle 32-bit v.xy* -> 64-bit
2164 builder.clearAccessChain();
2165 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002166 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
John Kessenich9c14f772019-06-17 08:38:35 -06002167 std::vector<spv::Id> components;
2168 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2169 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2170
2171 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2172 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2173 builder.createCompositeConstruct(vecType, components));
2174 } else {
2175 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2176 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002177 } else if (builder.isMatrixType(objectTypeId)) {
2178 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2179 // and we insert a transpose after loading the original non-transposed builtins
2180 builder.clearAccessChain();
2181 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002182 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
Daniel Kochdb32b242020-03-17 20:42:47 -04002183 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2184
2185 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002186 logger->missingFunctionality("forcing non 32-bit vector type");
2187 }
2188
2189 return object;
2190}
2191
John Kessenich140f3df2015-06-26 16:58:36 -06002192bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2193{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002194 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002195
qining40887662016-04-03 22:20:42 -04002196 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2197 if (node->getType().getQualifier().isSpecConstant())
2198 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2199
John Kessenichfc51d282015-08-19 13:34:18 -06002200 spv::Id result = spv::NoResult;
2201
2202 // try texturing first
2203 result = createImageTextureFunctionCall(node);
2204 if (result != spv::NoResult) {
2205 builder.clearAccessChain();
2206 builder.setAccessChainRValue(result);
2207
2208 return false; // done with this node
2209 }
2210
2211 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002212
2213 if (node->getOp() == glslang::EOpArrayLength) {
2214 // Quite special; won't want to evaluate the operand.
2215
John Kessenich5611c6d2018-04-05 11:25:02 -06002216 // Currently, the front-end does not allow .length() on an array until it is sized,
2217 // except for the last block membeor of an SSBO.
2218 // TODO: If this changes, link-time sized arrays might show up here, and need their
2219 // size extracted.
2220
John Kessenichc9a80832015-09-12 12:17:44 -06002221 // Normal .length() would have been constant folded by the front-end.
2222 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002223 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002224
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002225 spv::Id length;
2226 if (node->getOperand()->getType().isCoopMat()) {
2227 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2228
2229 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2230 assert(builder.isCooperativeMatrixType(typeId));
2231
2232 length = builder.createCooperativeMatrixLength(typeId);
2233 } else {
2234 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2235 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002236 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2237 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002238 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2239 }
John Kessenichc9a80832015-09-12 12:17:44 -06002240
John Kessenich8c869672018-11-28 07:01:37 -07002241 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2242 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2243 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002244 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2245 if (builder.isInSpecConstCodeGenMode()) {
2246 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2247 } else {
2248 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2249 }
2250 }
John Kessenich8c869672018-11-28 07:01:37 -07002251
John Kessenichc9a80832015-09-12 12:17:44 -06002252 builder.clearAccessChain();
2253 builder.setAccessChainRValue(length);
2254
2255 return false;
2256 }
2257
John Kessenichfc51d282015-08-19 13:34:18 -06002258 // Start by evaluating the operand
2259
John Kessenich8c8505c2016-07-26 12:50:38 -06002260 // Does it need a swizzle inversion? If so, evaluation is inverted;
2261 // operate first on the swizzle base, then apply the swizzle.
2262 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002263 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2264 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002265 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2266 invertedType = getInvertedSwizzleType(*node->getOperand());
2267
John Kessenich140f3df2015-06-26 16:58:36 -06002268 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002269 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002270 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002271 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002272 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002273 operandNode = node->getOperand();
2274
2275 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002276
Rex Xufc618912015-09-09 16:42:49 +08002277 spv::Id operand = spv::NoResult;
2278
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002279 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2280
John Kessenichfb4f2332019-08-09 03:49:15 -06002281#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002282 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2283 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002284 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002285 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2286 node->getOp() == glslang::EOpRayQueryProceed ||
2287 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2288 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2289 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2290 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2291 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2292 node->getOp() == glslang::EOpRayQueryTerminate ||
2293 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002294 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002295 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2296 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2297 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002298#endif
2299 {
John Kessenich32cfd492016-02-02 12:37:46 -07002300 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002301 }
John Kessenich140f3df2015-06-26 16:58:36 -06002302
John Kessenichead86222018-03-28 18:01:20 -06002303 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002304 TranslateNoContractionDecoration(node->getType().getQualifier()),
2305 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002306
2307 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002308 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002309 result = createConversion(node->getOp(), decorations, resultType(), operand,
2310 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002311
2312 // if not, then possibly an operation
2313 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002314 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2315 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002318 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002319 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002320 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002321 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002322
John Kessenich140f3df2015-06-26 16:58:36 -06002323 builder.clearAccessChain();
2324 builder.setAccessChainRValue(result);
2325
2326 return false; // done with this node
2327 }
2328
2329 // it must be a special case, check...
2330 switch (node->getOp()) {
2331 case glslang::EOpPostIncrement:
2332 case glslang::EOpPostDecrement:
2333 case glslang::EOpPreIncrement:
2334 case glslang::EOpPreDecrement:
2335 {
2336 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002337 spv::Id one = 0;
2338 if (node->getBasicType() == glslang::EbtFloat)
2339 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002340#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002341 else if (node->getBasicType() == glslang::EbtDouble)
2342 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002343 else if (node->getBasicType() == glslang::EbtFloat16)
2344 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002345 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2346 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002347 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2348 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002349 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2350 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002351#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002352 else
2353 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002354 glslang::TOperator op;
2355 if (node->getOp() == glslang::EOpPreIncrement ||
2356 node->getOp() == glslang::EOpPostIncrement)
2357 op = glslang::EOpAdd;
2358 else
2359 op = glslang::EOpSub;
2360
John Kessenichead86222018-03-28 18:01:20 -06002361 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002362 convertGlslangToSpvType(node->getType()), operand, one,
2363 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002364 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002365
2366 // The result of operation is always stored, but conditionally the
2367 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002368 builder.accessChainStore(result,
greg-lunarg639f5462020-11-12 11:10:07 -07002369 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags));
John Kessenich140f3df2015-06-26 16:58:36 -06002370 builder.clearAccessChain();
2371 if (node->getOp() == glslang::EOpPreIncrement ||
2372 node->getOp() == glslang::EOpPreDecrement)
2373 builder.setAccessChainRValue(result);
2374 else
2375 builder.setAccessChainRValue(operand);
2376 }
2377
2378 return false;
2379
John Kessenich155d3512019-08-08 23:29:20 -06002380#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002381 case glslang::EOpEmitStreamVertex:
2382 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2383 return false;
2384 case glslang::EOpEndStreamPrimitive:
2385 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2386 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002387 case glslang::EOpRayQueryTerminate:
2388 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2389 return false;
2390 case glslang::EOpRayQueryConfirmIntersection:
2391 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2392 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002393#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002394
2395 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002396 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002397 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002398 }
John Kessenich140f3df2015-06-26 16:58:36 -06002399}
2400
Jeff Bolz53134492019-06-25 13:31:10 -05002401// Construct a composite object, recursively copying members if their types don't match
2402spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2403{
2404 for (int c = 0; c < (int)constituents.size(); ++c) {
2405 spv::Id& constituent = constituents[c];
2406 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2407 spv::Id rType = builder.getTypeId(constituent);
2408 if (lType != rType) {
2409 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2410 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2411 } else if (builder.isStructType(rType)) {
2412 std::vector<spv::Id> rTypeConstituents;
2413 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2414 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002415 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2416 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002417 }
2418 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2419 } else {
2420 assert(builder.isArrayType(rType));
2421 std::vector<spv::Id> rTypeConstituents;
2422 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2423
2424 spv::Id elementRType = builder.getContainedTypeId(rType);
2425 for (int i = 0; i < numrTypeConstituents; ++i) {
2426 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2427 }
2428 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2429 }
2430 }
2431 }
2432 return builder.createCompositeConstruct(resultTypeId, constituents);
2433}
2434
John Kessenich140f3df2015-06-26 16:58:36 -06002435bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2436{
qining27e04a02016-04-14 16:40:20 -04002437 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2438 if (node->getType().getQualifier().isSpecConstant())
2439 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2440
John Kessenichfc51d282015-08-19 13:34:18 -06002441 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002442 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2443 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2444 // SPIR-V, for an out parameter
2445 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002446
John Kessenich8985fc92020-03-03 10:25:07 -07002447 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2448 invertedType :
2449 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002450
2451 // try texturing
2452 result = createImageTextureFunctionCall(node);
2453 if (result != spv::NoResult) {
2454 builder.clearAccessChain();
2455 builder.setAccessChainRValue(result);
2456
2457 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002458 }
2459#ifndef GLSLANG_WEB
2460 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002461 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002462 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002463 // "imageStore" is a special case, which has no result
2464 return false;
2465 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002466#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002467
John Kessenich140f3df2015-06-26 16:58:36 -06002468 glslang::TOperator binOp = glslang::EOpNull;
2469 bool reduceComparison = true;
2470 bool isMatrix = false;
2471 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002472 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002473
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002474 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2475
John Kessenich140f3df2015-06-26 16:58:36 -06002476 assert(node->getOp());
2477
John Kessenichf6640762016-08-01 19:44:00 -06002478 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002479
2480 switch (node->getOp()) {
2481 case glslang::EOpSequence:
2482 {
2483 if (preVisit)
2484 ++sequenceDepth;
2485 else
2486 --sequenceDepth;
2487
2488 if (sequenceDepth == 1) {
2489 // If this is the parent node of all the functions, we want to see them
2490 // early, so all call points have actual SPIR-V functions to reference.
2491 // In all cases, still let the traverser visit the children for us.
2492 makeFunctions(node->getAsAggregate()->getSequence());
2493
John Kessenich6fccb3c2016-09-19 16:01:41 -06002494 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002495 // anything else gets there, so visit out of order, doing them all now.
2496 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2497
Daniel Kochffccefd2020-11-23 15:41:27 -05002498 //Pre process linker objects for ray tracing stages
2499 if (glslangIntermediate->isRayTracingStage())
2500 collectRayTracingLinkerObjects();
2501
John Kessenich6a60c2f2016-12-08 21:01:59 -07002502 // 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 -06002503 // so do them manually.
2504 visitFunctions(node->getAsAggregate()->getSequence());
2505
2506 return false;
2507 }
2508
2509 return true;
2510 }
2511 case glslang::EOpLinkerObjects:
2512 {
2513 if (visit == glslang::EvPreVisit)
2514 linkageOnly = true;
2515 else
2516 linkageOnly = false;
2517
2518 return true;
2519 }
2520 case glslang::EOpComma:
2521 {
2522 // processing from left to right naturally leaves the right-most
2523 // lying around in the access chain
2524 glslang::TIntermSequence& glslangOperands = node->getSequence();
2525 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2526 glslangOperands[i]->traverse(this);
2527
2528 return false;
2529 }
2530 case glslang::EOpFunction:
2531 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002532 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002533 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002534 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002535 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002536 } else {
2537 handleFunctionEntry(node);
2538 }
2539 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002540 if (inEntryPoint)
2541 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002542 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002543 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002544 }
2545
2546 return true;
2547 case glslang::EOpParameters:
2548 // Parameters will have been consumed by EOpFunction processing, but not
2549 // the body, so we still visited the function node's children, making this
2550 // child redundant.
2551 return false;
2552 case glslang::EOpFunctionCall:
2553 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002554 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002555 if (node->isUserDefined())
2556 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002557 if (result) {
2558 builder.clearAccessChain();
2559 builder.setAccessChainRValue(result);
2560 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002561 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002562
2563 return false;
2564 }
2565 case glslang::EOpConstructMat2x2:
2566 case glslang::EOpConstructMat2x3:
2567 case glslang::EOpConstructMat2x4:
2568 case glslang::EOpConstructMat3x2:
2569 case glslang::EOpConstructMat3x3:
2570 case glslang::EOpConstructMat3x4:
2571 case glslang::EOpConstructMat4x2:
2572 case glslang::EOpConstructMat4x3:
2573 case glslang::EOpConstructMat4x4:
2574 case glslang::EOpConstructDMat2x2:
2575 case glslang::EOpConstructDMat2x3:
2576 case glslang::EOpConstructDMat2x4:
2577 case glslang::EOpConstructDMat3x2:
2578 case glslang::EOpConstructDMat3x3:
2579 case glslang::EOpConstructDMat3x4:
2580 case glslang::EOpConstructDMat4x2:
2581 case glslang::EOpConstructDMat4x3:
2582 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002583 case glslang::EOpConstructIMat2x2:
2584 case glslang::EOpConstructIMat2x3:
2585 case glslang::EOpConstructIMat2x4:
2586 case glslang::EOpConstructIMat3x2:
2587 case glslang::EOpConstructIMat3x3:
2588 case glslang::EOpConstructIMat3x4:
2589 case glslang::EOpConstructIMat4x2:
2590 case glslang::EOpConstructIMat4x3:
2591 case glslang::EOpConstructIMat4x4:
2592 case glslang::EOpConstructUMat2x2:
2593 case glslang::EOpConstructUMat2x3:
2594 case glslang::EOpConstructUMat2x4:
2595 case glslang::EOpConstructUMat3x2:
2596 case glslang::EOpConstructUMat3x3:
2597 case glslang::EOpConstructUMat3x4:
2598 case glslang::EOpConstructUMat4x2:
2599 case glslang::EOpConstructUMat4x3:
2600 case glslang::EOpConstructUMat4x4:
2601 case glslang::EOpConstructBMat2x2:
2602 case glslang::EOpConstructBMat2x3:
2603 case glslang::EOpConstructBMat2x4:
2604 case glslang::EOpConstructBMat3x2:
2605 case glslang::EOpConstructBMat3x3:
2606 case glslang::EOpConstructBMat3x4:
2607 case glslang::EOpConstructBMat4x2:
2608 case glslang::EOpConstructBMat4x3:
2609 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002610 case glslang::EOpConstructF16Mat2x2:
2611 case glslang::EOpConstructF16Mat2x3:
2612 case glslang::EOpConstructF16Mat2x4:
2613 case glslang::EOpConstructF16Mat3x2:
2614 case glslang::EOpConstructF16Mat3x3:
2615 case glslang::EOpConstructF16Mat3x4:
2616 case glslang::EOpConstructF16Mat4x2:
2617 case glslang::EOpConstructF16Mat4x3:
2618 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002619 isMatrix = true;
2620 // fall through
2621 case glslang::EOpConstructFloat:
2622 case glslang::EOpConstructVec2:
2623 case glslang::EOpConstructVec3:
2624 case glslang::EOpConstructVec4:
2625 case glslang::EOpConstructDouble:
2626 case glslang::EOpConstructDVec2:
2627 case glslang::EOpConstructDVec3:
2628 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002629 case glslang::EOpConstructFloat16:
2630 case glslang::EOpConstructF16Vec2:
2631 case glslang::EOpConstructF16Vec3:
2632 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002633 case glslang::EOpConstructBool:
2634 case glslang::EOpConstructBVec2:
2635 case glslang::EOpConstructBVec3:
2636 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002637 case glslang::EOpConstructInt8:
2638 case glslang::EOpConstructI8Vec2:
2639 case glslang::EOpConstructI8Vec3:
2640 case glslang::EOpConstructI8Vec4:
2641 case glslang::EOpConstructUint8:
2642 case glslang::EOpConstructU8Vec2:
2643 case glslang::EOpConstructU8Vec3:
2644 case glslang::EOpConstructU8Vec4:
2645 case glslang::EOpConstructInt16:
2646 case glslang::EOpConstructI16Vec2:
2647 case glslang::EOpConstructI16Vec3:
2648 case glslang::EOpConstructI16Vec4:
2649 case glslang::EOpConstructUint16:
2650 case glslang::EOpConstructU16Vec2:
2651 case glslang::EOpConstructU16Vec3:
2652 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002653 case glslang::EOpConstructInt:
2654 case glslang::EOpConstructIVec2:
2655 case glslang::EOpConstructIVec3:
2656 case glslang::EOpConstructIVec4:
2657 case glslang::EOpConstructUint:
2658 case glslang::EOpConstructUVec2:
2659 case glslang::EOpConstructUVec3:
2660 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002661 case glslang::EOpConstructInt64:
2662 case glslang::EOpConstructI64Vec2:
2663 case glslang::EOpConstructI64Vec3:
2664 case glslang::EOpConstructI64Vec4:
2665 case glslang::EOpConstructUint64:
2666 case glslang::EOpConstructU64Vec2:
2667 case glslang::EOpConstructU64Vec3:
2668 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002669 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002670 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002671 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002672 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002673 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002674 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002675 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002676 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002677 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002678 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002679 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002680 else if (node->getOp() == glslang::EOpConstructStruct ||
2681 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2682 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002683 std::vector<spv::Id> constituents;
2684 for (int c = 0; c < (int)arguments.size(); ++c)
2685 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002686 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002687 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002688 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002689 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002690 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002691
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002692 if (node->getType().getQualifier().isNonUniform()) {
2693 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2694 }
2695
John Kessenich140f3df2015-06-26 16:58:36 -06002696 builder.clearAccessChain();
2697 builder.setAccessChainRValue(constructed);
2698
2699 return false;
2700 }
2701
2702 // These six are component-wise compares with component-wise results.
2703 // Forward on to createBinaryOperation(), requesting a vector result.
2704 case glslang::EOpLessThan:
2705 case glslang::EOpGreaterThan:
2706 case glslang::EOpLessThanEqual:
2707 case glslang::EOpGreaterThanEqual:
2708 case glslang::EOpVectorEqual:
2709 case glslang::EOpVectorNotEqual:
2710 {
2711 // Map the operation to a binary
2712 binOp = node->getOp();
2713 reduceComparison = false;
2714 switch (node->getOp()) {
2715 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2716 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2717 default: binOp = node->getOp(); break;
2718 }
2719
2720 break;
2721 }
2722 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002723 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002724 binOp = glslang::EOpMul;
2725 break;
2726 case glslang::EOpOuterProduct:
2727 // two vectors multiplied to make a matrix
2728 binOp = glslang::EOpOuterProduct;
2729 break;
2730 case glslang::EOpDot:
2731 {
qining25262b32016-05-06 17:25:16 -04002732 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002733 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002734 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002735 binOp = glslang::EOpMul;
2736 break;
2737 }
2738 case glslang::EOpMod:
2739 // when an aggregate, this is the floating-point mod built-in function,
2740 // which can be emitted by the one in createBinaryOperation()
2741 binOp = glslang::EOpMod;
2742 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002743
John Kessenich140f3df2015-06-26 16:58:36 -06002744 case glslang::EOpEmitVertex:
2745 case glslang::EOpEndPrimitive:
2746 case glslang::EOpBarrier:
2747 case glslang::EOpMemoryBarrier:
2748 case glslang::EOpMemoryBarrierAtomicCounter:
2749 case glslang::EOpMemoryBarrierBuffer:
2750 case glslang::EOpMemoryBarrierImage:
2751 case glslang::EOpMemoryBarrierShared:
2752 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002753 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002754 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002755 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002756 case glslang::EOpWorkgroupMemoryBarrier:
2757 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002758 case glslang::EOpSubgroupBarrier:
2759 case glslang::EOpSubgroupMemoryBarrier:
2760 case glslang::EOpSubgroupMemoryBarrierBuffer:
2761 case glslang::EOpSubgroupMemoryBarrierImage:
2762 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002763 noReturnValue = true;
2764 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2765 break;
2766
John Kessenich426394d2015-07-23 10:22:48 -06002767 case glslang::EOpAtomicAdd:
2768 case glslang::EOpAtomicMin:
2769 case glslang::EOpAtomicMax:
2770 case glslang::EOpAtomicAnd:
2771 case glslang::EOpAtomicOr:
2772 case glslang::EOpAtomicXor:
2773 case glslang::EOpAtomicExchange:
2774 case glslang::EOpAtomicCompSwap:
2775 atomic = true;
2776 break;
2777
John Kesseniche5eee8f2019-10-18 01:03:11 -06002778#ifndef GLSLANG_WEB
2779 case glslang::EOpAtomicStore:
2780 noReturnValue = true;
2781 // fallthrough
2782 case glslang::EOpAtomicLoad:
2783 atomic = true;
2784 break;
2785
John Kessenich0d0c6d32017-07-23 16:08:26 -06002786 case glslang::EOpAtomicCounterAdd:
2787 case glslang::EOpAtomicCounterSubtract:
2788 case glslang::EOpAtomicCounterMin:
2789 case glslang::EOpAtomicCounterMax:
2790 case glslang::EOpAtomicCounterAnd:
2791 case glslang::EOpAtomicCounterOr:
2792 case glslang::EOpAtomicCounterXor:
2793 case glslang::EOpAtomicCounterExchange:
2794 case glslang::EOpAtomicCounterCompSwap:
2795 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2796 builder.addCapability(spv::CapabilityAtomicStorageOps);
2797 atomic = true;
2798 break;
2799
Ian Romanickb3bd4022019-01-21 08:57:25 -08002800 case glslang::EOpAbsDifference:
2801 case glslang::EOpAddSaturate:
2802 case glslang::EOpSubSaturate:
2803 case glslang::EOpAverage:
2804 case glslang::EOpAverageRounded:
2805 case glslang::EOpMul32x16:
2806 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2807 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2808 binOp = node->getOp();
2809 break;
2810
Daniel Kochffccefd2020-11-23 15:41:27 -05002811 case glslang::EOpIgnoreIntersectionNV:
2812 case glslang::EOpTerminateRayNV:
2813 case glslang::EOpTraceNV:
2814 case glslang::EOpTraceKHR:
2815 case glslang::EOpExecuteCallableNV:
2816 case glslang::EOpExecuteCallableKHR:
Chao Chen3c366992018-09-19 11:41:59 -07002817 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2818 noReturnValue = true;
2819 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002820 case glslang::EOpRayQueryInitialize:
2821 case glslang::EOpRayQueryTerminate:
2822 case glslang::EOpRayQueryGenerateIntersection:
2823 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002824 builder.addExtension("SPV_KHR_ray_query");
Daniel Kochffccefd2020-11-23 15:41:27 -05002825 builder.addCapability(spv::CapabilityRayQueryKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002826 noReturnValue = true;
2827 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002828 case glslang::EOpRayQueryProceed:
2829 case glslang::EOpRayQueryGetIntersectionType:
2830 case glslang::EOpRayQueryGetRayTMin:
2831 case glslang::EOpRayQueryGetRayFlags:
2832 case glslang::EOpRayQueryGetIntersectionT:
2833 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2834 case glslang::EOpRayQueryGetIntersectionInstanceId:
2835 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2836 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2837 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2838 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2839 case glslang::EOpRayQueryGetIntersectionFrontFace:
2840 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2841 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2842 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2843 case glslang::EOpRayQueryGetWorldRayDirection:
2844 case glslang::EOpRayQueryGetWorldRayOrigin:
2845 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2846 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2847 builder.addExtension("SPV_KHR_ray_query");
Daniel Kochffccefd2020-11-23 15:41:27 -05002848 builder.addCapability(spv::CapabilityRayQueryKHR);
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002849 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002850 case glslang::EOpCooperativeMatrixLoad:
2851 case glslang::EOpCooperativeMatrixStore:
2852 noReturnValue = true;
2853 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002854 case glslang::EOpBeginInvocationInterlock:
2855 case glslang::EOpEndInvocationInterlock:
2856 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2857 noReturnValue = true;
2858 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002859#endif
Chao Chen3c366992018-09-19 11:41:59 -07002860
Jeff Bolz04d73732019-05-31 13:06:01 -05002861 case glslang::EOpDebugPrintf:
2862 noReturnValue = true;
2863 break;
2864
John Kessenich140f3df2015-06-26 16:58:36 -06002865 default:
2866 break;
2867 }
2868
2869 //
2870 // See if it maps to a regular operation.
2871 //
John Kessenich140f3df2015-06-26 16:58:36 -06002872 if (binOp != glslang::EOpNull) {
2873 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2874 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2875 assert(left && right);
2876
2877 builder.clearAccessChain();
2878 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002879 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002880
2881 builder.clearAccessChain();
2882 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002883 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002884
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002885 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002886 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002887 TranslateNoContractionDecoration(node->getType().getQualifier()),
2888 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002889 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002890 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002891 left->getType().getBasicType(), reduceComparison);
2892
2893 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002894 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002895 builder.clearAccessChain();
2896 builder.setAccessChainRValue(result);
2897
2898 return false;
2899 }
2900
John Kessenich426394d2015-07-23 10:22:48 -06002901 //
2902 // Create the list of operands.
2903 //
John Kessenich140f3df2015-06-26 16:58:36 -06002904 glslang::TIntermSequence& glslangOperands = node->getSequence();
2905 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002906 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002907 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002908 // special case l-value operands; there are just a few
2909 bool lvalue = false;
2910 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002911 case glslang::EOpModf:
2912 if (arg == 1)
2913 lvalue = true;
2914 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002915
Torosdagli06c2eee2020-03-19 11:09:57 -04002916 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002917 case glslang::EOpRayQueryTerminate:
2918 case glslang::EOpRayQueryConfirmIntersection:
2919 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002920 case glslang::EOpRayQueryGenerateIntersection:
2921 case glslang::EOpRayQueryGetIntersectionType:
2922 case glslang::EOpRayQueryGetIntersectionT:
2923 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2924 case glslang::EOpRayQueryGetIntersectionInstanceId:
2925 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2926 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2927 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2928 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2929 case glslang::EOpRayQueryGetIntersectionFrontFace:
2930 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2931 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2932 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2933 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2934 if (arg == 0)
2935 lvalue = true;
2936 break;
2937
John Kesseniche5eee8f2019-10-18 01:03:11 -06002938 case glslang::EOpAtomicAdd:
2939 case glslang::EOpAtomicMin:
2940 case glslang::EOpAtomicMax:
2941 case glslang::EOpAtomicAnd:
2942 case glslang::EOpAtomicOr:
2943 case glslang::EOpAtomicXor:
2944 case glslang::EOpAtomicExchange:
2945 case glslang::EOpAtomicCompSwap:
2946 if (arg == 0)
2947 lvalue = true;
2948 break;
2949
John Kessenicha28f7a72019-08-06 07:00:58 -06002950#ifndef GLSLANG_WEB
2951 case glslang::EOpFrexp:
2952 if (arg == 1)
2953 lvalue = true;
2954 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002955 case glslang::EOpInterpolateAtSample:
2956 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002957 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002958 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002959 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002960
2961 // Does it need a swizzle inversion? If so, evaluation is inverted;
2962 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002963 // That is, we transform
2964 //
2965 // interpolate(v.zy) -> interpolate(v).zy
2966 //
John Kessenichecba76f2017-01-06 00:34:48 -07002967 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002968 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002969 invertedType = convertGlslangToSpvType(
2970 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002971 }
Rex Xu7a26c172015-12-08 17:12:09 +08002972 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002973 case glslang::EOpAtomicLoad:
2974 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002975 case glslang::EOpAtomicCounterAdd:
2976 case glslang::EOpAtomicCounterSubtract:
2977 case glslang::EOpAtomicCounterMin:
2978 case glslang::EOpAtomicCounterMax:
2979 case glslang::EOpAtomicCounterAnd:
2980 case glslang::EOpAtomicCounterOr:
2981 case glslang::EOpAtomicCounterXor:
2982 case glslang::EOpAtomicCounterExchange:
2983 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002984 if (arg == 0)
2985 lvalue = true;
2986 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002987 case glslang::EOpAddCarry:
2988 case glslang::EOpSubBorrow:
2989 if (arg == 2)
2990 lvalue = true;
2991 break;
2992 case glslang::EOpUMulExtended:
2993 case glslang::EOpIMulExtended:
2994 if (arg >= 2)
2995 lvalue = true;
2996 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002997 case glslang::EOpCooperativeMatrixLoad:
2998 if (arg == 0 || arg == 1)
2999 lvalue = true;
3000 break;
3001 case glslang::EOpCooperativeMatrixStore:
3002 if (arg == 1)
3003 lvalue = true;
3004 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003005#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003006 default:
3007 break;
3008 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003009 builder.clearAccessChain();
3010 if (invertedType != spv::NoType && arg == 0)
3011 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
3012 else
3013 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003014
John Kessenichb9197c82019-08-11 07:41:45 -06003015#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003016 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
3017 node->getOp() == glslang::EOpCooperativeMatrixStore) {
3018
3019 if (arg == 1) {
3020 // fold "element" parameter into the access chain
3021 spv::Builder::AccessChain save = builder.getAccessChain();
3022 builder.clearAccessChain();
3023 glslangOperands[2]->traverse(this);
3024
3025 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
3026
3027 builder.setAccessChain(save);
3028
3029 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07003030 builder.accessChainPush(elementId,
3031 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
3032 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003033
3034 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3035 unsigned int alignment = builder.getAccessChain().alignment;
3036
3037 int memoryAccess = TranslateMemoryAccess(coherentFlags);
3038 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
3039 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
3040 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
3041 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07003042 if (builder.getStorageClass(builder.getAccessChain().base) ==
3043 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003044 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
3045 }
3046
3047 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
3048
3049 if (memoryAccess & spv::MemoryAccessAlignedMask) {
3050 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
3051 }
3052
John Kessenich8985fc92020-03-03 10:25:07 -07003053 if (memoryAccess &
3054 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3055 memoryAccessOperands.push_back(spv::IdImmediate(true,
3056 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003057 }
3058 } else if (arg == 2) {
3059 continue;
3060 }
3061 }
John Kessenichb9197c82019-08-11 07:41:45 -06003062#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003063
John Kessenichbbbd9a22020-03-03 07:21:37 -07003064 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003065 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003066 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3067 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3068 // reduce to a simple access chain. So, we need a temporary vector to
3069 // receive the result, and must later swizzle that into the original
3070 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003071 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06003072 temporaryLvalues.push_back(builder.createVariable(
3073 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003074 builder.accessChainGetInferredType(), "swizzleTemp"));
3075 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003076 } else {
3077 operands.push_back(builder.accessChainGetLValue());
3078 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003079 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3080 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3081 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003082 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003083 glslang::TOperator glslangOp = node->getOp();
3084 if (arg == 1 &&
3085 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3086 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3087 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3088 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3089 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3090 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3091 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3092 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3093 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3094 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3095 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3096 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3097 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3098 )) {
3099 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3100 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
Daniel Kochffccefd2020-11-23 15:41:27 -05003101 } else if ((arg == 10 && glslangOp == glslang::EOpTraceKHR) ||
3102 (arg == 1 && glslangOp == glslang::EOpExecuteCallableKHR)) {
3103 const int opdNum = glslangOp == glslang::EOpTraceKHR ? 10 : 1;
3104 const int set = glslangOp == glslang::EOpTraceKHR ? 0 : 1;
3105 const int location = glslangOperands[opdNum]->getAsConstantUnion()->getConstArray()[0].getUConst();
3106 auto itNode = locationToSymbol[set].find(location);
3107 visitSymbol(itNode->second);
3108 spv::Id symId = getSymbolId(itNode->second);
3109 operands.push_back(symId);
3110 } else {
Torosdagli06c2eee2020-03-19 11:09:57 -04003111 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
Daniel Kochffccefd2020-11-23 15:41:27 -05003112 }
John Kesseniche485c7a2017-05-31 18:50:53 -06003113 }
John Kessenich140f3df2015-06-26 16:58:36 -06003114 }
John Kessenich426394d2015-07-23 10:22:48 -06003115
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003116 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003117#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003118 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3119 std::vector<spv::IdImmediate> idImmOps;
3120
3121 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3122 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3123 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3124 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3125 // get the pointee type
3126 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3127 assert(builder.isCooperativeMatrixType(typeId));
3128 // do the op
3129 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3130 // store the result to the pointer (out param 'm')
3131 builder.createStore(result, operands[0]);
3132 result = 0;
3133 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3134 std::vector<spv::IdImmediate> idImmOps;
3135
3136 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3137 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3138 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3139 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3140 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3141
3142 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3143 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003144 } else
3145#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003146 if (atomic) {
3147 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003148 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3149 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003150 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3151 if (!nonSemanticDebugPrintf) {
3152 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3153 }
3154 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3155 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003156 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003157 // Pass through to generic operations.
3158 switch (glslangOperands.size()) {
3159 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003160 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003161 break;
3162 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003163 {
3164 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003165 TranslateNoContractionDecoration(node->getType().getQualifier()),
3166 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003167 result = createUnaryOperation(
3168 node->getOp(), decorations,
3169 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003170 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003171 }
John Kessenich426394d2015-07-23 10:22:48 -06003172 break;
3173 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003174 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003175 break;
3176 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003177
John Kessenichbbbd9a22020-03-03 07:21:37 -07003178 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003179 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003180
3181 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3182 builder.setAccessChain(complexLvalues[i]);
greg-lunarg639f5462020-11-12 11:10:07 -07003183 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision),
3184 TranslateNonUniformDecoration(complexLvalues[i].coherentFlags));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003185 }
John Kessenich140f3df2015-06-26 16:58:36 -06003186 }
3187
3188 if (noReturnValue)
3189 return false;
3190
3191 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003192 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003193 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003194 } else {
3195 builder.clearAccessChain();
3196 builder.setAccessChainRValue(result);
3197 return false;
3198 }
3199}
3200
John Kessenich433e9ff2017-01-26 20:31:11 -07003201// This path handles both if-then-else and ?:
3202// The if-then-else has a node type of void, while
3203// ?: has either a void or a non-void node type
3204//
3205// Leaving the result, when not void:
3206// GLSL only has r-values as the result of a :?, but
3207// if we have an l-value, that can be more efficient if it will
3208// become the base of a complex r-value expression, because the
3209// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003210bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3211{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003212 // see if OpSelect can handle it
3213 const auto isOpSelectable = [&]() {
3214 if (node->getBasicType() == glslang::EbtVoid)
3215 return false;
3216 // OpSelect can do all other types starting with SPV 1.4
3217 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3218 // pre-1.4, only scalars and vectors can be handled
3219 if ((!node->getType().isScalar() && !node->getType().isVector()))
3220 return false;
3221 }
3222 return true;
3223 };
3224
John Kessenich4bee5312018-02-20 21:29:05 -07003225 // See if it simple and safe, or required, to execute both sides.
3226 // Crucially, side effects must be either semantically required or avoided,
3227 // and there are performance trade-offs.
3228 // Return true if required or a good idea (and safe) to execute both sides,
3229 // false otherwise.
3230 const auto bothSidesPolicy = [&]() -> bool {
3231 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003232 if (node->getTrueBlock() == nullptr ||
3233 node->getFalseBlock() == nullptr)
3234 return false;
3235
John Kessenich4bee5312018-02-20 21:29:05 -07003236 // required? (unless we write additional code to look for side effects
3237 // and make performance trade-offs if none are present)
3238 if (!node->getShortCircuit())
3239 return true;
3240
3241 // if not required to execute both, decide based on performance/practicality...
3242
John Kessenich0c1e71a2019-01-10 18:23:06 +07003243 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003244 return false;
3245
John Kessenich433e9ff2017-01-26 20:31:11 -07003246 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3247 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3248
3249 // return true if a single operand to ? : is okay for OpSelect
3250 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003251 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003252 };
3253
3254 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3255 operandOkay(node->getFalseBlock()->getAsTyped());
3256 };
3257
John Kessenich4bee5312018-02-20 21:29:05 -07003258 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3259 // emit the condition before doing anything with selection
3260 node->getCondition()->traverse(this);
3261 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3262
3263 // Find a way of executing both sides and selecting the right result.
3264 const auto executeBothSides = [&]() -> void {
3265 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003266 node->getTrueBlock()->traverse(this);
3267 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3268 node->getFalseBlock()->traverse(this);
3269 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3270
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003271 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003272
John Kessenich4bee5312018-02-20 21:29:05 -07003273 // done if void
3274 if (node->getBasicType() == glslang::EbtVoid)
3275 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003276
John Kessenich4bee5312018-02-20 21:29:05 -07003277 // emit code to select between trueValue and falseValue
3278
3279 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003280 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003281 // Emit OpSelect for this selection.
3282
3283 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003284 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3285 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003286 condition = builder.smearScalar(spv::NoPrecision, condition,
3287 builder.makeVectorType(builder.makeBoolType(),
3288 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003289 }
John Kessenich4bee5312018-02-20 21:29:05 -07003290
3291 // OpSelect
3292 result = builder.createTriOp(spv::OpSelect,
3293 convertGlslangToSpvType(node->getType()), condition,
3294 trueValue, falseValue);
3295
3296 builder.clearAccessChain();
3297 builder.setAccessChainRValue(result);
3298 } else {
3299 // We need control flow to select the result.
3300 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003301 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3302 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003303
3304 // Selection control:
3305 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3306
3307 // make an "if" based on the value created by the condition
3308 spv::Builder::If ifBuilder(condition, control, builder);
3309
3310 // emit the "then" statement
3311 builder.createStore(trueValue, result);
3312 ifBuilder.makeBeginElse();
3313 // emit the "else" statement
3314 builder.createStore(falseValue, result);
3315
3316 // finish off the control flow
3317 ifBuilder.makeEndIf();
3318
3319 builder.clearAccessChain();
3320 builder.setAccessChainLValue(result);
3321 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003322 };
3323
John Kessenich4bee5312018-02-20 21:29:05 -07003324 // Execute the one side needed, as per the condition
3325 const auto executeOneSide = [&]() {
3326 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003327 if (node->getBasicType() != glslang::EbtVoid) {
3328 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3329 convertGlslangToSpvType(node->getType()));
3330 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003331
John Kessenich4bee5312018-02-20 21:29:05 -07003332 // Selection control:
3333 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3334
3335 // make an "if" based on the value created by the condition
3336 spv::Builder::If ifBuilder(condition, control, builder);
3337
3338 // emit the "then" statement
3339 if (node->getTrueBlock() != nullptr) {
3340 node->getTrueBlock()->traverse(this);
3341 if (result != spv::NoResult)
3342 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3343 }
3344
3345 if (node->getFalseBlock() != nullptr) {
3346 ifBuilder.makeBeginElse();
3347 // emit the "else" statement
3348 node->getFalseBlock()->traverse(this);
3349 if (result != spv::NoResult)
3350 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3351 }
3352
3353 // finish off the control flow
3354 ifBuilder.makeEndIf();
3355
3356 if (result != spv::NoResult) {
3357 builder.clearAccessChain();
3358 builder.setAccessChainLValue(result);
3359 }
3360 };
3361
3362 // Try for OpSelect (or a requirement to execute both sides)
3363 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003364 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3365 if (node->getType().getQualifier().isSpecConstant())
3366 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003367 executeBothSides();
3368 } else
3369 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003370
3371 return false;
3372}
3373
3374bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3375{
3376 // emit and get the condition before doing anything with switch
3377 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003378 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003379
Rex Xu57e65922017-07-04 23:23:40 +08003380 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003381 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003382
John Kessenich140f3df2015-06-26 16:58:36 -06003383 // browse the children to sort out code segments
3384 int defaultSegment = -1;
3385 std::vector<TIntermNode*> codeSegments;
3386 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3387 std::vector<int> caseValues;
3388 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3389 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3390 TIntermNode* child = *c;
3391 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003392 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003393 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003394 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003395 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3396 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003397 } else
3398 codeSegments.push_back(child);
3399 }
3400
qining25262b32016-05-06 17:25:16 -04003401 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003402 // statements between the last case and the end of the switch statement
3403 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3404 (int)codeSegments.size() == defaultSegment)
3405 codeSegments.push_back(nullptr);
3406
3407 // make the switch statement
3408 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003409 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3410 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003411
3412 // emit all the code in the segments
3413 breakForLoop.push(false);
3414 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3415 builder.nextSwitchSegment(segmentBlocks, s);
3416 if (codeSegments[s])
3417 codeSegments[s]->traverse(this);
3418 else
3419 builder.addSwitchBreak();
3420 }
3421 breakForLoop.pop();
3422
3423 builder.endSwitch(segmentBlocks);
3424
3425 return false;
3426}
3427
3428void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3429{
3430 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003431 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003432
3433 builder.clearAccessChain();
3434 builder.setAccessChainRValue(constant);
3435}
3436
3437bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3438{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003439 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003440 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003441
3442 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003443 std::vector<unsigned int> operands;
3444 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003445
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003446 // Spec requires back edges to target header blocks, and every header block
3447 // must dominate its merge block. Make a header block first to ensure these
3448 // conditions are met. By definition, it will contain OpLoopMerge, followed
3449 // by a block-ending branch. But we don't want to put any other body/test
3450 // instructions in it, since the body/test may have arbitrary instructions,
3451 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003452 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003453 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003454 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003455 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003456 spv::Block& test = builder.makeNewBlock();
3457 builder.createBranch(&test);
3458
3459 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003460 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003461 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003462 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3463
3464 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003465 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003466 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003467 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003468 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003469 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003470
3471 builder.setBuildPoint(&blocks.continue_target);
3472 if (node->getTerminal())
3473 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003474 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003475 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003476 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003477 builder.createBranch(&blocks.body);
3478
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003479 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003480 builder.setBuildPoint(&blocks.body);
3481 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003482 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003483 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003484 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003485
3486 builder.setBuildPoint(&blocks.continue_target);
3487 if (node->getTerminal())
3488 node->getTerminal()->traverse(this);
3489 if (node->getTest()) {
3490 node->getTest()->traverse(this);
3491 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003492 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003493 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003494 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003495 // TODO: unless there was a break/return/discard instruction
3496 // somewhere in the body, this is an infinite loop, so we should
3497 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003498 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003499 }
John Kessenich140f3df2015-06-26 16:58:36 -06003500 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003501 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003502 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003503 return false;
3504}
3505
3506bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3507{
3508 if (node->getExpression())
3509 node->getExpression()->traverse(this);
3510
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003511 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003512
John Kessenich140f3df2015-06-26 16:58:36 -06003513 switch (node->getFlowOp()) {
3514 case glslang::EOpKill:
Daniel Kochffccefd2020-11-23 15:41:27 -05003515 builder.makeStatementTerminator(spv::OpKill, "post-discard");
John Kessenich140f3df2015-06-26 16:58:36 -06003516 break;
Jesse Hall74e8f052020-11-09 08:30:01 -08003517 case glslang::EOpTerminateInvocation:
3518 builder.addExtension(spv::E_SPV_KHR_terminate_invocation);
Daniel Kochffccefd2020-11-23 15:41:27 -05003519 builder.makeStatementTerminator(spv::OpTerminateInvocation, "post-terminate-invocation");
Jesse Hall74e8f052020-11-09 08:30:01 -08003520 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003521 case glslang::EOpBreak:
3522 if (breakForLoop.top())
3523 builder.createLoopExit();
3524 else
3525 builder.addSwitchBreak();
3526 break;
3527 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003528 builder.createLoopContinue();
3529 break;
3530 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003531 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003532 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3533 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003534 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3535 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003536 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003537 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3538 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003539 builder.setAccessChainLValue(copyId);
3540 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003541 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003542 }
3543 builder.makeReturn(false, returnId);
3544 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003545 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003546
3547 builder.clearAccessChain();
3548 break;
3549
John Kessenichb9197c82019-08-11 07:41:45 -06003550#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003551 case glslang::EOpDemote:
3552 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3553 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3554 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3555 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05003556 case glslang::EOpTerminateRayKHR:
3557 builder.makeStatementTerminator(spv::OpTerminateRayKHR, "post-terminateRayKHR");
3558 break;
3559 case glslang::EOpIgnoreIntersectionKHR:
3560 builder.makeStatementTerminator(spv::OpIgnoreIntersectionKHR, "post-ignoreIntersectionKHR");
3561 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003562#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003563
John Kessenich140f3df2015-06-26 16:58:36 -06003564 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003565 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003566 break;
3567 }
3568
3569 return false;
3570}
3571
John Kessenich9c14f772019-06-17 08:38:35 -06003572spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003573{
qining25262b32016-05-06 17:25:16 -04003574 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003575 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003576 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003577 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003578 spv::Id result = createSpvConstant(*node);
3579 if (result != spv::NoResult)
3580 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003581 }
3582
3583 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003584 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003585 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3586 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003587
John Kessenichb9197c82019-08-11 07:41:45 -06003588 const bool contains16BitType = node->getType().contains16BitFloat() ||
3589 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003590 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003591 switch (storageClass) {
3592 case spv::StorageClassInput:
3593 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003594 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003595 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003596 break;
John Kessenich18310872018-05-14 22:08:53 -06003597 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003598 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003599 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3600 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003601 else
3602 builder.addCapability(spv::CapabilityStorageUniform16);
3603 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003604#ifndef GLSLANG_WEB
3605 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003606 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003607 builder.addCapability(spv::CapabilityStoragePushConstant16);
3608 break;
John Kessenich18310872018-05-14 22:08:53 -06003609 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003610 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003611 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003612 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3613 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003614#endif
John Kessenich18310872018-05-14 22:08:53 -06003615 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003616 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003617 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003618 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003619 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003620 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003621 }
3622 }
Rex Xuf89ad982017-04-07 23:22:33 +08003623
John Kessenichb9197c82019-08-11 07:41:45 -06003624 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003625 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003626 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003627 builder.addCapability(spv::CapabilityStoragePushConstant8);
3628 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003629 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003630 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003631 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003632 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003633 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003634 } else {
3635 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003636 }
3637 }
3638
John Kessenich140f3df2015-06-26 16:58:36 -06003639 const char* name = node->getName().c_str();
3640 if (glslang::IsAnonymous(name))
3641 name = "";
3642
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003643 spv::Id initializer = spv::NoResult;
3644
3645 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3646 !node->getConstArray().empty()) {
3647 int nextConst = 0;
3648 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3649 node->getConstArray(),
3650 nextConst,
3651 false /* specConst */);
3652 }
3653
John Kessenich435dd802020-06-30 01:27:08 -06003654 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003655}
3656
3657// Return type Id of the sampled type.
3658spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3659{
3660 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003661 case glslang::EbtInt: return builder.makeIntType(32);
3662 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003663 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003664#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003665 case glslang::EbtFloat16:
3666 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3667 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3668 return builder.makeFloatType(16);
Tobski8c1a3a02020-11-04 16:24:23 +00003669 case glslang::EbtInt64: return builder.makeIntType(64);
3670 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3671 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3672 case glslang::EbtUint64: return builder.makeUintType(64);
3673 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3674 builder.addCapability(spv::CapabilityFloat16ImageAMD);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003675#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003676 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003677 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003678 return builder.makeFloatType(32);
3679 }
3680}
3681
John Kessenich8c8505c2016-07-26 12:50:38 -06003682// If node is a swizzle operation, return the type that should be used if
3683// the swizzle base is first consumed by another operation, before the swizzle
3684// is applied.
3685spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3686{
John Kessenichecba76f2017-01-06 00:34:48 -07003687 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003688 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3689 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3690 else
3691 return spv::NoType;
3692}
3693
3694// When inverting a swizzle with a parent op, this function
3695// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003696spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3697 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003698{
3699 std::vector<unsigned> swizzle;
3700 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3701 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3702}
3703
John Kessenich8c8505c2016-07-26 12:50:38 -06003704// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3705void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3706{
3707 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3708 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3709 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3710}
3711
John Kessenich3ac051e2015-12-20 11:29:16 -07003712// Convert from a glslang type to an SPV type, by calling into a
3713// recursive version of this function. This establishes the inherited
3714// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003715spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003716{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003717 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003718}
3719
3720// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003721// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003722// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003723spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003724 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3725 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003726{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003727 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003728
3729 switch (type.getBasicType()) {
3730 case glslang::EbtVoid:
3731 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003732 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003734 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003735 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3736 // a 32-bit int where non-0 means true.
3737 if (explicitLayout != glslang::ElpNone)
3738 spvType = builder.makeUintType(32);
3739 else
3740 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003741 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003742 case glslang::EbtInt:
3743 spvType = builder.makeIntType(32);
3744 break;
3745 case glslang::EbtUint:
3746 spvType = builder.makeUintType(32);
3747 break;
3748 case glslang::EbtFloat:
3749 spvType = builder.makeFloatType(32);
3750 break;
3751#ifndef GLSLANG_WEB
3752 case glslang::EbtDouble:
3753 spvType = builder.makeFloatType(64);
3754 break;
3755 case glslang::EbtFloat16:
3756 spvType = builder.makeFloatType(16);
3757 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003758 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003759 spvType = builder.makeIntType(8);
3760 break;
3761 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003762 spvType = builder.makeUintType(8);
3763 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003764 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003765 spvType = builder.makeIntType(16);
3766 break;
3767 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003768 spvType = builder.makeUintType(16);
3769 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003770 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003771 spvType = builder.makeIntType(64);
3772 break;
3773 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003774 spvType = builder.makeUintType(64);
3775 break;
John Kessenich426394d2015-07-23 10:22:48 -06003776 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003777 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003778 spvType = builder.makeUintType(32);
3779 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003780 case glslang::EbtAccStruct:
3781 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003782 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003783 case glslang::EbtRayQuery:
3784 spvType = builder.makeRayQueryType();
3785 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003786 case glslang::EbtReference:
3787 {
3788 // Make the forward pointer, then recurse to convert the structure type, then
3789 // patch up the forward pointer with a real pointer type.
3790 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3791 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3792 forwardPointers[type.getReferentType()] = forwardId;
3793 }
3794 spvType = forwardPointers[type.getReferentType()];
3795 if (!forwardReferenceOnly) {
3796 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3797 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3798 forwardPointers[type.getReferentType()],
3799 referentType);
3800 }
3801 }
3802 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003803#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003804 case glslang::EbtSampler:
3805 {
3806 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003807 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003808 spvType = builder.makeSamplerType();
3809 } else {
3810 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003811 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3812 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3813 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3814 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003815 // already has both image and sampler, make the combined type
3816 spvType = builder.makeSampledImageType(spvType);
3817 }
John Kessenich55e7d112015-11-15 21:33:39 -07003818 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003819 }
John Kessenich140f3df2015-06-26 16:58:36 -06003820 break;
3821 case glslang::EbtStruct:
3822 case glslang::EbtBlock:
3823 {
3824 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003825 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003826
3827 // Try to share structs for different layouts, but not yet for other
3828 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003829 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003830 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003831 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833
3834 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003835 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003836 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003837 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 }
3839 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003840 case glslang::EbtString:
3841 // no type used for OpString
3842 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003843 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003844 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003845 break;
3846 }
3847
3848 if (type.isMatrix())
3849 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3850 else {
3851 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3852 if (type.getVectorSize() > 1)
3853 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3854 }
3855
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003856 if (type.isCoopMat()) {
3857 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3858 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3859 if (type.getBasicType() == glslang::EbtFloat16)
3860 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003861 if (type.getBasicType() == glslang::EbtUint8 ||
3862 type.getBasicType() == glslang::EbtInt8) {
3863 builder.addCapability(spv::CapabilityInt8);
3864 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003865
3866 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3867 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3868 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3869
3870 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3871 }
3872
John Kessenich140f3df2015-06-26 16:58:36 -06003873 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003874 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3875
John Kessenichc9a80832015-09-12 12:17:44 -06003876 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003877 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003878 // We need to decorate array strides for types needing explicit layout, except blocks.
3879 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003880 // Use a dummy glslang type for querying internal strides of
3881 // arrays of arrays, but using just a one-dimensional array.
3882 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003883 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3884 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003885
3886 // Will compute the higher-order strides here, rather than making a whole
3887 // pile of types and doing repetitive recursion on their contents.
3888 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3889 }
John Kessenichf8842e52016-01-04 19:22:56 -07003890
3891 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003892 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003893 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003894 if (stride > 0)
3895 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003896 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003897 }
3898 } else {
3899 // single-dimensional array, and don't yet have stride
3900
John Kessenichf8842e52016-01-04 19:22:56 -07003901 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003902 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3903 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003904 }
John Kessenich31ed4832015-09-09 17:51:38 -06003905
John Kessenichead86222018-03-28 18:01:20 -06003906 // Do the outer dimension, which might not be known for a runtime-sized array.
3907 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3908 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003909 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003910 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003911#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003912 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003913 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003914 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3915 }
John Kessenichb9197c82019-08-11 07:41:45 -06003916#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003917 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003918 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003919 if (stride > 0)
3920 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003921 }
3922
3923 return spvType;
3924}
3925
John Kessenich0e737842017-03-24 18:38:16 -06003926// TODO: this functionality should exist at a higher level, in creating the AST
3927//
3928// Identify interface members that don't have their required extension turned on.
3929//
3930bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3931{
John Kessenicha28f7a72019-08-06 07:00:58 -06003932#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003933 auto& extensions = glslangIntermediate->getRequestedExtensions();
3934
Rex Xubcf291a2017-03-29 23:01:36 +08003935 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3936 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3937 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003938 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3939 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3940 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003941
3942 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3943 if (member.getFieldName() == "gl_ViewportMask" &&
3944 extensions.find("GL_NV_viewport_array2") == extensions.end())
3945 return true;
3946 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3947 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3948 return true;
3949 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3950 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3951 return true;
3952 }
3953#endif
John Kessenich0e737842017-03-24 18:38:16 -06003954
3955 return false;
3956};
3957
John Kessenich6090df02016-06-30 21:18:02 -06003958// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3959// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3960// Mutually recursive with convertGlslangToSpvType().
3961spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3962 const glslang::TTypeList* glslangMembers,
3963 glslang::TLayoutPacking explicitLayout,
3964 const glslang::TQualifier& qualifier)
3965{
3966 // Create a vector of struct types for SPIR-V to consume
3967 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003968 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3969 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003970 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003971 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3972 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3973 if (glslangMember.hiddenMember()) {
3974 ++memberDelta;
3975 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003976 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003977 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003978 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003979 if (filterMember(glslangMember)) {
3980 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003981 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003982 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003983 }
Roy05a5b532020-01-03 16:21:34 +08003984 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003985 }
John Kessenich6090df02016-06-30 21:18:02 -06003986 // modify just this child's view of the qualifier
3987 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3988 InheritQualifiers(memberQualifier, qualifier);
3989
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003990 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003991 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003992 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003993
3994 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003995 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3996 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003997
3998 // Make forward pointers for any pointer members, and create a list of members to
3999 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06004000 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004001 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
4002 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
4003 }
4004 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004005 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4006 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004007 } else {
4008 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004009 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4010 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004011 }
John Kessenich6090df02016-06-30 21:18:02 -06004012 }
4013 }
4014
4015 // Make the SPIR-V type
4016 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06004017 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06004018 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
4019
4020 // Decorate it
4021 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
4022
John Kessenichd72f4882019-01-16 14:55:37 +07004023 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004024 auto it = deferredForwardPointers[i];
4025 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
4026 }
4027
John Kessenich6090df02016-06-30 21:18:02 -06004028 return spvType;
4029}
4030
4031void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
4032 const glslang::TTypeList* glslangMembers,
4033 glslang::TLayoutPacking explicitLayout,
4034 const glslang::TQualifier& qualifier,
4035 spv::Id spvType)
4036{
4037 // Name and decorate the non-hidden members
4038 int offset = -1;
4039 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08004040 bool memberLocationInvalid = type.isArrayOfArrays() ||
4041 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06004042 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4043 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4044 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06004045 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08004046 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06004047 if (filterMember(glslangMember))
4048 continue;
4049 }
John Kessenich6090df02016-06-30 21:18:02 -06004050
4051 // modify just this child's view of the qualifier
4052 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4053 InheritQualifiers(memberQualifier, qualifier);
4054
4055 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07004056 if (member < 0)
4057 continue;
4058
4059 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
4060 builder.addMemberDecoration(spvType, member,
4061 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
4062 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
4063 // Add interpolation and auxiliary storage decorations only to
4064 // top-level members of Input and Output storage classes
4065 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4066 type.getQualifier().storage == glslang::EvqVaryingOut) {
4067 if (type.getBasicType() == glslang::EbtBlock ||
4068 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4069 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4070 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004071#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004072 addMeshNVDecoration(spvType, member, memberQualifier);
4073#endif
John Kessenich6090df02016-06-30 21:18:02 -06004074 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004075 }
4076 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004077
John Kessenichb9197c82019-08-11 07:41:45 -06004078#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004079 if (type.getBasicType() == glslang::EbtBlock &&
4080 qualifier.storage == glslang::EvqBuffer) {
4081 // Add memory decorations only to top-level members of shader storage block
4082 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004083 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004084 for (unsigned int i = 0; i < memory.size(); ++i)
4085 builder.addMemberDecoration(spvType, member, memory[i]);
4086 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004087
John Kessenichb9197c82019-08-11 07:41:45 -06004088#endif
John Kessenich6090df02016-06-30 21:18:02 -06004089
John Kessenich5d610ee2018-03-07 18:05:55 -07004090 // Location assignment was already completed correctly by the front end,
4091 // just track whether a member needs to be decorated.
4092 // Ignore member locations if the container is an array, as that's
4093 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004094 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004095 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004096
John Kessenich5d610ee2018-03-07 18:05:55 -07004097 if (qualifier.hasLocation()) // track for upcoming inheritance
4098 locationOffset += glslangIntermediate->computeTypeLocationSize(
4099 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004100
John Kessenich5d610ee2018-03-07 18:05:55 -07004101 // component, XFB, others
4102 if (glslangMember.getQualifier().hasComponent())
4103 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4104 glslangMember.getQualifier().layoutComponent);
4105 if (glslangMember.getQualifier().hasXfbOffset())
4106 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4107 glslangMember.getQualifier().layoutXfbOffset);
4108 else if (explicitLayout != glslang::ElpNone) {
4109 // figure out what to do with offset, which is accumulating
4110 int nextOffset;
4111 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4112 if (offset >= 0)
4113 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4114 offset = nextOffset;
4115 }
John Kessenich6090df02016-06-30 21:18:02 -06004116
John Kessenich5d610ee2018-03-07 18:05:55 -07004117 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4118 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4119 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004120
John Kessenich5d610ee2018-03-07 18:05:55 -07004121 // built-in variable decorations
4122 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4123 if (builtIn != spv::BuiltInMax)
4124 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004125
John Kessenichb9197c82019-08-11 07:41:45 -06004126#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004127 // nonuniform
4128 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4129
John Kessenichead86222018-03-28 18:01:20 -06004130 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4131 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4132 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4133 memberQualifier.semanticName);
4134 }
4135
John Kessenich5d610ee2018-03-07 18:05:55 -07004136 if (builtIn == spv::BuiltInLayer) {
4137 // SPV_NV_viewport_array2 extension
4138 if (glslangMember.getQualifier().layoutViewportRelative){
4139 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4140 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4141 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004142 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004143 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4144 builder.addMemberDecoration(spvType, member,
4145 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4146 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4147 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4148 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004149 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004150 }
4151 if (glslangMember.getQualifier().layoutPassthrough) {
4152 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4153 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4154 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4155 }
chaoc771d89f2017-01-13 01:10:53 -08004156#endif
John Kessenich6090df02016-06-30 21:18:02 -06004157 }
4158
4159 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004160 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4161 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004162}
4163
John Kessenich6c292d32016-02-15 20:58:50 -07004164// Turn the expression forming the array size into an id.
4165// This is not quite trivial, because of specialization constants.
4166// Sometimes, a raw constant is turned into an Id, and sometimes
4167// a specialization constant expression is.
4168spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4169{
4170 // First, see if this is sized with a node, meaning a specialization constant:
4171 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4172 if (specNode != nullptr) {
4173 builder.clearAccessChain();
4174 specNode->traverse(this);
4175 return accessChainLoad(specNode->getAsTyped()->getType());
4176 }
qining25262b32016-05-06 17:25:16 -04004177
John Kessenich6c292d32016-02-15 20:58:50 -07004178 // Otherwise, need a compile-time (front end) size, get it:
4179 int size = arraySizes.getDimSize(dim);
4180 assert(size > 0);
4181 return builder.makeUintConstant(size);
4182}
4183
John Kessenich103bef92016-02-08 21:38:15 -07004184// Wrap the builder's accessChainLoad to:
4185// - localize handling of RelaxedPrecision
4186// - use the SPIR-V inferred type instead of another conversion of the glslang type
4187// (avoids unnecessary work and possible type punning for structures)
4188// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004189spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4190{
John Kessenich103bef92016-02-08 21:38:15 -07004191 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004192
4193 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4194 coherentFlags |= TranslateCoherent(type);
4195
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004196 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004197 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004198
John Kessenich5611c6d2018-04-05 11:25:02 -06004199 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
greg-lunarg639f5462020-11-12 11:10:07 -07004200 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004201 TranslateNonUniformDecoration(type.getQualifier()),
4202 nominalTypeId,
4203 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4204 TranslateMemoryScope(coherentFlags),
4205 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004206
4207 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004208 if (type.getBasicType() == glslang::EbtBool) {
4209 if (builder.isScalarType(nominalTypeId)) {
4210 // Conversion for bool
4211 spv::Id boolType = builder.makeBoolType();
4212 if (nominalTypeId != boolType)
4213 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4214 } else if (builder.isVectorType(nominalTypeId)) {
4215 // Conversion for bvec
4216 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4217 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4218 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004219 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4220 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004221 }
4222 }
John Kessenich103bef92016-02-08 21:38:15 -07004223
4224 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004225}
4226
Rex Xu27253232016-02-23 17:51:09 +08004227// Wrap the builder's accessChainStore to:
4228// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004229//
4230// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004231void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4232{
4233 // Need to convert to abstract types when necessary
4234 if (type.getBasicType() == glslang::EbtBool) {
4235 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4236
4237 if (builder.isScalarType(nominalTypeId)) {
4238 // Conversion for bool
4239 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004240 if (nominalTypeId != boolType) {
4241 // keep these outside arguments, for determinant order-of-evaluation
4242 spv::Id one = builder.makeUintConstant(1);
4243 spv::Id zero = builder.makeUintConstant(0);
4244 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4245 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004246 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004247 } else if (builder.isVectorType(nominalTypeId)) {
4248 // Conversion for bvec
4249 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4250 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004251 if (nominalTypeId != bvecType) {
4252 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004253 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4254 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4255 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004256 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004257 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4258 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004259 }
4260 }
4261
Jeff Bolz36831c92018-09-05 10:11:41 -05004262 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4263 coherentFlags |= TranslateCoherent(type);
4264
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004265 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004266 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004267
greg-lunarg639f5462020-11-12 11:10:07 -07004268 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004269 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4270 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004271 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004272}
4273
John Kessenich4bf71552016-09-02 11:20:21 -06004274// For storing when types match at the glslang level, but not might match at the
4275// SPIR-V level.
4276//
4277// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004278// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004279// as in a member-decorated way.
4280//
4281// NOTE: This function can handle any store request; if it's not special it
4282// simplifies to a simple OpStore.
4283//
4284// Implicitly uses the existing builder.accessChain as the storage target.
4285void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4286{
John Kessenichb3e24e42016-09-11 12:33:43 -06004287 // we only do the complex path here if it's an aggregate
4288 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004289 accessChainStore(type, rValue);
4290 return;
4291 }
4292
John Kessenichb3e24e42016-09-11 12:33:43 -06004293 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004294 spv::Id rType = builder.getTypeId(rValue);
4295 spv::Id lValue = builder.accessChainGetLValue();
4296 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4297 if (lType == rType) {
4298 accessChainStore(type, rValue);
4299 return;
4300 }
4301
John Kessenichb3e24e42016-09-11 12:33:43 -06004302 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004303 // where the two types were the same type in GLSL. This requires member
4304 // by member copy, recursively.
4305
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004306 // SPIR-V 1.4 added an instruction to do help do this.
4307 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4308 // However, bool in uniform space is changed to int, so
4309 // OpCopyLogical does not work for that.
4310 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4311 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4312 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4313 if (lBool == rBool) {
4314 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4315 accessChainStore(type, logicalCopy);
4316 return;
4317 }
4318 }
4319
John Kessenichb3e24e42016-09-11 12:33:43 -06004320 // If an array, copy element by element.
4321 if (type.isArray()) {
4322 glslang::TType glslangElementType(type, 0);
4323 spv::Id elementRType = builder.getContainedTypeId(rType);
4324 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4325 // get the source member
4326 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004327
John Kessenichb3e24e42016-09-11 12:33:43 -06004328 // set up the target storage
4329 builder.clearAccessChain();
4330 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004331 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4332 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004333
John Kessenichb3e24e42016-09-11 12:33:43 -06004334 // store the member
4335 multiTypeStore(glslangElementType, elementRValue);
4336 }
4337 } else {
4338 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004339
John Kessenichb3e24e42016-09-11 12:33:43 -06004340 // loop over structure members
4341 const glslang::TTypeList& members = *type.getStruct();
4342 for (int m = 0; m < (int)members.size(); ++m) {
4343 const glslang::TType& glslangMemberType = *members[m].type;
4344
4345 // get the source member
4346 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4347 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4348
4349 // set up the target storage
4350 builder.clearAccessChain();
4351 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004352 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4353 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004354
4355 // store the member
4356 multiTypeStore(glslangMemberType, memberRValue);
4357 }
John Kessenich4bf71552016-09-02 11:20:21 -06004358 }
4359}
4360
John Kessenichf85e8062015-12-19 13:57:10 -07004361// Decide whether or not this type should be
4362// decorated with offsets and strides, and if so
4363// whether std140 or std430 rules should be applied.
4364glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004365{
John Kessenichf85e8062015-12-19 13:57:10 -07004366 // has to be a block
4367 if (type.getBasicType() != glslang::EbtBlock)
4368 return glslang::ElpNone;
4369
Chao Chen3c366992018-09-19 11:41:59 -07004370 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004371 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004372 type.getQualifier().storage != glslang::EvqBuffer &&
4373 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004374 return glslang::ElpNone;
4375
4376 // return the layout to use
4377 switch (type.getQualifier().layoutPacking) {
4378 case glslang::ElpStd140:
4379 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004380 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004381 return type.getQualifier().layoutPacking;
4382 default:
4383 return glslang::ElpNone;
4384 }
John Kessenich31ed4832015-09-09 17:51:38 -06004385}
4386
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004387// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004388int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4389 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004390{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004391 int size;
John Kessenich49987892015-12-29 17:11:44 -07004392 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004393 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4394 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004395
4396 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004397}
4398
John Kessenich49987892015-12-29 17:11:44 -07004399// 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 -07004400// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004401int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4402 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004403{
John Kessenich49987892015-12-29 17:11:44 -07004404 glslang::TType elementType;
4405 elementType.shallowCopy(matrixType);
4406 elementType.clearArraySizes();
4407
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004408 int size;
John Kessenich49987892015-12-29 17:11:44 -07004409 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004410 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4411 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004412
4413 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004414}
4415
John Kessenich5e4b1242015-08-06 22:53:06 -06004416// Given a member type of a struct, realign the current offset for it, and compute
4417// the next (not yet aligned) offset for the next member, which will get aligned
4418// on the next call.
4419// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4420// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4421// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004422void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4423 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004424{
4425 // this will get a positive value when deemed necessary
4426 nextOffset = -1;
4427
John Kessenich5e4b1242015-08-06 22:53:06 -06004428 // override anything in currentOffset with user-set offset
4429 if (memberType.getQualifier().hasOffset())
4430 currentOffset = memberType.getQualifier().layoutOffset;
4431
4432 // It could be that current linker usage in glslang updated all the layoutOffset,
4433 // in which case the following code does not matter. But, that's not quite right
4434 // once cross-compilation unit GLSL validation is done, as the original user
4435 // settings are needed in layoutOffset, and then the following will come into play.
4436
John Kessenichf85e8062015-12-19 13:57:10 -07004437 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004438 if (! memberType.getQualifier().hasOffset())
4439 currentOffset = -1;
4440
4441 return;
4442 }
4443
John Kessenichf85e8062015-12-19 13:57:10 -07004444 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004445 if (currentOffset < 0)
4446 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004447
John Kessenich5e4b1242015-08-06 22:53:06 -06004448 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4449 // but possibly not yet correctly aligned.
4450
4451 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004452 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004453 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4454 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004455
4456 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004457 // TODO: make this consistent in early phases of code:
4458 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4459 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4460 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004461 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004462 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004463 int dummySize;
4464 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4465 if (componentAlignment <= 4)
4466 memberAlignment = componentAlignment;
4467 }
4468
4469 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004470 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004471
4472 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004473 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4474 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004475 glslang::RoundToPow2(currentOffset, 16);
4476
John Kessenich5e4b1242015-08-06 22:53:06 -06004477 nextOffset = currentOffset + memberSize;
4478}
4479
David Netoa901ffe2016-06-08 14:11:40 +01004480void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004481{
David Netoa901ffe2016-06-08 14:11:40 +01004482 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4483 switch (glslangBuiltIn)
4484 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004485 case glslang::EbvPointSize:
4486#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004487 case glslang::EbvClipDistance:
4488 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004489 case glslang::EbvViewportMaskNV:
4490 case glslang::EbvSecondaryPositionNV:
4491 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004492 case glslang::EbvPositionPerViewNV:
4493 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004494 case glslang::EbvTaskCountNV:
4495 case glslang::EbvPrimitiveCountNV:
4496 case glslang::EbvPrimitiveIndicesNV:
4497 case glslang::EbvClipDistancePerViewNV:
4498 case glslang::EbvCullDistancePerViewNV:
4499 case glslang::EbvLayerPerViewNV:
4500 case glslang::EbvMeshViewCountNV:
4501 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004502#endif
David Netoa901ffe2016-06-08 14:11:40 +01004503 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4504 // Alternately, we could just call this for any glslang built-in, since the
4505 // capability already guards against duplicates.
4506 TranslateBuiltInDecoration(glslangBuiltIn, false);
4507 break;
4508 default:
4509 // Capabilities were already generated when the struct was declared.
4510 break;
4511 }
John Kessenichebb50532016-05-16 19:22:05 -06004512}
4513
John Kessenich6fccb3c2016-09-19 16:01:41 -06004514bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004515{
John Kessenicheee9d532016-09-19 18:09:30 -06004516 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004517}
4518
John Kessenichd41993d2017-09-10 15:21:05 -06004519// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004520// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4521// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004522bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004523{
John Kessenich6a14f782017-12-04 02:48:10 -07004524 assert(qualifier == glslang::EvqIn ||
4525 qualifier == glslang::EvqOut ||
4526 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004527 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004528 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004529 return qualifier != glslang::EvqConstReadOnly &&
4530 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004531}
4532
4533// Is parameter pass-by-original?
4534bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4535 bool implicitThisParam)
4536{
4537 if (implicitThisParam) // implicit this
4538 return true;
4539 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004540 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004541 return paramType.containsOpaque() || // sampler, etc.
4542 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4543}
4544
John Kessenich140f3df2015-06-26 16:58:36 -06004545// Make all the functions, skeletally, without actually visiting their bodies.
4546void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4547{
John Kessenich8985fc92020-03-03 10:25:07 -07004548 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4549 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004550 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4551 if (paramPrecision != spv::NoPrecision)
4552 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004553 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004554 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004555 // Original and non-writable params pass the pointer directly and
4556 // use restrict/aliased, others are stored to a pointer in Function
4557 // memory and use RestrictPointer/AliasedPointer.
4558 if (originalParam(type.getQualifier().storage, type, false) ||
4559 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004560 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4561 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004562 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004563 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4564 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004565 }
4566 }
John Kessenichfad62972017-07-18 02:35:46 -06004567 };
4568
John Kessenich140f3df2015-06-26 16:58:36 -06004569 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4570 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004571 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004572 continue;
4573
4574 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004575 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004576 //
qining25262b32016-05-06 17:25:16 -04004577 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004578 // function. What it is an address of varies:
4579 //
John Kessenich4bf71552016-09-02 11:20:21 -06004580 // - "in" parameters not marked as "const" can be written to without modifying the calling
4581 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004582 //
4583 // - "const in" parameters can just be the r-value, as no writes need occur.
4584 //
John Kessenich4bf71552016-09-02 11:20:21 -06004585 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4586 // 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 -06004587
4588 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004589 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004590 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4591
John Kessenich155d3512019-08-08 23:29:20 -06004592#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004593 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4594 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004595#else
4596 bool implicitThis = false;
4597#endif
John Kessenich37789792017-03-21 23:56:40 -06004598
John Kessenichfad62972017-07-18 02:35:46 -06004599 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004600 for (int p = 0; p < (int)parameters.size(); ++p) {
4601 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4602 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004603 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004604 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004605 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004606 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4607 else
John Kessenich4bf71552016-09-02 11:20:21 -06004608 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004610 paramTypes.push_back(typeId);
4611 }
4612
4613 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004614 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4615 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004616 glslFunction->getName().c_str(), paramTypes,
4617 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004618 if (implicitThis)
4619 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004620
4621 // Track function to emit/call later
4622 functionMap[glslFunction->getName().c_str()] = function;
4623
4624 // Set the parameter id's
4625 for (int p = 0; p < (int)parameters.size(); ++p) {
4626 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4627 // give a name too
4628 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004629
4630 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004631 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004632 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004633 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004634 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004635 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004636 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004637 }
4638 }
4639}
4640
4641// Process all the initializers, while skipping the functions and link objects
4642void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4643{
4644 builder.setBuildPoint(shaderEntry->getLastBlock());
4645 for (int i = 0; i < (int)initializers.size(); ++i) {
4646 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004647 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4648 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004649
4650 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004651 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004652 initializer->traverse(this);
4653 }
4654 }
4655}
Daniel Kochffccefd2020-11-23 15:41:27 -05004656// Walk over all linker objects to create a map for payload and callable data linker objects
4657// and their location to be used during codegen for OpTraceKHR and OpExecuteCallableKHR
4658// This is done here since it is possible that these linker objects are not be referenced in the AST
4659void TGlslangToSpvTraverser::collectRayTracingLinkerObjects()
4660{
4661 glslang::TIntermAggregate* linkerObjects = glslangIntermediate->findLinkerObjects();
4662 for (auto& objSeq : linkerObjects->getSequence()) {
4663 auto objNode = objSeq->getAsSymbolNode();
4664 if (objNode != nullptr) {
4665 if (objNode->getQualifier().hasLocation()) {
4666 unsigned int location = objNode->getQualifier().layoutLocation;
4667 auto st = objNode->getQualifier().storage;
4668 int set;
4669 switch (st)
4670 {
4671 case glslang::EvqPayload:
4672 case glslang::EvqPayloadIn:
4673 set = 0;
4674 break;
4675 case glslang::EvqCallableData:
4676 case glslang::EvqCallableDataIn:
4677 set = 1;
4678 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004679
Daniel Kochffccefd2020-11-23 15:41:27 -05004680 default:
4681 set = -1;
4682 }
4683 if (set != -1)
4684 locationToSymbol[set].insert(std::make_pair(location, objNode));
4685 }
4686 }
4687 }
4688}
John Kessenich140f3df2015-06-26 16:58:36 -06004689// Process all the functions, while skipping initializers.
4690void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4691{
4692 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4693 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004694 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004695 node->traverse(this);
4696 }
4697}
4698
4699void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4700{
qining25262b32016-05-06 17:25:16 -04004701 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004702 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004703 currentFunction = functionMap[node->getName().c_str()];
4704 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004705 builder.setBuildPoint(functionBlock);
4706}
4707
John Kessenich8985fc92020-03-03 10:25:07 -07004708void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4709 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004710{
Rex Xufc618912015-09-09 16:42:49 +08004711 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004712
4713 glslang::TSampler sampler = {};
4714 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004715#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004716 bool f16ShadowCompare = false;
4717#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004718 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004719 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4720 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004721#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004722 f16ShadowCompare = sampler.shadow &&
4723 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004724#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004725 }
4726
John Kessenich140f3df2015-06-26 16:58:36 -06004727 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4728 builder.clearAccessChain();
4729 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004730
John Kessenicha28f7a72019-08-06 07:00:58 -06004731#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004732 // Special case l-value operands
4733 bool lvalue = false;
4734 switch (node.getOp()) {
4735 case glslang::EOpImageAtomicAdd:
4736 case glslang::EOpImageAtomicMin:
4737 case glslang::EOpImageAtomicMax:
4738 case glslang::EOpImageAtomicAnd:
4739 case glslang::EOpImageAtomicOr:
4740 case glslang::EOpImageAtomicXor:
4741 case glslang::EOpImageAtomicExchange:
4742 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004743 case glslang::EOpImageAtomicLoad:
4744 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004745 if (i == 0)
4746 lvalue = true;
4747 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004748 case glslang::EOpSparseImageLoad:
4749 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4750 lvalue = true;
4751 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004752 case glslang::EOpSparseTexture:
4753 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4754 lvalue = true;
4755 break;
4756 case glslang::EOpSparseTextureClamp:
4757 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4758 lvalue = true;
4759 break;
4760 case glslang::EOpSparseTextureLod:
4761 case glslang::EOpSparseTextureOffset:
4762 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4763 lvalue = true;
4764 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004765 case glslang::EOpSparseTextureFetch:
4766 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4767 lvalue = true;
4768 break;
4769 case glslang::EOpSparseTextureFetchOffset:
4770 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4771 lvalue = true;
4772 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004773 case glslang::EOpSparseTextureLodOffset:
4774 case glslang::EOpSparseTextureGrad:
4775 case glslang::EOpSparseTextureOffsetClamp:
4776 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4777 lvalue = true;
4778 break;
4779 case glslang::EOpSparseTextureGradOffset:
4780 case glslang::EOpSparseTextureGradClamp:
4781 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4782 lvalue = true;
4783 break;
4784 case glslang::EOpSparseTextureGradOffsetClamp:
4785 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4786 lvalue = true;
4787 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004788 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004789 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4790 lvalue = true;
4791 break;
4792 case glslang::EOpSparseTextureGatherOffset:
4793 case glslang::EOpSparseTextureGatherOffsets:
4794 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4795 lvalue = true;
4796 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004797 case glslang::EOpSparseTextureGatherLod:
4798 if (i == 3)
4799 lvalue = true;
4800 break;
4801 case glslang::EOpSparseTextureGatherLodOffset:
4802 case glslang::EOpSparseTextureGatherLodOffsets:
4803 if (i == 4)
4804 lvalue = true;
4805 break;
Rex Xu129799a2017-07-05 17:23:28 +08004806 case glslang::EOpSparseImageLoadLod:
4807 if (i == 3)
4808 lvalue = true;
4809 break;
Chao Chen3a137962018-09-19 11:41:27 -07004810 case glslang::EOpImageSampleFootprintNV:
4811 if (i == 4)
4812 lvalue = true;
4813 break;
4814 case glslang::EOpImageSampleFootprintClampNV:
4815 case glslang::EOpImageSampleFootprintLodNV:
4816 if (i == 5)
4817 lvalue = true;
4818 break;
4819 case glslang::EOpImageSampleFootprintGradNV:
4820 if (i == 6)
4821 lvalue = true;
4822 break;
4823 case glslang::EOpImageSampleFootprintGradClampNV:
4824 if (i == 7)
4825 lvalue = true;
4826 break;
Rex Xufc618912015-09-09 16:42:49 +08004827 default:
4828 break;
4829 }
4830
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004831 if (lvalue) {
greg-lunarg639f5462020-11-12 11:10:07 -07004832 spv::Id lvalue_id = builder.accessChainGetLValue();
4833 arguments.push_back(lvalue_id);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004834 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
greg-lunarg639f5462020-11-12 11:10:07 -07004835 builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004836 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4837 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004838#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004839 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004840 }
4841}
4842
John Kessenichfc51d282015-08-19 13:34:18 -06004843void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004844{
John Kessenichfc51d282015-08-19 13:34:18 -06004845 builder.clearAccessChain();
4846 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004847 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004848}
John Kessenich140f3df2015-06-26 16:58:36 -06004849
John Kessenichfc51d282015-08-19 13:34:18 -06004850spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4851{
John Kesseniche485c7a2017-05-31 18:50:53 -06004852 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004853 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004854
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004855 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004856
John Kessenichfc51d282015-08-19 13:34:18 -06004857 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004858
John Kessenichf43c7392019-03-31 10:51:57 -06004859 const glslang::TType &imageType = node->getAsAggregate()
4860 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4861 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004862 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004863#ifdef GLSLANG_WEB
4864 const bool f16ShadowCompare = false;
4865#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004866 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004867 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4868 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004869#endif
4870
John Kessenichf43c7392019-03-31 10:51:57 -06004871 const auto signExtensionMask = [&]() {
4872 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4873 if (sampler.type == glslang::EbtUint)
4874 return spv::ImageOperandsZeroExtendMask;
4875 else if (sampler.type == glslang::EbtInt)
4876 return spv::ImageOperandsSignExtendMask;
4877 }
4878 return spv::ImageOperandsMaskNone;
4879 };
4880
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004881 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4882
John Kessenichfc51d282015-08-19 13:34:18 -06004883 std::vector<spv::Id> arguments;
4884 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004885 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004886 else
4887 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004888 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004889
4890 spv::Builder::TextureParameters params = { };
4891 params.sampler = arguments[0];
4892
Rex Xu04db3f52015-09-16 11:44:02 +08004893 glslang::TCrackedTextureOp cracked;
4894 node->crackTexture(sampler, cracked);
4895
amhagan05506bb2017-06-13 16:53:02 -04004896 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004897
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004898 if (builder.isSampledImage(params.sampler) &&
4899 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4900 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4901 if (imageType.getQualifier().isNonUniform()) {
4902 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4903 }
4904 }
John Kessenichfc51d282015-08-19 13:34:18 -06004905 // Check for queries
4906 if (cracked.query) {
4907 switch (node->getOp()) {
4908 case glslang::EOpImageQuerySize:
4909 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004910 if (arguments.size() > 1) {
4911 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004912 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004913 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004914 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004915#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004916 case glslang::EOpImageQuerySamples:
4917 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004918 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004919 case glslang::EOpTextureQueryLod:
4920 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004921 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004922 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004923 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004924 case glslang::EOpSparseTexelsResident:
4925 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004926#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004927 default:
4928 assert(0);
4929 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004930 }
John Kessenich140f3df2015-06-26 16:58:36 -06004931 }
4932
LoopDawg4425f242018-02-18 11:40:01 -07004933 int components = node->getType().getVectorSize();
4934
4935 if (node->getOp() == glslang::EOpTextureFetch) {
4936 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4937 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4938 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4939 // here around e.g. which ones return scalars or other types.
4940 components = 4;
4941 }
4942
4943 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4944
4945 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4946
Rex Xufc618912015-09-09 16:42:49 +08004947 // Check for image functions other than queries
4948 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004949 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004950 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004951 spv::IdImmediate image = { true, *(opIt++) };
4952 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004953
4954 // Handle subpass operations
4955 // TODO: GLSL should change to have the "MS" only on the type rather than the
4956 // built-in function.
4957 if (cracked.subpass) {
4958 // add on the (0,0) coordinate
4959 spv::Id zero = builder.makeIntConstant(0);
4960 std::vector<spv::Id> comps;
4961 comps.push_back(zero);
4962 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004963 spv::IdImmediate coord = { true,
4964 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4965 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004966 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4967 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004968 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004969 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4970 }
4971 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004972 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004973 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004974 spv::IdImmediate imageOperand = { true, *(opIt++) };
4975 operands.push_back(imageOperand);
4976 }
John Kessenich6c292d32016-02-15 20:58:50 -07004977 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004978 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4979 builder.setPrecision(result, precision);
4980 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004981 }
4982
John Kessenich149afc32018-08-14 13:31:43 -06004983 spv::IdImmediate coord = { true, *(opIt++) };
4984 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004985 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004986 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004987 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004988 mask = mask | spv::ImageOperandsSampleMask;
4989 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004990 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004991 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4992 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004993 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004994 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004995 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4996 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004997 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004998 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004999 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5000 operands.push_back(imageOperands);
5001 }
5002 if (mask & spv::ImageOperandsSampleMask) {
5003 spv::IdImmediate imageOperand = { true, *opIt++ };
5004 operands.push_back(imageOperand);
5005 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005006 if (mask & spv::ImageOperandsLodMask) {
5007 spv::IdImmediate imageOperand = { true, *opIt++ };
5008 operands.push_back(imageOperand);
5009 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005010 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005011 spv::IdImmediate imageOperand = { true,
5012 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005013 operands.push_back(imageOperand);
5014 }
5015
John Kessenich149afc32018-08-14 13:31:43 -06005016 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005017 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06005018
John Kessenich149afc32018-08-14 13:31:43 -06005019 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07005020 builder.setPrecision(result[0], precision);
5021
5022 // If needed, add a conversion constructor to the proper size.
5023 if (components != node->getType().getVectorSize())
5024 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5025
5026 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08005027 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08005028
Jeff Bolz36831c92018-09-05 10:11:41 -05005029 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005030 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06005031 spv::IdImmediate texel = { true, *(opIt + 1) };
5032 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06005033 } else {
5034 spv::IdImmediate texel = { true, *opIt };
5035 operands.push_back(texel);
5036 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005037
5038 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005039 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005040 mask = mask | spv::ImageOperandsSampleMask;
5041 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005042 if (cracked.lod) {
5043 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5044 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5045 mask = mask | spv::ImageOperandsLodMask;
5046 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005047 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5048 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005049 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005050 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005051 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5052 operands.push_back(imageOperands);
5053 }
5054 if (mask & spv::ImageOperandsSampleMask) {
5055 spv::IdImmediate imageOperand = { true, *opIt++ };
5056 operands.push_back(imageOperand);
5057 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005058 if (mask & spv::ImageOperandsLodMask) {
5059 spv::IdImmediate imageOperand = { true, *opIt++ };
5060 operands.push_back(imageOperand);
5061 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005062 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005063 spv::IdImmediate imageOperand = { true,
5064 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005065 operands.push_back(imageOperand);
5066 }
5067
John Kessenich56bab042015-09-16 10:54:31 -06005068 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06005069 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005070 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06005071 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06005072 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
5073 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08005074 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06005075 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08005076 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
5077
Jeff Bolz36831c92018-09-05 10:11:41 -05005078 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005079 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005080 mask = mask | spv::ImageOperandsSampleMask;
5081 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005082 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005083 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5084 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5085
Jeff Bolz36831c92018-09-05 10:11:41 -05005086 mask = mask | spv::ImageOperandsLodMask;
5087 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005088 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5089 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005090 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005091 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005092 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06005093 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05005094 }
5095 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06005096 spv::IdImmediate imageOperand = { true, *opIt++ };
5097 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05005098 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005099 if (mask & spv::ImageOperandsLodMask) {
5100 spv::IdImmediate imageOperand = { true, *opIt++ };
5101 operands.push_back(imageOperand);
5102 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005103 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005104 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5105 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005106 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005107 }
5108
5109 // Create the return type that was a special structure
5110 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005111 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005112 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5113 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5114
5115 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5116
5117 // Decode the return type
5118 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5119 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005120 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005121 // Process image atomic operations
5122
5123 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5124 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005125 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005126 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005127 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005128
Jeff Bolz36831c92018-09-05 10:11:41 -05005129 spv::Id resultTypeId;
5130 // imageAtomicStore has a void return type so base the pointer type on
5131 // the type of the value operand.
5132 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005133 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005134 } else {
5135 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5136 }
John Kessenich56bab042015-09-16 10:54:31 -06005137 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005138 if (imageType.getQualifier().nonUniform) {
5139 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5140 }
Rex Xufc618912015-09-09 16:42:49 +08005141
5142 std::vector<spv::Id> operands;
5143 operands.push_back(pointer);
5144 for (; opIt != arguments.end(); ++opIt)
5145 operands.push_back(*opIt);
5146
John Kessenich8985fc92020-03-03 10:25:07 -07005147 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5148 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005149 }
5150 }
5151
John Kessenicha28f7a72019-08-06 07:00:58 -06005152#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005153 // Check for fragment mask functions other than queries
5154 if (cracked.fragMask) {
5155 assert(sampler.ms);
5156
5157 auto opIt = arguments.begin();
5158 std::vector<spv::Id> operands;
5159
amhagan05506bb2017-06-13 16:53:02 -04005160 operands.push_back(params.sampler);
5161 ++opIt;
5162
5163 if (sampler.isSubpass()) {
5164 // add on the (0,0) coordinate
5165 spv::Id zero = builder.makeIntConstant(0);
5166 std::vector<spv::Id> comps;
5167 comps.push_back(zero);
5168 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005169 operands.push_back(builder.makeCompositeConstant(
5170 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005171 }
5172
5173 for (; opIt != arguments.end(); ++opIt)
5174 operands.push_back(*opIt);
5175
5176 spv::Op fragMaskOp = spv::OpNop;
5177 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5178 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5179 else if (node->getOp() == glslang::EOpFragmentFetch)
5180 fragMaskOp = spv::OpFragmentFetchAMD;
5181
5182 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5183 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5184 return builder.createOp(fragMaskOp, resultType(), operands);
5185 }
5186#endif
5187
Rex Xufc618912015-09-09 16:42:49 +08005188 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005189 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005190 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005191 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005192
John Kessenichfc51d282015-08-19 13:34:18 -06005193 // check for bias argument
5194 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005195 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005196 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005197 if (cracked.gather)
5198 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005199
5200 if (f16ShadowCompare)
5201 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005202 if (cracked.offset)
5203 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005204 else if (cracked.offsets)
5205 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005206 if (cracked.grad)
5207 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005208 if (cracked.lodClamp)
5209 ++nonBiasArgCount;
5210 if (sparse)
5211 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005212 if (imageFootprint)
5213 //Following three extra arguments
5214 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5215 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005216 if ((int)arguments.size() > nonBiasArgCount)
5217 bias = true;
5218 }
5219
John Kessenicha28f7a72019-08-06 07:00:58 -06005220#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005221 if (cracked.gather) {
5222 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5223 if (bias || cracked.lod ||
5224 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5225 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005226 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005227 }
5228 }
5229#endif
5230
John Kessenichfc51d282015-08-19 13:34:18 -06005231 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005232
John Kessenichfc51d282015-08-19 13:34:18 -06005233 params.coords = arguments[1];
5234 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005235 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005236
5237 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005238 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005239 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005240 ++extraArgs;
5241 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005242 params.Dref = arguments[2];
5243 ++extraArgs;
5244 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005245 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005246 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005247 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005248 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005249 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005250 dRefComp = builder.getNumComponents(params.coords) - 1;
5251 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005252 params.Dref = builder.createCompositeExtract(params.coords,
5253 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005254 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005255
5256 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005257 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005258 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005259 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005260 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5261 !(glslangIntermediate->getStage() == EShLangCompute &&
5262 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005263 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5264 noImplicitLod = true;
5265 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005266
5267 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005268 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005269 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005270 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005271 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005272
5273 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005274 if (cracked.grad) {
5275 params.gradX = arguments[2 + extraArgs];
5276 params.gradY = arguments[3 + extraArgs];
5277 extraArgs += 2;
5278 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005279
5280 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005281 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005282 params.offset = arguments[2 + extraArgs];
5283 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005284 } else if (cracked.offsets) {
5285 params.offsets = arguments[2 + extraArgs];
5286 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005287 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005288
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005289#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005290 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005291 if (cracked.lodClamp) {
5292 params.lodClamp = arguments[2 + extraArgs];
5293 ++extraArgs;
5294 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005295 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005296 if (sparse) {
5297 params.texelOut = arguments[2 + extraArgs];
5298 ++extraArgs;
5299 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005300 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005301 if (cracked.gather && ! sampler.shadow) {
5302 // default component is 0, if missing, otherwise an argument
5303 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005304 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005305 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005306 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005307 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005308 }
Chao Chen3a137962018-09-19 11:41:27 -07005309 spv::Id resultStruct = spv::NoResult;
5310 if (imageFootprint) {
5311 //Following three extra arguments
5312 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5313 params.granularity = arguments[2 + extraArgs];
5314 params.coarse = arguments[3 + extraArgs];
5315 resultStruct = arguments[4 + extraArgs];
5316 extraArgs += 3;
5317 }
5318#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005319 // bias
5320 if (bias) {
5321 params.bias = arguments[2 + extraArgs];
5322 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005323 }
John Kessenichfc51d282015-08-19 13:34:18 -06005324
John Kessenicha28f7a72019-08-06 07:00:58 -06005325#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005326 if (imageFootprint) {
5327 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5328 builder.addCapability(spv::CapabilityImageFootprintNV);
5329
5330
5331 //resultStructType(OpenGL type) contains 5 elements:
5332 //struct gl_TextureFootprint2DNV {
5333 // uvec2 anchor;
5334 // uvec2 offset;
5335 // uvec2 mask;
5336 // uint lod;
5337 // uint granularity;
5338 //};
5339 //or
5340 //struct gl_TextureFootprint3DNV {
5341 // uvec3 anchor;
5342 // uvec3 offset;
5343 // uvec2 mask;
5344 // uint lod;
5345 // uint granularity;
5346 //};
5347 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5348 assert(builder.isStructType(resultStructType));
5349
5350 //resType (SPIR-V type) contains 6 elements:
5351 //Member 0 must be a Boolean type scalar(LOD),
5352 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5353 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5354 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5355 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5356 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5357 std::vector<spv::Id> members;
5358 members.push_back(resultType());
5359 for (int i = 0; i < 5; i++) {
5360 members.push_back(builder.getContainedTypeId(resultStructType, i));
5361 }
5362 spv::Id resType = builder.makeStructType(members, "ResType");
5363
5364 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005365 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5366 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005367
5368 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5369 for (int i = 0; i < 5; i++) {
5370 builder.clearAccessChain();
5371 builder.setAccessChainLValue(resultStruct);
5372
5373 //Accessing to a struct we created, no coherent flag is set
5374 spv::Builder::AccessChain::CoherentFlags flags;
5375 flags.clear();
5376
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005377 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005378 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005379 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005380 }
5381 return builder.createCompositeExtract(res, resultType(), 0);
5382 }
5383#endif
5384
John Kessenich65336482016-06-16 14:06:26 -06005385 // projective component (might not to move)
5386 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5387 // are divided by the last component of P."
5388 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5389 // unused components will appear after all used components."
5390 if (cracked.proj) {
5391 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5392 int projTargetComp;
5393 switch (sampler.dim) {
5394 case glslang::Esd1D: projTargetComp = 1; break;
5395 case glslang::Esd2D: projTargetComp = 2; break;
5396 case glslang::EsdRect: projTargetComp = 2; break;
5397 default: projTargetComp = projSourceComp; break;
5398 }
5399 // copy the projective coordinate if we have to
5400 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005401 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005402 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005403 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005404 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005405 }
5406 }
5407
John Kessenichf8d1d742019-10-21 06:55:11 -06005408#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005409 // nonprivate
5410 if (imageType.getQualifier().nonprivate) {
5411 params.nonprivate = true;
5412 }
5413
5414 // volatile
5415 if (imageType.getQualifier().volatil) {
5416 params.volatil = true;
5417 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005418#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005419
St0fFa1184dd2018-04-09 21:08:14 +02005420 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005421 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5422 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005423 );
LoopDawg4425f242018-02-18 11:40:01 -07005424
5425 if (components != node->getType().getVectorSize())
5426 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5427
5428 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005429}
5430
5431spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5432{
5433 // Grab the function's pointer from the previously created function
5434 spv::Function* function = functionMap[node->getName().c_str()];
5435 if (! function)
5436 return 0;
5437
5438 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5439 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5440
5441 // See comments in makeFunctions() for details about the semantics for parameter passing.
5442 //
5443 // These imply we need a four step process:
5444 // 1. Evaluate the arguments
5445 // 2. Allocate and make copies of in, out, and inout arguments
5446 // 3. Make the call
5447 // 4. Copy back the results
5448
John Kessenichd3ed90b2018-05-04 11:43:03 -06005449 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005450 std::vector<spv::Builder::AccessChain> lValues;
5451 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005452 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005453 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005454 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005455 // build l-value
5456 builder.clearAccessChain();
5457 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005458 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005459 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005460 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005461 // save l-value
5462 lValues.push_back(builder.getAccessChain());
5463 } else {
5464 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005465 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005466 }
5467 }
5468
5469 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5470 // copy the original into that space.
5471 //
5472 // Also, build up the list of actual arguments to pass in for the call
5473 int lValueCount = 0;
5474 int rValueCount = 0;
5475 std::vector<spv::Id> spvArgs;
5476 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5477 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005478 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005479 builder.setAccessChain(lValues[lValueCount]);
5480 arg = builder.accessChainGetLValue();
5481 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005482 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005483 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005484 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005485 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005486 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5487 // need to copy the input into output space
5488 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005489 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005490 builder.clearAccessChain();
5491 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005492 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005493 }
5494 ++lValueCount;
5495 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005496 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005497 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005498 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005499 {
John Kessenich435dd802020-06-30 01:27:08 -06005500 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005501 builder.clearAccessChain();
5502 builder.setAccessChainLValue(argCopy);
5503 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005504 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005505 } else
5506 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005507 ++rValueCount;
5508 }
5509 spvArgs.push_back(arg);
5510 }
5511
5512 // 3. Make the call.
5513 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005514 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
greg-lunarg639f5462020-11-12 11:10:07 -07005515 builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005516
5517 // 4. Copy back out an "out" arguments.
5518 lValueCount = 0;
5519 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005520 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005521 ++lValueCount;
5522 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005523 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005524 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
greg-lunarg639f5462020-11-12 11:10:07 -07005525 builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005526 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005527 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005528 }
5529 ++lValueCount;
5530 }
5531 }
5532
5533 return result;
5534}
5535
5536// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005537spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005538 spv::Id typeId, spv::Id left, spv::Id right,
5539 glslang::TBasicType typeProxy, bool reduceComparison)
5540{
John Kessenich66011cb2018-03-06 16:12:04 -07005541 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5542 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005543 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005544
5545 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005546 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005547 bool comparison = false;
5548
5549 switch (op) {
5550 case glslang::EOpAdd:
5551 case glslang::EOpAddAssign:
5552 if (isFloat)
5553 binOp = spv::OpFAdd;
5554 else
5555 binOp = spv::OpIAdd;
5556 break;
5557 case glslang::EOpSub:
5558 case glslang::EOpSubAssign:
5559 if (isFloat)
5560 binOp = spv::OpFSub;
5561 else
5562 binOp = spv::OpISub;
5563 break;
5564 case glslang::EOpMul:
5565 case glslang::EOpMulAssign:
5566 if (isFloat)
5567 binOp = spv::OpFMul;
5568 else
5569 binOp = spv::OpIMul;
5570 break;
5571 case glslang::EOpVectorTimesScalar:
5572 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005573 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005574 if (builder.isVector(right))
5575 std::swap(left, right);
5576 assert(builder.isScalar(right));
5577 needMatchingVectors = false;
5578 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005579 } else if (isFloat)
5580 binOp = spv::OpFMul;
5581 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005582 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005583 break;
5584 case glslang::EOpVectorTimesMatrix:
5585 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005586 binOp = spv::OpVectorTimesMatrix;
5587 break;
5588 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005589 binOp = spv::OpMatrixTimesVector;
5590 break;
5591 case glslang::EOpMatrixTimesScalar:
5592 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005593 binOp = spv::OpMatrixTimesScalar;
5594 break;
5595 case glslang::EOpMatrixTimesMatrix:
5596 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005597 binOp = spv::OpMatrixTimesMatrix;
5598 break;
5599 case glslang::EOpOuterProduct:
5600 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005601 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005602 break;
5603
5604 case glslang::EOpDiv:
5605 case glslang::EOpDivAssign:
5606 if (isFloat)
5607 binOp = spv::OpFDiv;
5608 else if (isUnsigned)
5609 binOp = spv::OpUDiv;
5610 else
5611 binOp = spv::OpSDiv;
5612 break;
5613 case glslang::EOpMod:
5614 case glslang::EOpModAssign:
5615 if (isFloat)
5616 binOp = spv::OpFMod;
5617 else if (isUnsigned)
5618 binOp = spv::OpUMod;
5619 else
5620 binOp = spv::OpSMod;
5621 break;
5622 case glslang::EOpRightShift:
5623 case glslang::EOpRightShiftAssign:
5624 if (isUnsigned)
5625 binOp = spv::OpShiftRightLogical;
5626 else
5627 binOp = spv::OpShiftRightArithmetic;
5628 break;
5629 case glslang::EOpLeftShift:
5630 case glslang::EOpLeftShiftAssign:
5631 binOp = spv::OpShiftLeftLogical;
5632 break;
5633 case glslang::EOpAnd:
5634 case glslang::EOpAndAssign:
5635 binOp = spv::OpBitwiseAnd;
5636 break;
5637 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005638 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005639 binOp = spv::OpLogicalAnd;
5640 break;
5641 case glslang::EOpInclusiveOr:
5642 case glslang::EOpInclusiveOrAssign:
5643 binOp = spv::OpBitwiseOr;
5644 break;
5645 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005646 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005647 binOp = spv::OpLogicalOr;
5648 break;
5649 case glslang::EOpExclusiveOr:
5650 case glslang::EOpExclusiveOrAssign:
5651 binOp = spv::OpBitwiseXor;
5652 break;
5653 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005654 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005655 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005656 break;
5657
Ian Romanickb3bd4022019-01-21 08:57:25 -08005658 case glslang::EOpAbsDifference:
5659 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5660 break;
5661
5662 case glslang::EOpAddSaturate:
5663 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5664 break;
5665
5666 case glslang::EOpSubSaturate:
5667 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5668 break;
5669
5670 case glslang::EOpAverage:
5671 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5672 break;
5673
5674 case glslang::EOpAverageRounded:
5675 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5676 break;
5677
5678 case glslang::EOpMul32x16:
5679 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5680 break;
5681
John Kessenich140f3df2015-06-26 16:58:36 -06005682 case glslang::EOpLessThan:
5683 case glslang::EOpGreaterThan:
5684 case glslang::EOpLessThanEqual:
5685 case glslang::EOpGreaterThanEqual:
5686 case glslang::EOpEqual:
5687 case glslang::EOpNotEqual:
5688 case glslang::EOpVectorEqual:
5689 case glslang::EOpVectorNotEqual:
5690 comparison = true;
5691 break;
5692 default:
5693 break;
5694 }
5695
John Kessenich7c1aa102015-10-15 13:29:11 -06005696 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005697 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005698 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005699 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5700 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005701 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005702
5703 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005704 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005705 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005706
qining25262b32016-05-06 17:25:16 -04005707 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005708 decorations.addNoContraction(builder, result);
5709 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005710 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005711 }
5712
5713 if (! comparison)
5714 return 0;
5715
John Kessenich7c1aa102015-10-15 13:29:11 -06005716 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005717
John Kessenich4583b612016-08-07 19:14:22 -06005718 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005719 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5720 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005721 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005722 return result;
5723 }
John Kessenich140f3df2015-06-26 16:58:36 -06005724
5725 switch (op) {
5726 case glslang::EOpLessThan:
5727 if (isFloat)
5728 binOp = spv::OpFOrdLessThan;
5729 else if (isUnsigned)
5730 binOp = spv::OpULessThan;
5731 else
5732 binOp = spv::OpSLessThan;
5733 break;
5734 case glslang::EOpGreaterThan:
5735 if (isFloat)
5736 binOp = spv::OpFOrdGreaterThan;
5737 else if (isUnsigned)
5738 binOp = spv::OpUGreaterThan;
5739 else
5740 binOp = spv::OpSGreaterThan;
5741 break;
5742 case glslang::EOpLessThanEqual:
5743 if (isFloat)
5744 binOp = spv::OpFOrdLessThanEqual;
5745 else if (isUnsigned)
5746 binOp = spv::OpULessThanEqual;
5747 else
5748 binOp = spv::OpSLessThanEqual;
5749 break;
5750 case glslang::EOpGreaterThanEqual:
5751 if (isFloat)
5752 binOp = spv::OpFOrdGreaterThanEqual;
5753 else if (isUnsigned)
5754 binOp = spv::OpUGreaterThanEqual;
5755 else
5756 binOp = spv::OpSGreaterThanEqual;
5757 break;
5758 case glslang::EOpEqual:
5759 case glslang::EOpVectorEqual:
5760 if (isFloat)
5761 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005762 else if (isBool)
5763 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005764 else
5765 binOp = spv::OpIEqual;
5766 break;
5767 case glslang::EOpNotEqual:
5768 case glslang::EOpVectorNotEqual:
5769 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005770 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005771 else if (isBool)
5772 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005773 else
5774 binOp = spv::OpINotEqual;
5775 break;
5776 default:
5777 break;
5778 }
5779
qining25262b32016-05-06 17:25:16 -04005780 if (binOp != spv::OpNop) {
5781 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005782 decorations.addNoContraction(builder, result);
5783 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005784 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005785 }
John Kessenich140f3df2015-06-26 16:58:36 -06005786
5787 return 0;
5788}
5789
John Kessenich04bb8a02015-12-12 12:28:14 -07005790//
5791// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5792// These can be any of:
5793//
5794// matrix * scalar
5795// scalar * matrix
5796// matrix * matrix linear algebraic
5797// matrix * vector
5798// vector * matrix
5799// matrix * matrix componentwise
5800// matrix op matrix op in {+, -, /}
5801// matrix op scalar op in {+, -, /}
5802// scalar op matrix op in {+, -, /}
5803//
John Kessenichead86222018-03-28 18:01:20 -06005804spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5805 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005806{
5807 bool firstClass = true;
5808
5809 // First, handle first-class matrix operations (* and matrix/scalar)
5810 switch (op) {
5811 case spv::OpFDiv:
5812 if (builder.isMatrix(left) && builder.isScalar(right)) {
5813 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005814 spv::Id resultType = builder.getTypeId(right);
5815 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005816 op = spv::OpMatrixTimesScalar;
5817 } else
5818 firstClass = false;
5819 break;
5820 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005821 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005822 std::swap(left, right);
5823 assert(builder.isScalar(right));
5824 break;
5825 case spv::OpVectorTimesMatrix:
5826 assert(builder.isVector(left));
5827 assert(builder.isMatrix(right));
5828 break;
5829 case spv::OpMatrixTimesVector:
5830 assert(builder.isMatrix(left));
5831 assert(builder.isVector(right));
5832 break;
5833 case spv::OpMatrixTimesMatrix:
5834 assert(builder.isMatrix(left));
5835 assert(builder.isMatrix(right));
5836 break;
5837 default:
5838 firstClass = false;
5839 break;
5840 }
5841
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005842 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5843 firstClass = true;
5844
qining25262b32016-05-06 17:25:16 -04005845 if (firstClass) {
5846 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005847 decorations.addNoContraction(builder, result);
5848 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005849 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005850 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005851
LoopDawg592860c2016-06-09 08:57:35 -06005852 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005853 // The result type of all of them is the same type as the (a) matrix operand.
5854 // The algorithm is to:
5855 // - break the matrix(es) into vectors
5856 // - smear any scalar to a vector
5857 // - do vector operations
5858 // - make a matrix out the vector results
5859 switch (op) {
5860 case spv::OpFAdd:
5861 case spv::OpFSub:
5862 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005863 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005864 case spv::OpFMul:
5865 {
5866 // one time set up...
5867 bool leftMat = builder.isMatrix(left);
5868 bool rightMat = builder.isMatrix(right);
5869 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5870 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5871 spv::Id scalarType = builder.getScalarTypeId(typeId);
5872 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5873 std::vector<spv::Id> results;
5874 spv::Id smearVec = spv::NoResult;
5875 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005876 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005877 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005878 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005879
5880 // do each vector op
5881 for (unsigned int c = 0; c < numCols; ++c) {
5882 std::vector<unsigned int> indexes;
5883 indexes.push_back(c);
5884 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5885 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005886 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005887 decorations.addNoContraction(builder, result);
5888 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005889 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005890 }
5891
5892 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005893 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005894 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005895 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005896 }
5897 default:
5898 assert(0);
5899 return spv::NoResult;
5900 }
5901}
5902
John Kessenichead86222018-03-28 18:01:20 -06005903spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005904 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005905{
5906 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005907 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005908 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005909 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5910 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005911
5912 switch (op) {
5913 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005914 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005915 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005916 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005917 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005918 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005919 unaryOp = spv::OpSNegate;
5920 break;
5921
5922 case glslang::EOpLogicalNot:
5923 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005924 unaryOp = spv::OpLogicalNot;
5925 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005926 case glslang::EOpBitwiseNot:
5927 unaryOp = spv::OpNot;
5928 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005929
John Kessenich140f3df2015-06-26 16:58:36 -06005930 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005931 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005932 break;
5933 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005934 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005935 break;
5936 case glslang::EOpTranspose:
5937 unaryOp = spv::OpTranspose;
5938 break;
5939
5940 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005941 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005942 break;
5943 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005944 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005945 break;
5946 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005947 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005948 break;
5949 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005950 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005951 break;
5952 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005953 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005954 break;
5955 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005956 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005957 break;
5958 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005959 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005960 break;
5961 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005962 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005963 break;
5964
5965 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005966 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005967 break;
5968 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005969 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005970 break;
5971 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005972 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005973 break;
5974 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005975 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005976 break;
5977 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005978 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005979 break;
5980 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005981 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005982 break;
5983
5984 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005985 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005986 break;
5987 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005988 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005989 break;
5990
5991 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005992 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005993 break;
5994 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005995 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005996 break;
5997 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005998 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005999 break;
6000 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006001 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06006002 break;
6003 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006004 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006005 break;
6006 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006007 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006008 break;
6009
6010 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06006011 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06006012 break;
6013 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06006014 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
6016 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06006017 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06006018 break;
6019 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06006020 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06006021 break;
6022 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06006023 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06006024 break;
6025 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006026 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06006027 break;
6028
6029 case glslang::EOpIsNan:
6030 unaryOp = spv::OpIsNan;
6031 break;
6032 case glslang::EOpIsInf:
6033 unaryOp = spv::OpIsInf;
6034 break;
LoopDawg592860c2016-06-09 08:57:35 -06006035 case glslang::EOpIsFinite:
6036 unaryOp = spv::OpIsFinite;
6037 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006038
Rex Xucbc426e2015-12-15 16:03:10 +08006039 case glslang::EOpFloatBitsToInt:
6040 case glslang::EOpFloatBitsToUint:
6041 case glslang::EOpIntBitsToFloat:
6042 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08006043 case glslang::EOpDoubleBitsToInt64:
6044 case glslang::EOpDoubleBitsToUint64:
6045 case glslang::EOpInt64BitsToDouble:
6046 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08006047 case glslang::EOpFloat16BitsToInt16:
6048 case glslang::EOpFloat16BitsToUint16:
6049 case glslang::EOpInt16BitsToFloat16:
6050 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08006051 unaryOp = spv::OpBitcast;
6052 break;
6053
John Kessenich140f3df2015-06-26 16:58:36 -06006054 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006055 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006056 break;
6057 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006058 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006059 break;
6060 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006061 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006064 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006065 break;
6066 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006067 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006068 break;
6069 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006070 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006071 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006072#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06006073 case glslang::EOpPackSnorm4x8:
6074 libCall = spv::GLSLstd450PackSnorm4x8;
6075 break;
6076 case glslang::EOpUnpackSnorm4x8:
6077 libCall = spv::GLSLstd450UnpackSnorm4x8;
6078 break;
6079 case glslang::EOpPackUnorm4x8:
6080 libCall = spv::GLSLstd450PackUnorm4x8;
6081 break;
6082 case glslang::EOpUnpackUnorm4x8:
6083 libCall = spv::GLSLstd450UnpackUnorm4x8;
6084 break;
6085 case glslang::EOpPackDouble2x32:
6086 libCall = spv::GLSLstd450PackDouble2x32;
6087 break;
6088 case glslang::EOpUnpackDouble2x32:
6089 libCall = spv::GLSLstd450UnpackDouble2x32;
6090 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006091#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006092
Rex Xu8ff43de2016-04-22 16:51:45 +08006093 case glslang::EOpPackInt2x32:
6094 case glslang::EOpUnpackInt2x32:
6095 case glslang::EOpPackUint2x32:
6096 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07006097 case glslang::EOpPack16:
6098 case glslang::EOpPack32:
6099 case glslang::EOpPack64:
6100 case glslang::EOpUnpack32:
6101 case glslang::EOpUnpack16:
6102 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006103 case glslang::EOpPackInt2x16:
6104 case glslang::EOpUnpackInt2x16:
6105 case glslang::EOpPackUint2x16:
6106 case glslang::EOpUnpackUint2x16:
6107 case glslang::EOpPackInt4x16:
6108 case glslang::EOpUnpackInt4x16:
6109 case glslang::EOpPackUint4x16:
6110 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006111 case glslang::EOpPackFloat2x16:
6112 case glslang::EOpUnpackFloat2x16:
6113 unaryOp = spv::OpBitcast;
6114 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006115
John Kessenich140f3df2015-06-26 16:58:36 -06006116 case glslang::EOpDPdx:
6117 unaryOp = spv::OpDPdx;
6118 break;
6119 case glslang::EOpDPdy:
6120 unaryOp = spv::OpDPdy;
6121 break;
6122 case glslang::EOpFwidth:
6123 unaryOp = spv::OpFwidth;
6124 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006125
John Kessenich140f3df2015-06-26 16:58:36 -06006126 case glslang::EOpAny:
6127 unaryOp = spv::OpAny;
6128 break;
6129 case glslang::EOpAll:
6130 unaryOp = spv::OpAll;
6131 break;
6132
6133 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006134 if (isFloat)
6135 libCall = spv::GLSLstd450FAbs;
6136 else
6137 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006138 break;
6139 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006140 if (isFloat)
6141 libCall = spv::GLSLstd450FSign;
6142 else
6143 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006144 break;
6145
John Kessenicha28f7a72019-08-06 07:00:58 -06006146#ifndef GLSLANG_WEB
6147 case glslang::EOpDPdxFine:
6148 unaryOp = spv::OpDPdxFine;
6149 break;
6150 case glslang::EOpDPdyFine:
6151 unaryOp = spv::OpDPdyFine;
6152 break;
6153 case glslang::EOpFwidthFine:
6154 unaryOp = spv::OpFwidthFine;
6155 break;
6156 case glslang::EOpDPdxCoarse:
6157 unaryOp = spv::OpDPdxCoarse;
6158 break;
6159 case glslang::EOpDPdyCoarse:
6160 unaryOp = spv::OpDPdyCoarse;
6161 break;
6162 case glslang::EOpFwidthCoarse:
6163 unaryOp = spv::OpFwidthCoarse;
6164 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006165 case glslang::EOpRayQueryProceed:
6166 unaryOp = spv::OpRayQueryProceedKHR;
6167 break;
6168 case glslang::EOpRayQueryGetRayTMin:
6169 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6170 break;
6171 case glslang::EOpRayQueryGetRayFlags:
6172 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6173 break;
6174 case glslang::EOpRayQueryGetWorldRayOrigin:
6175 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6176 break;
6177 case glslang::EOpRayQueryGetWorldRayDirection:
6178 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6179 break;
6180 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6181 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6182 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006183 case glslang::EOpInterpolateAtCentroid:
6184 if (typeProxy == glslang::EbtFloat16)
6185 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6186 libCall = spv::GLSLstd450InterpolateAtCentroid;
6187 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006188 case glslang::EOpAtomicCounterIncrement:
6189 case glslang::EOpAtomicCounterDecrement:
6190 case glslang::EOpAtomicCounter:
6191 {
6192 // Handle all of the atomics in one place, in createAtomicOperation()
6193 std::vector<spv::Id> operands;
6194 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006195 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006196 }
6197
John Kessenichfc51d282015-08-19 13:34:18 -06006198 case glslang::EOpBitFieldReverse:
6199 unaryOp = spv::OpBitReverse;
6200 break;
6201 case glslang::EOpBitCount:
6202 unaryOp = spv::OpBitCount;
6203 break;
6204 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006205 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006206 break;
6207 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006208 if (isUnsigned)
6209 libCall = spv::GLSLstd450FindUMsb;
6210 else
6211 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006212 break;
6213
Ian Romanickb3bd4022019-01-21 08:57:25 -08006214 case glslang::EOpCountLeadingZeros:
6215 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6216 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6217 unaryOp = spv::OpUCountLeadingZerosINTEL;
6218 break;
6219
6220 case glslang::EOpCountTrailingZeros:
6221 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6222 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6223 unaryOp = spv::OpUCountTrailingZerosINTEL;
6224 break;
6225
Rex Xu574ab042016-04-14 16:53:07 +08006226 case glslang::EOpBallot:
6227 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006228 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006229 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006230 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006231 case glslang::EOpMinInvocations:
6232 case glslang::EOpMaxInvocations:
6233 case glslang::EOpAddInvocations:
6234 case glslang::EOpMinInvocationsNonUniform:
6235 case glslang::EOpMaxInvocationsNonUniform:
6236 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006237 case glslang::EOpMinInvocationsInclusiveScan:
6238 case glslang::EOpMaxInvocationsInclusiveScan:
6239 case glslang::EOpAddInvocationsInclusiveScan:
6240 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6241 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6242 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6243 case glslang::EOpMinInvocationsExclusiveScan:
6244 case glslang::EOpMaxInvocationsExclusiveScan:
6245 case glslang::EOpAddInvocationsExclusiveScan:
6246 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6247 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6248 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006249 {
6250 std::vector<spv::Id> operands;
6251 operands.push_back(operand);
6252 return createInvocationsOperation(op, typeId, operands, typeProxy);
6253 }
John Kessenich66011cb2018-03-06 16:12:04 -07006254 case glslang::EOpSubgroupAll:
6255 case glslang::EOpSubgroupAny:
6256 case glslang::EOpSubgroupAllEqual:
6257 case glslang::EOpSubgroupBroadcastFirst:
6258 case glslang::EOpSubgroupBallot:
6259 case glslang::EOpSubgroupInverseBallot:
6260 case glslang::EOpSubgroupBallotBitCount:
6261 case glslang::EOpSubgroupBallotInclusiveBitCount:
6262 case glslang::EOpSubgroupBallotExclusiveBitCount:
6263 case glslang::EOpSubgroupBallotFindLSB:
6264 case glslang::EOpSubgroupBallotFindMSB:
6265 case glslang::EOpSubgroupAdd:
6266 case glslang::EOpSubgroupMul:
6267 case glslang::EOpSubgroupMin:
6268 case glslang::EOpSubgroupMax:
6269 case glslang::EOpSubgroupAnd:
6270 case glslang::EOpSubgroupOr:
6271 case glslang::EOpSubgroupXor:
6272 case glslang::EOpSubgroupInclusiveAdd:
6273 case glslang::EOpSubgroupInclusiveMul:
6274 case glslang::EOpSubgroupInclusiveMin:
6275 case glslang::EOpSubgroupInclusiveMax:
6276 case glslang::EOpSubgroupInclusiveAnd:
6277 case glslang::EOpSubgroupInclusiveOr:
6278 case glslang::EOpSubgroupInclusiveXor:
6279 case glslang::EOpSubgroupExclusiveAdd:
6280 case glslang::EOpSubgroupExclusiveMul:
6281 case glslang::EOpSubgroupExclusiveMin:
6282 case glslang::EOpSubgroupExclusiveMax:
6283 case glslang::EOpSubgroupExclusiveAnd:
6284 case glslang::EOpSubgroupExclusiveOr:
6285 case glslang::EOpSubgroupExclusiveXor:
6286 case glslang::EOpSubgroupQuadSwapHorizontal:
6287 case glslang::EOpSubgroupQuadSwapVertical:
6288 case glslang::EOpSubgroupQuadSwapDiagonal: {
6289 std::vector<spv::Id> operands;
6290 operands.push_back(operand);
6291 return createSubgroupOperation(op, typeId, operands, typeProxy);
6292 }
Rex Xu9d93a232016-05-05 12:30:44 +08006293 case glslang::EOpMbcnt:
6294 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6295 libCall = spv::MbcntAMD;
6296 break;
6297
6298 case glslang::EOpCubeFaceIndex:
6299 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6300 libCall = spv::CubeFaceIndexAMD;
6301 break;
6302
6303 case glslang::EOpCubeFaceCoord:
6304 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6305 libCall = spv::CubeFaceCoordAMD;
6306 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006307 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006308 unaryOp = spv::OpGroupNonUniformPartitionNV;
6309 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006310 case glslang::EOpConstructReference:
6311 unaryOp = spv::OpBitcast;
6312 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05006313
6314 case glslang::EOpConvUint64ToAccStruct:
6315 case glslang::EOpConvUvec2ToAccStruct:
6316 unaryOp = spv::OpConvertUToAccelerationStructureKHR;
6317 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006318#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006319
6320 case glslang::EOpCopyObject:
6321 unaryOp = spv::OpCopyObject;
6322 break;
6323
John Kessenich140f3df2015-06-26 16:58:36 -06006324 default:
6325 return 0;
6326 }
6327
6328 spv::Id id;
6329 if (libCall >= 0) {
6330 std::vector<spv::Id> args;
6331 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006332 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006333 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006334 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006335 }
John Kessenich140f3df2015-06-26 16:58:36 -06006336
John Kessenichb9197c82019-08-11 07:41:45 -06006337 decorations.addNoContraction(builder, id);
6338 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006339 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006340}
6341
John Kessenich7a53f762016-01-20 11:19:27 -07006342// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006343spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6344 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006345{
6346 // Handle unary operations vector by vector.
6347 // The result type is the same type as the original type.
6348 // The algorithm is to:
6349 // - break the matrix into vectors
6350 // - apply the operation to each vector
6351 // - make a matrix out the vector results
6352
6353 // get the types sorted out
6354 int numCols = builder.getNumColumns(operand);
6355 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006356 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6357 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006358 std::vector<spv::Id> results;
6359
6360 // do each vector op
6361 for (int c = 0; c < numCols; ++c) {
6362 std::vector<unsigned int> indexes;
6363 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006364 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6365 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006366 decorations.addNoContraction(builder, destVec);
6367 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006368 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006369 }
6370
6371 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006372 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006373 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006374 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006375}
6376
John Kessenichad7645f2018-06-04 19:11:25 -06006377// For converting integers where both the bitwidth and the signedness could
6378// change, but only do the width change here. The caller is still responsible
6379// for the signedness conversion.
6380spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006381{
John Kessenichad7645f2018-06-04 19:11:25 -06006382 // Get the result type width, based on the type to convert to.
6383 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006384 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006385 case glslang::EOpConvInt16ToUint8:
6386 case glslang::EOpConvIntToUint8:
6387 case glslang::EOpConvInt64ToUint8:
6388 case glslang::EOpConvUint16ToInt8:
6389 case glslang::EOpConvUintToInt8:
6390 case glslang::EOpConvUint64ToInt8:
6391 width = 8;
6392 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006394 case glslang::EOpConvIntToUint16:
6395 case glslang::EOpConvInt64ToUint16:
6396 case glslang::EOpConvUint8ToInt16:
6397 case glslang::EOpConvUintToInt16:
6398 case glslang::EOpConvUint64ToInt16:
6399 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006400 break;
6401 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006402 case glslang::EOpConvInt16ToUint:
6403 case glslang::EOpConvInt64ToUint:
6404 case glslang::EOpConvUint8ToInt:
6405 case glslang::EOpConvUint16ToInt:
6406 case glslang::EOpConvUint64ToInt:
6407 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006408 break;
6409 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006410 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006411 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006412 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006413 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006414 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006415 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006416 break;
6417
6418 default:
6419 assert(false && "Default missing");
6420 break;
6421 }
6422
John Kessenichad7645f2018-06-04 19:11:25 -06006423 // Get the conversion operation and result type,
6424 // based on the target width, but the source type.
6425 spv::Id type = spv::NoType;
6426 spv::Op convOp = spv::OpNop;
6427 switch(op) {
6428 case glslang::EOpConvInt8ToUint16:
6429 case glslang::EOpConvInt8ToUint:
6430 case glslang::EOpConvInt8ToUint64:
6431 case glslang::EOpConvInt16ToUint8:
6432 case glslang::EOpConvInt16ToUint:
6433 case glslang::EOpConvInt16ToUint64:
6434 case glslang::EOpConvIntToUint8:
6435 case glslang::EOpConvIntToUint16:
6436 case glslang::EOpConvIntToUint64:
6437 case glslang::EOpConvInt64ToUint8:
6438 case glslang::EOpConvInt64ToUint16:
6439 case glslang::EOpConvInt64ToUint:
6440 convOp = spv::OpSConvert;
6441 type = builder.makeIntType(width);
6442 break;
6443 default:
6444 convOp = spv::OpUConvert;
6445 type = builder.makeUintType(width);
6446 break;
6447 }
6448
John Kessenich66011cb2018-03-06 16:12:04 -07006449 if (vectorSize > 0)
6450 type = builder.makeVectorType(type, vectorSize);
6451
John Kessenichad7645f2018-06-04 19:11:25 -06006452 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006453}
6454
John Kessenichead86222018-03-28 18:01:20 -06006455spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6456 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006457{
6458 spv::Op convOp = spv::OpNop;
6459 spv::Id zero = 0;
6460 spv::Id one = 0;
6461
6462 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6463
6464 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006465 case glslang::EOpConvIntToBool:
6466 case glslang::EOpConvUintToBool:
6467 zero = builder.makeUintConstant(0);
6468 zero = makeSmearedConstant(zero, vectorSize);
6469 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006470 case glslang::EOpConvFloatToBool:
6471 zero = builder.makeFloatConstant(0.0F);
6472 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006473 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006474 case glslang::EOpConvBoolToFloat:
6475 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006476 zero = builder.makeFloatConstant(0.0F);
6477 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006478 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006479
John Kessenich140f3df2015-06-26 16:58:36 -06006480 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006481 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006482#ifndef GLSLANG_WEB
6483 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006484 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006485 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006486 } else
6487#endif
6488 {
6489 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006490 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006491 }
Rex Xucabbb782017-03-24 13:41:14 +08006492
John Kessenich140f3df2015-06-26 16:58:36 -06006493 convOp = spv::OpSelect;
6494 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006495
John Kessenich140f3df2015-06-26 16:58:36 -06006496 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006497 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006498#ifndef GLSLANG_WEB
6499 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006500 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006501 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006502 } else
6503#endif
6504 {
6505 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006506 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006507 }
Rex Xucabbb782017-03-24 13:41:14 +08006508
John Kessenich140f3df2015-06-26 16:58:36 -06006509 convOp = spv::OpSelect;
6510 break;
6511
John Kessenich66011cb2018-03-06 16:12:04 -07006512 case glslang::EOpConvInt8ToFloat16:
6513 case glslang::EOpConvInt8ToFloat:
6514 case glslang::EOpConvInt8ToDouble:
6515 case glslang::EOpConvInt16ToFloat16:
6516 case glslang::EOpConvInt16ToFloat:
6517 case glslang::EOpConvInt16ToDouble:
6518 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006519 case glslang::EOpConvIntToFloat:
6520 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006521 case glslang::EOpConvInt64ToFloat:
6522 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006523 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006524 convOp = spv::OpConvertSToF;
6525 break;
6526
John Kessenich66011cb2018-03-06 16:12:04 -07006527 case glslang::EOpConvUint8ToFloat16:
6528 case glslang::EOpConvUint8ToFloat:
6529 case glslang::EOpConvUint8ToDouble:
6530 case glslang::EOpConvUint16ToFloat16:
6531 case glslang::EOpConvUint16ToFloat:
6532 case glslang::EOpConvUint16ToDouble:
6533 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006534 case glslang::EOpConvUintToFloat:
6535 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006536 case glslang::EOpConvUint64ToFloat:
6537 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006538 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006539 convOp = spv::OpConvertUToF;
6540 break;
6541
John Kessenich66011cb2018-03-06 16:12:04 -07006542 case glslang::EOpConvFloat16ToInt8:
6543 case glslang::EOpConvFloatToInt8:
6544 case glslang::EOpConvDoubleToInt8:
6545 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006546 case glslang::EOpConvFloatToInt16:
6547 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006548 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006549 case glslang::EOpConvFloatToInt:
6550 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006551 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006552 case glslang::EOpConvFloatToInt64:
6553 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006554 convOp = spv::OpConvertFToS;
6555 break;
6556
John Kessenich66011cb2018-03-06 16:12:04 -07006557 case glslang::EOpConvUint8ToInt8:
6558 case glslang::EOpConvInt8ToUint8:
6559 case glslang::EOpConvUint16ToInt16:
6560 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006561 case glslang::EOpConvUintToInt:
6562 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006563 case glslang::EOpConvUint64ToInt64:
6564 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006565 if (builder.isInSpecConstCodeGenMode()) {
6566 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006567#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006568 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6569 zero = builder.makeUint8Constant(0);
6570 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006571 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006572 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6573 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006574 } else
6575#endif
6576 {
Rex Xucabbb782017-03-24 13:41:14 +08006577 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006578 }
qining189b2032016-04-12 23:16:20 -04006579 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006580 // Use OpIAdd, instead of OpBitcast to do the conversion when
6581 // generating for OpSpecConstantOp instruction.
6582 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6583 }
6584 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006585 convOp = spv::OpBitcast;
6586 break;
6587
John Kessenich66011cb2018-03-06 16:12:04 -07006588 case glslang::EOpConvFloat16ToUint8:
6589 case glslang::EOpConvFloatToUint8:
6590 case glslang::EOpConvDoubleToUint8:
6591 case glslang::EOpConvFloat16ToUint16:
6592 case glslang::EOpConvFloatToUint16:
6593 case glslang::EOpConvDoubleToUint16:
6594 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006595 case glslang::EOpConvFloatToUint:
6596 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006597 case glslang::EOpConvFloatToUint64:
6598 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006599 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006600 convOp = spv::OpConvertFToU;
6601 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006602
John Kessenich39697cd2019-08-08 10:35:51 -06006603#ifndef GLSLANG_WEB
6604 case glslang::EOpConvInt8ToBool:
6605 case glslang::EOpConvUint8ToBool:
6606 zero = builder.makeUint8Constant(0);
6607 zero = makeSmearedConstant(zero, vectorSize);
6608 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6609 case glslang::EOpConvInt16ToBool:
6610 case glslang::EOpConvUint16ToBool:
6611 zero = builder.makeUint16Constant(0);
6612 zero = makeSmearedConstant(zero, vectorSize);
6613 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6614 case glslang::EOpConvInt64ToBool:
6615 case glslang::EOpConvUint64ToBool:
6616 zero = builder.makeUint64Constant(0);
6617 zero = makeSmearedConstant(zero, vectorSize);
6618 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6619 case glslang::EOpConvDoubleToBool:
6620 zero = builder.makeDoubleConstant(0.0);
6621 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006622 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006623 case glslang::EOpConvFloat16ToBool:
6624 zero = builder.makeFloat16Constant(0.0F);
6625 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006626 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006627 case glslang::EOpConvBoolToDouble:
6628 convOp = spv::OpSelect;
6629 zero = builder.makeDoubleConstant(0.0);
6630 one = builder.makeDoubleConstant(1.0);
6631 break;
6632 case glslang::EOpConvBoolToFloat16:
6633 convOp = spv::OpSelect;
6634 zero = builder.makeFloat16Constant(0.0F);
6635 one = builder.makeFloat16Constant(1.0F);
6636 break;
6637 case glslang::EOpConvBoolToInt8:
6638 zero = builder.makeInt8Constant(0);
6639 one = builder.makeInt8Constant(1);
6640 convOp = spv::OpSelect;
6641 break;
6642 case glslang::EOpConvBoolToUint8:
6643 zero = builder.makeUint8Constant(0);
6644 one = builder.makeUint8Constant(1);
6645 convOp = spv::OpSelect;
6646 break;
6647 case glslang::EOpConvBoolToInt16:
6648 zero = builder.makeInt16Constant(0);
6649 one = builder.makeInt16Constant(1);
6650 convOp = spv::OpSelect;
6651 break;
6652 case glslang::EOpConvBoolToUint16:
6653 zero = builder.makeUint16Constant(0);
6654 one = builder.makeUint16Constant(1);
6655 convOp = spv::OpSelect;
6656 break;
6657 case glslang::EOpConvDoubleToFloat:
6658 case glslang::EOpConvFloatToDouble:
6659 case glslang::EOpConvDoubleToFloat16:
6660 case glslang::EOpConvFloat16ToDouble:
6661 case glslang::EOpConvFloatToFloat16:
6662 case glslang::EOpConvFloat16ToFloat:
6663 convOp = spv::OpFConvert;
6664 if (builder.isMatrixType(destType))
6665 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6666 break;
6667
John Kessenich66011cb2018-03-06 16:12:04 -07006668 case glslang::EOpConvInt8ToInt16:
6669 case glslang::EOpConvInt8ToInt:
6670 case glslang::EOpConvInt8ToInt64:
6671 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006672 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006673 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006674 case glslang::EOpConvIntToInt8:
6675 case glslang::EOpConvIntToInt16:
6676 case glslang::EOpConvIntToInt64:
6677 case glslang::EOpConvInt64ToInt8:
6678 case glslang::EOpConvInt64ToInt16:
6679 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006680 convOp = spv::OpSConvert;
6681 break;
6682
John Kessenich66011cb2018-03-06 16:12:04 -07006683 case glslang::EOpConvUint8ToUint16:
6684 case glslang::EOpConvUint8ToUint:
6685 case glslang::EOpConvUint8ToUint64:
6686 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006687 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006688 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006689 case glslang::EOpConvUintToUint8:
6690 case glslang::EOpConvUintToUint16:
6691 case glslang::EOpConvUintToUint64:
6692 case glslang::EOpConvUint64ToUint8:
6693 case glslang::EOpConvUint64ToUint16:
6694 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006695 convOp = spv::OpUConvert;
6696 break;
6697
John Kessenich66011cb2018-03-06 16:12:04 -07006698 case glslang::EOpConvInt8ToUint16:
6699 case glslang::EOpConvInt8ToUint:
6700 case glslang::EOpConvInt8ToUint64:
6701 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006702 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006703 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006704 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006705 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006706 case glslang::EOpConvIntToUint64:
6707 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006708 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006709 case glslang::EOpConvInt64ToUint:
6710 case glslang::EOpConvUint8ToInt16:
6711 case glslang::EOpConvUint8ToInt:
6712 case glslang::EOpConvUint8ToInt64:
6713 case glslang::EOpConvUint16ToInt8:
6714 case glslang::EOpConvUint16ToInt:
6715 case glslang::EOpConvUint16ToInt64:
6716 case glslang::EOpConvUintToInt8:
6717 case glslang::EOpConvUintToInt16:
6718 case glslang::EOpConvUintToInt64:
6719 case glslang::EOpConvUint64ToInt8:
6720 case glslang::EOpConvUint64ToInt16:
6721 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006722 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006723 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006724
6725 if (builder.isInSpecConstCodeGenMode()) {
6726 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006727 switch(op) {
6728 case glslang::EOpConvInt16ToUint8:
6729 case glslang::EOpConvIntToUint8:
6730 case glslang::EOpConvInt64ToUint8:
6731 case glslang::EOpConvUint16ToInt8:
6732 case glslang::EOpConvUintToInt8:
6733 case glslang::EOpConvUint64ToInt8:
6734 zero = builder.makeUint8Constant(0);
6735 break;
6736 case glslang::EOpConvInt8ToUint16:
6737 case glslang::EOpConvIntToUint16:
6738 case glslang::EOpConvInt64ToUint16:
6739 case glslang::EOpConvUint8ToInt16:
6740 case glslang::EOpConvUintToInt16:
6741 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006742 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006743 break;
6744 case glslang::EOpConvInt8ToUint:
6745 case glslang::EOpConvInt16ToUint:
6746 case glslang::EOpConvInt64ToUint:
6747 case glslang::EOpConvUint8ToInt:
6748 case glslang::EOpConvUint16ToInt:
6749 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006750 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006751 break;
6752 case glslang::EOpConvInt8ToUint64:
6753 case glslang::EOpConvInt16ToUint64:
6754 case glslang::EOpConvIntToUint64:
6755 case glslang::EOpConvUint8ToInt64:
6756 case glslang::EOpConvUint16ToInt64:
6757 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006758 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006759 break;
6760 default:
6761 assert(false && "Default missing");
6762 break;
6763 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006764 zero = makeSmearedConstant(zero, vectorSize);
6765 // Use OpIAdd, instead of OpBitcast to do the conversion when
6766 // generating for OpSpecConstantOp instruction.
6767 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6768 }
6769 // For normal run-time conversion instruction, use OpBitcast.
6770 convOp = spv::OpBitcast;
6771 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006772 case glslang::EOpConvUint64ToPtr:
6773 convOp = spv::OpConvertUToPtr;
6774 break;
6775 case glslang::EOpConvPtrToUint64:
6776 convOp = spv::OpConvertPtrToU;
6777 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006778 case glslang::EOpConvPtrToUvec2:
6779 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006780 if (builder.isVector(operand))
6781 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6782 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006783 convOp = spv::OpBitcast;
6784 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006785#endif
6786
John Kessenich140f3df2015-06-26 16:58:36 -06006787 default:
6788 break;
6789 }
6790
6791 spv::Id result = 0;
6792 if (convOp == spv::OpNop)
6793 return result;
6794
6795 if (convOp == spv::OpSelect) {
6796 zero = makeSmearedConstant(zero, vectorSize);
6797 one = makeSmearedConstant(one, vectorSize);
6798 result = builder.createTriOp(convOp, destType, operand, one, zero);
6799 } else
6800 result = builder.createUnaryOp(convOp, destType, operand);
6801
John Kessenichead86222018-03-28 18:01:20 -06006802 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006803 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006804 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006805}
6806
6807spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6808{
6809 if (vectorSize == 0)
6810 return constant;
6811
6812 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6813 std::vector<spv::Id> components;
6814 for (int c = 0; c < vectorSize; ++c)
6815 components.push_back(constant);
6816 return builder.makeCompositeConstant(vectorTypeId, components);
6817}
6818
John Kessenich426394d2015-07-23 10:22:48 -06006819// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006820spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6821 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6822 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006823{
6824 spv::Op opCode = spv::OpNop;
6825
6826 switch (op) {
6827 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006828 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006829 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006830 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006831 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6832 opCode = spv::OpAtomicFAddEXT;
6833 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6834 if (typeProxy == glslang::EbtFloat)
6835 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6836 else
6837 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6838 }
John Kessenich426394d2015-07-23 10:22:48 -06006839 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006840 case glslang::EOpAtomicCounterSubtract:
6841 opCode = spv::OpAtomicISub;
6842 break;
John Kessenich426394d2015-07-23 10:22:48 -06006843 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006844 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006845 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006846 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6847 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006848 break;
6849 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006850 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006851 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006852 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6853 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006854 break;
6855 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006856 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006857 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006858 opCode = spv::OpAtomicAnd;
6859 break;
6860 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006861 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006862 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006863 opCode = spv::OpAtomicOr;
6864 break;
6865 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006866 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006867 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006868 opCode = spv::OpAtomicXor;
6869 break;
6870 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006871 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006872 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006873 opCode = spv::OpAtomicExchange;
6874 break;
6875 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006876 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006877 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006878 opCode = spv::OpAtomicCompareExchange;
6879 break;
6880 case glslang::EOpAtomicCounterIncrement:
6881 opCode = spv::OpAtomicIIncrement;
6882 break;
6883 case glslang::EOpAtomicCounterDecrement:
6884 opCode = spv::OpAtomicIDecrement;
6885 break;
6886 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006887 case glslang::EOpImageAtomicLoad:
6888 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006889 opCode = spv::OpAtomicLoad;
6890 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006891 case glslang::EOpAtomicStore:
6892 case glslang::EOpImageAtomicStore:
6893 opCode = spv::OpAtomicStore;
6894 break;
John Kessenich426394d2015-07-23 10:22:48 -06006895 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006896 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006897 break;
6898 }
6899
Rex Xue8fe8b02017-09-26 15:42:56 +08006900 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6901 builder.addCapability(spv::CapabilityInt64Atomics);
6902
John Kessenich426394d2015-07-23 10:22:48 -06006903 // Sort out the operands
6904 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006905 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006906 // - compare-exchange swaps the value and comparator
6907 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006908 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006909 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6910 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6911 spv::Id scopeId;
6912 if (glslangIntermediate->usingVulkanMemoryModel()) {
6913 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6914 } else {
6915 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6916 }
6917 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006918 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6919 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006920 spv::MemorySemanticsVolatileMask :
6921 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006922 spv::Id semanticsId2 = semanticsId;
6923
6924 pointerId = operands[0];
6925 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6926 // no additional operands
6927 } else if (opCode == spv::OpAtomicCompareExchange) {
6928 compareId = operands[1];
6929 valueId = operands[2];
6930 if (operands.size() > 3) {
6931 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006932 semanticsId = builder.makeUintConstant(
6933 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6934 semanticsId2 = builder.makeUintConstant(
6935 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006936 }
6937 } else if (opCode == spv::OpAtomicLoad) {
6938 if (operands.size() > 1) {
6939 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006940 semanticsId = builder.makeUintConstant(
6941 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006942 }
6943 } else {
6944 // atomic store or RMW
6945 valueId = operands[1];
6946 if (operands.size() > 2) {
6947 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006948 semanticsId = builder.makeUintConstant
6949 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006950 }
Rex Xu04db3f52015-09-16 11:44:02 +08006951 }
John Kessenich426394d2015-07-23 10:22:48 -06006952
Jeff Bolz36831c92018-09-05 10:11:41 -05006953 // Check for capabilities
6954 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006955 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6956 spv::MemorySemanticsMakeVisibleKHRMask |
6957 spv::MemorySemanticsOutputMemoryKHRMask |
6958 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006959 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6960 }
John Kessenich426394d2015-07-23 10:22:48 -06006961
Jeff Bolz36831c92018-09-05 10:11:41 -05006962 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6963 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6964 }
John Kessenich48d6e792017-10-06 21:21:48 -06006965
Jeff Bolz36831c92018-09-05 10:11:41 -05006966 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6967 spvAtomicOperands.push_back(pointerId);
6968 spvAtomicOperands.push_back(scopeId);
6969 spvAtomicOperands.push_back(semanticsId);
6970 if (opCode == spv::OpAtomicCompareExchange) {
6971 spvAtomicOperands.push_back(semanticsId2);
6972 spvAtomicOperands.push_back(valueId);
6973 spvAtomicOperands.push_back(compareId);
6974 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6975 spvAtomicOperands.push_back(valueId);
6976 }
John Kessenich48d6e792017-10-06 21:21:48 -06006977
Jeff Bolz36831c92018-09-05 10:11:41 -05006978 if (opCode == spv::OpAtomicStore) {
6979 builder.createNoResultOp(opCode, spvAtomicOperands);
6980 return 0;
6981 } else {
6982 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6983
6984 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6985 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6986 if (op == glslang::EOpAtomicCounterDecrement)
6987 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6988
6989 return resultId;
6990 }
John Kessenich426394d2015-07-23 10:22:48 -06006991}
6992
John Kessenich91cef522016-05-05 16:45:40 -06006993// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006994spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6995 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006996{
John Kessenich66011cb2018-03-06 16:12:04 -07006997 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6998 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006999
Rex Xu51596642016-09-21 18:56:12 +08007000 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06007001 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08007002 spv::GroupOperation groupOperation = spv::GroupOperationMax;
7003
chaocf200da82016-12-20 12:44:35 -08007004 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
7005 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08007006 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
7007 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007008 } else if (op == glslang::EOpAnyInvocation ||
7009 op == glslang::EOpAllInvocations ||
7010 op == glslang::EOpAllInvocationsEqual) {
7011 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
7012 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08007013 } else {
7014 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08007015 if (op == glslang::EOpMinInvocationsNonUniform ||
7016 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08007017 op == glslang::EOpAddInvocationsNonUniform ||
7018 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7019 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7020 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
7021 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
7022 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
7023 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08007024 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08007025
Rex Xu430ef402016-10-14 17:22:23 +08007026 switch (op) {
7027 case glslang::EOpMinInvocations:
7028 case glslang::EOpMaxInvocations:
7029 case glslang::EOpAddInvocations:
7030 case glslang::EOpMinInvocationsNonUniform:
7031 case glslang::EOpMaxInvocationsNonUniform:
7032 case glslang::EOpAddInvocationsNonUniform:
7033 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08007034 break;
7035 case glslang::EOpMinInvocationsInclusiveScan:
7036 case glslang::EOpMaxInvocationsInclusiveScan:
7037 case glslang::EOpAddInvocationsInclusiveScan:
7038 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7039 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7040 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7041 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007042 break;
7043 case glslang::EOpMinInvocationsExclusiveScan:
7044 case glslang::EOpMaxInvocationsExclusiveScan:
7045 case glslang::EOpAddInvocationsExclusiveScan:
7046 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7047 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7048 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7049 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007050 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07007051 default:
7052 break;
Rex Xu430ef402016-10-14 17:22:23 +08007053 }
John Kessenich149afc32018-08-14 13:31:43 -06007054 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7055 spvGroupOperands.push_back(scope);
7056 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007057 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007058 spvGroupOperands.push_back(groupOp);
7059 }
Rex Xu51596642016-09-21 18:56:12 +08007060 }
7061
John Kessenich149afc32018-08-14 13:31:43 -06007062 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
7063 spv::IdImmediate op = { true, *opIt };
7064 spvGroupOperands.push_back(op);
7065 }
John Kessenich91cef522016-05-05 16:45:40 -06007066
7067 switch (op) {
7068 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007069 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08007070 break;
John Kessenich91cef522016-05-05 16:45:40 -06007071 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007072 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08007073 break;
John Kessenich91cef522016-05-05 16:45:40 -06007074 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007075 opCode = spv::OpSubgroupAllEqualKHR;
7076 break;
Rex Xu51596642016-09-21 18:56:12 +08007077 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08007078 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08007079 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007080 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007081 break;
7082 case glslang::EOpReadFirstInvocation:
7083 opCode = spv::OpSubgroupFirstInvocationKHR;
7084 break;
7085 case glslang::EOpBallot:
7086 {
7087 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
7088 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
7089 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
7090 //
7091 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
7092 //
7093 spv::Id uintType = builder.makeUintType(32);
7094 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
7095 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
7096
7097 std::vector<spv::Id> components;
7098 components.push_back(builder.createCompositeExtract(result, uintType, 0));
7099 components.push_back(builder.createCompositeExtract(result, uintType, 1));
7100
7101 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
7102 return builder.createUnaryOp(spv::OpBitcast, typeId,
7103 builder.createCompositeConstruct(uvec2Type, components));
7104 }
7105
Rex Xu9d93a232016-05-05 12:30:44 +08007106 case glslang::EOpMinInvocations:
7107 case glslang::EOpMaxInvocations:
7108 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007109 case glslang::EOpMinInvocationsInclusiveScan:
7110 case glslang::EOpMaxInvocationsInclusiveScan:
7111 case glslang::EOpAddInvocationsInclusiveScan:
7112 case glslang::EOpMinInvocationsExclusiveScan:
7113 case glslang::EOpMaxInvocationsExclusiveScan:
7114 case glslang::EOpAddInvocationsExclusiveScan:
7115 if (op == glslang::EOpMinInvocations ||
7116 op == glslang::EOpMinInvocationsInclusiveScan ||
7117 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007118 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007119 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007120 else {
7121 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007122 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007123 else
Rex Xu51596642016-09-21 18:56:12 +08007124 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007125 }
Rex Xu430ef402016-10-14 17:22:23 +08007126 } else if (op == glslang::EOpMaxInvocations ||
7127 op == glslang::EOpMaxInvocationsInclusiveScan ||
7128 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007129 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007130 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007131 else {
7132 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007133 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007134 else
Rex Xu51596642016-09-21 18:56:12 +08007135 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007136 }
7137 } else {
7138 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007139 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007140 else
Rex Xu51596642016-09-21 18:56:12 +08007141 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007142 }
7143
Rex Xu2bbbe062016-08-23 15:41:05 +08007144 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007145 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007146
7147 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007148 case glslang::EOpMinInvocationsNonUniform:
7149 case glslang::EOpMaxInvocationsNonUniform:
7150 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007151 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7152 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7153 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7154 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7155 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7156 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7157 if (op == glslang::EOpMinInvocationsNonUniform ||
7158 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7159 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007160 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007161 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007162 else {
7163 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007164 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007165 else
Rex Xu51596642016-09-21 18:56:12 +08007166 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007167 }
7168 }
Rex Xu430ef402016-10-14 17:22:23 +08007169 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7170 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7171 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007172 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007173 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007174 else {
7175 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007176 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007177 else
Rex Xu51596642016-09-21 18:56:12 +08007178 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007179 }
7180 }
7181 else {
7182 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007183 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007184 else
Rex Xu51596642016-09-21 18:56:12 +08007185 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007186 }
7187
Rex Xu2bbbe062016-08-23 15:41:05 +08007188 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007189 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007190
7191 break;
John Kessenich91cef522016-05-05 16:45:40 -06007192 default:
7193 logger->missingFunctionality("invocation operation");
7194 return spv::NoResult;
7195 }
Rex Xu51596642016-09-21 18:56:12 +08007196
7197 assert(opCode != spv::OpNop);
7198 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007199}
7200
Rex Xu2bbbe062016-08-23 15:41:05 +08007201// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007202spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7203 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007204{
7205 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7206 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007207 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007208 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007209 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7210 op == spv::OpGroupSMinNonUniformAMD ||
7211 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7212 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007213 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7214
7215 // Handle group invocation operations scalar by scalar.
7216 // The result type is the same type as the original type.
7217 // The algorithm is to:
7218 // - break the vector into scalars
7219 // - apply the operation to each scalar
7220 // - make a vector out the scalar results
7221
7222 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007223 int numComponents = builder.getNumComponents(operands[0]);
7224 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007225 std::vector<spv::Id> results;
7226
7227 // do each scalar op
7228 for (int comp = 0; comp < numComponents; ++comp) {
7229 std::vector<unsigned int> indexes;
7230 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007231 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7232 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007233 if (op == spv::OpSubgroupReadInvocationKHR) {
7234 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007235 spv::IdImmediate operand = { true, operands[1] };
7236 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007237 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007238 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7239 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007240 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007241 spv::IdImmediate operand = { true, operands[1] };
7242 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007243 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007244 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7245 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007246 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007247 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007248 spvGroupOperands.push_back(scalar);
7249 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007250
Rex Xub7072052016-09-26 15:53:40 +08007251 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007252 }
7253
7254 // put the pieces together
7255 return builder.createCompositeConstruct(typeId, results);
7256}
Rex Xu2bbbe062016-08-23 15:41:05 +08007257
John Kessenich66011cb2018-03-06 16:12:04 -07007258// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007259spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7260 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007261{
7262 // Add the required capabilities.
7263 switch (op) {
7264 case glslang::EOpSubgroupElect:
7265 builder.addCapability(spv::CapabilityGroupNonUniform);
7266 break;
7267 case glslang::EOpSubgroupAll:
7268 case glslang::EOpSubgroupAny:
7269 case glslang::EOpSubgroupAllEqual:
7270 builder.addCapability(spv::CapabilityGroupNonUniform);
7271 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7272 break;
7273 case glslang::EOpSubgroupBroadcast:
7274 case glslang::EOpSubgroupBroadcastFirst:
7275 case glslang::EOpSubgroupBallot:
7276 case glslang::EOpSubgroupInverseBallot:
7277 case glslang::EOpSubgroupBallotBitExtract:
7278 case glslang::EOpSubgroupBallotBitCount:
7279 case glslang::EOpSubgroupBallotInclusiveBitCount:
7280 case glslang::EOpSubgroupBallotExclusiveBitCount:
7281 case glslang::EOpSubgroupBallotFindLSB:
7282 case glslang::EOpSubgroupBallotFindMSB:
7283 builder.addCapability(spv::CapabilityGroupNonUniform);
7284 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7285 break;
7286 case glslang::EOpSubgroupShuffle:
7287 case glslang::EOpSubgroupShuffleXor:
7288 builder.addCapability(spv::CapabilityGroupNonUniform);
7289 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7290 break;
7291 case glslang::EOpSubgroupShuffleUp:
7292 case glslang::EOpSubgroupShuffleDown:
7293 builder.addCapability(spv::CapabilityGroupNonUniform);
7294 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7295 break;
7296 case glslang::EOpSubgroupAdd:
7297 case glslang::EOpSubgroupMul:
7298 case glslang::EOpSubgroupMin:
7299 case glslang::EOpSubgroupMax:
7300 case glslang::EOpSubgroupAnd:
7301 case glslang::EOpSubgroupOr:
7302 case glslang::EOpSubgroupXor:
7303 case glslang::EOpSubgroupInclusiveAdd:
7304 case glslang::EOpSubgroupInclusiveMul:
7305 case glslang::EOpSubgroupInclusiveMin:
7306 case glslang::EOpSubgroupInclusiveMax:
7307 case glslang::EOpSubgroupInclusiveAnd:
7308 case glslang::EOpSubgroupInclusiveOr:
7309 case glslang::EOpSubgroupInclusiveXor:
7310 case glslang::EOpSubgroupExclusiveAdd:
7311 case glslang::EOpSubgroupExclusiveMul:
7312 case glslang::EOpSubgroupExclusiveMin:
7313 case glslang::EOpSubgroupExclusiveMax:
7314 case glslang::EOpSubgroupExclusiveAnd:
7315 case glslang::EOpSubgroupExclusiveOr:
7316 case glslang::EOpSubgroupExclusiveXor:
7317 builder.addCapability(spv::CapabilityGroupNonUniform);
7318 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7319 break;
7320 case glslang::EOpSubgroupClusteredAdd:
7321 case glslang::EOpSubgroupClusteredMul:
7322 case glslang::EOpSubgroupClusteredMin:
7323 case glslang::EOpSubgroupClusteredMax:
7324 case glslang::EOpSubgroupClusteredAnd:
7325 case glslang::EOpSubgroupClusteredOr:
7326 case glslang::EOpSubgroupClusteredXor:
7327 builder.addCapability(spv::CapabilityGroupNonUniform);
7328 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7329 break;
7330 case glslang::EOpSubgroupQuadBroadcast:
7331 case glslang::EOpSubgroupQuadSwapHorizontal:
7332 case glslang::EOpSubgroupQuadSwapVertical:
7333 case glslang::EOpSubgroupQuadSwapDiagonal:
7334 builder.addCapability(spv::CapabilityGroupNonUniform);
7335 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7336 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007337 case glslang::EOpSubgroupPartitionedAdd:
7338 case glslang::EOpSubgroupPartitionedMul:
7339 case glslang::EOpSubgroupPartitionedMin:
7340 case glslang::EOpSubgroupPartitionedMax:
7341 case glslang::EOpSubgroupPartitionedAnd:
7342 case glslang::EOpSubgroupPartitionedOr:
7343 case glslang::EOpSubgroupPartitionedXor:
7344 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7345 case glslang::EOpSubgroupPartitionedInclusiveMul:
7346 case glslang::EOpSubgroupPartitionedInclusiveMin:
7347 case glslang::EOpSubgroupPartitionedInclusiveMax:
7348 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7349 case glslang::EOpSubgroupPartitionedInclusiveOr:
7350 case glslang::EOpSubgroupPartitionedInclusiveXor:
7351 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7352 case glslang::EOpSubgroupPartitionedExclusiveMul:
7353 case glslang::EOpSubgroupPartitionedExclusiveMin:
7354 case glslang::EOpSubgroupPartitionedExclusiveMax:
7355 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7356 case glslang::EOpSubgroupPartitionedExclusiveOr:
7357 case glslang::EOpSubgroupPartitionedExclusiveXor:
7358 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7359 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7360 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007361 default: assert(0 && "Unhandled subgroup operation!");
7362 }
7363
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007364
7365 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7366 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007367 const bool isBool = typeProxy == glslang::EbtBool;
7368
7369 spv::Op opCode = spv::OpNop;
7370
7371 // Figure out which opcode to use.
7372 switch (op) {
7373 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7374 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7375 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7376 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7377 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7378 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7379 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7380 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7381 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7382 case glslang::EOpSubgroupBallotBitCount:
7383 case glslang::EOpSubgroupBallotInclusiveBitCount:
7384 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7385 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7386 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7387 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7388 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7389 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7390 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7391 case glslang::EOpSubgroupAdd:
7392 case glslang::EOpSubgroupInclusiveAdd:
7393 case glslang::EOpSubgroupExclusiveAdd:
7394 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007395 case glslang::EOpSubgroupPartitionedAdd:
7396 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7397 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007398 if (isFloat) {
7399 opCode = spv::OpGroupNonUniformFAdd;
7400 } else {
7401 opCode = spv::OpGroupNonUniformIAdd;
7402 }
7403 break;
7404 case glslang::EOpSubgroupMul:
7405 case glslang::EOpSubgroupInclusiveMul:
7406 case glslang::EOpSubgroupExclusiveMul:
7407 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007408 case glslang::EOpSubgroupPartitionedMul:
7409 case glslang::EOpSubgroupPartitionedInclusiveMul:
7410 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007411 if (isFloat) {
7412 opCode = spv::OpGroupNonUniformFMul;
7413 } else {
7414 opCode = spv::OpGroupNonUniformIMul;
7415 }
7416 break;
7417 case glslang::EOpSubgroupMin:
7418 case glslang::EOpSubgroupInclusiveMin:
7419 case glslang::EOpSubgroupExclusiveMin:
7420 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007421 case glslang::EOpSubgroupPartitionedMin:
7422 case glslang::EOpSubgroupPartitionedInclusiveMin:
7423 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007424 if (isFloat) {
7425 opCode = spv::OpGroupNonUniformFMin;
7426 } else if (isUnsigned) {
7427 opCode = spv::OpGroupNonUniformUMin;
7428 } else {
7429 opCode = spv::OpGroupNonUniformSMin;
7430 }
7431 break;
7432 case glslang::EOpSubgroupMax:
7433 case glslang::EOpSubgroupInclusiveMax:
7434 case glslang::EOpSubgroupExclusiveMax:
7435 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007436 case glslang::EOpSubgroupPartitionedMax:
7437 case glslang::EOpSubgroupPartitionedInclusiveMax:
7438 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007439 if (isFloat) {
7440 opCode = spv::OpGroupNonUniformFMax;
7441 } else if (isUnsigned) {
7442 opCode = spv::OpGroupNonUniformUMax;
7443 } else {
7444 opCode = spv::OpGroupNonUniformSMax;
7445 }
7446 break;
7447 case glslang::EOpSubgroupAnd:
7448 case glslang::EOpSubgroupInclusiveAnd:
7449 case glslang::EOpSubgroupExclusiveAnd:
7450 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007451 case glslang::EOpSubgroupPartitionedAnd:
7452 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7453 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007454 if (isBool) {
7455 opCode = spv::OpGroupNonUniformLogicalAnd;
7456 } else {
7457 opCode = spv::OpGroupNonUniformBitwiseAnd;
7458 }
7459 break;
7460 case glslang::EOpSubgroupOr:
7461 case glslang::EOpSubgroupInclusiveOr:
7462 case glslang::EOpSubgroupExclusiveOr:
7463 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007464 case glslang::EOpSubgroupPartitionedOr:
7465 case glslang::EOpSubgroupPartitionedInclusiveOr:
7466 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007467 if (isBool) {
7468 opCode = spv::OpGroupNonUniformLogicalOr;
7469 } else {
7470 opCode = spv::OpGroupNonUniformBitwiseOr;
7471 }
7472 break;
7473 case glslang::EOpSubgroupXor:
7474 case glslang::EOpSubgroupInclusiveXor:
7475 case glslang::EOpSubgroupExclusiveXor:
7476 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007477 case glslang::EOpSubgroupPartitionedXor:
7478 case glslang::EOpSubgroupPartitionedInclusiveXor:
7479 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007480 if (isBool) {
7481 opCode = spv::OpGroupNonUniformLogicalXor;
7482 } else {
7483 opCode = spv::OpGroupNonUniformBitwiseXor;
7484 }
7485 break;
7486 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7487 case glslang::EOpSubgroupQuadSwapHorizontal:
7488 case glslang::EOpSubgroupQuadSwapVertical:
7489 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7490 default: assert(0 && "Unhandled subgroup operation!");
7491 }
7492
John Kessenich149afc32018-08-14 13:31:43 -06007493 // get the right Group Operation
7494 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007495 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007496 default:
7497 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007498 case glslang::EOpSubgroupBallotBitCount:
7499 case glslang::EOpSubgroupAdd:
7500 case glslang::EOpSubgroupMul:
7501 case glslang::EOpSubgroupMin:
7502 case glslang::EOpSubgroupMax:
7503 case glslang::EOpSubgroupAnd:
7504 case glslang::EOpSubgroupOr:
7505 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007506 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007507 break;
7508 case glslang::EOpSubgroupBallotInclusiveBitCount:
7509 case glslang::EOpSubgroupInclusiveAdd:
7510 case glslang::EOpSubgroupInclusiveMul:
7511 case glslang::EOpSubgroupInclusiveMin:
7512 case glslang::EOpSubgroupInclusiveMax:
7513 case glslang::EOpSubgroupInclusiveAnd:
7514 case glslang::EOpSubgroupInclusiveOr:
7515 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007516 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007517 break;
7518 case glslang::EOpSubgroupBallotExclusiveBitCount:
7519 case glslang::EOpSubgroupExclusiveAdd:
7520 case glslang::EOpSubgroupExclusiveMul:
7521 case glslang::EOpSubgroupExclusiveMin:
7522 case glslang::EOpSubgroupExclusiveMax:
7523 case glslang::EOpSubgroupExclusiveAnd:
7524 case glslang::EOpSubgroupExclusiveOr:
7525 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007526 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007527 break;
7528 case glslang::EOpSubgroupClusteredAdd:
7529 case glslang::EOpSubgroupClusteredMul:
7530 case glslang::EOpSubgroupClusteredMin:
7531 case glslang::EOpSubgroupClusteredMax:
7532 case glslang::EOpSubgroupClusteredAnd:
7533 case glslang::EOpSubgroupClusteredOr:
7534 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007535 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007536 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007537 case glslang::EOpSubgroupPartitionedAdd:
7538 case glslang::EOpSubgroupPartitionedMul:
7539 case glslang::EOpSubgroupPartitionedMin:
7540 case glslang::EOpSubgroupPartitionedMax:
7541 case glslang::EOpSubgroupPartitionedAnd:
7542 case glslang::EOpSubgroupPartitionedOr:
7543 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007544 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007545 break;
7546 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7547 case glslang::EOpSubgroupPartitionedInclusiveMul:
7548 case glslang::EOpSubgroupPartitionedInclusiveMin:
7549 case glslang::EOpSubgroupPartitionedInclusiveMax:
7550 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7551 case glslang::EOpSubgroupPartitionedInclusiveOr:
7552 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007553 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007554 break;
7555 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7556 case glslang::EOpSubgroupPartitionedExclusiveMul:
7557 case glslang::EOpSubgroupPartitionedExclusiveMin:
7558 case glslang::EOpSubgroupPartitionedExclusiveMax:
7559 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7560 case glslang::EOpSubgroupPartitionedExclusiveOr:
7561 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007562 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007563 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007564 }
7565
John Kessenich149afc32018-08-14 13:31:43 -06007566 // build the instruction
7567 std::vector<spv::IdImmediate> spvGroupOperands;
7568
7569 // Every operation begins with the Execution Scope operand.
7570 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7571 spvGroupOperands.push_back(executionScope);
7572
7573 // Next, for all operations that use a Group Operation, push that as an operand.
7574 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007575 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007576 spvGroupOperands.push_back(groupOperand);
7577 }
7578
John Kessenich66011cb2018-03-06 16:12:04 -07007579 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007580 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7581 spv::IdImmediate operand = { true, *opIt };
7582 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007583 }
7584
7585 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007586 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007587 switch (op) {
7588 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007589 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7590 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7591 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7592 }
7593 if (directionId != spv::NoResult) {
7594 spv::IdImmediate direction = { true, directionId };
7595 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007596 }
7597
7598 return builder.createOp(opCode, typeId, spvGroupOperands);
7599}
7600
John Kessenich8985fc92020-03-03 10:25:07 -07007601spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7602 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007603{
John Kessenich66011cb2018-03-06 16:12:04 -07007604 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7605 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007606
John Kessenich140f3df2015-06-26 16:58:36 -06007607 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007608 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007609 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007610 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007611 spv::Id typeId0 = 0;
7612 if (consumedOperands > 0)
7613 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007614 spv::Id typeId1 = 0;
7615 if (consumedOperands > 1)
7616 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007617 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007618
7619 switch (op) {
7620 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007621 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007622 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007623 else if (isUnsigned)
7624 libCall = spv::GLSLstd450UMin;
7625 else
7626 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007627 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007628 break;
7629 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007630 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007631 break;
7632 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007633 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007634 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007635 else if (isUnsigned)
7636 libCall = spv::GLSLstd450UMax;
7637 else
7638 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007639 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007640 break;
7641 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007642 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007643 break;
7644 case glslang::EOpDot:
7645 opCode = spv::OpDot;
7646 break;
7647 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007648 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007649 break;
7650
7651 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007652 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007653 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007654 else if (isUnsigned)
7655 libCall = spv::GLSLstd450UClamp;
7656 else
7657 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007658 builder.promoteScalar(precision, operands.front(), operands[1]);
7659 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007660 break;
7661 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007662 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7663 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007664 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007665 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007666 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007667 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007668 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007669 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007670 break;
7671 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007672 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007673 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007674 break;
7675 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007676 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007677 builder.promoteScalar(precision, operands[0], operands[2]);
7678 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007679 break;
7680
7681 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007682 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007683 break;
7684 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007685 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007686 break;
7687 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007688 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007689 break;
7690 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007691 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007692 break;
7693 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007694 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007695 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007696 case glslang::EOpBarrier:
7697 {
7698 // This is for the extended controlBarrier function, with four operands.
7699 // The unextended barrier() goes through createNoArgOperation.
7700 assert(operands.size() == 4);
7701 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7702 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7703 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007704 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7705 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007706 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7707 spv::MemorySemanticsMakeVisibleKHRMask |
7708 spv::MemorySemanticsOutputMemoryKHRMask |
7709 spv::MemorySemanticsVolatileMask)) {
7710 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7711 }
John Kessenich8985fc92020-03-03 10:25:07 -07007712 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7713 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007714 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7715 }
7716 return 0;
7717 }
7718 break;
7719 case glslang::EOpMemoryBarrier:
7720 {
7721 // This is for the extended memoryBarrier function, with three operands.
7722 // The unextended memoryBarrier() goes through createNoArgOperation.
7723 assert(operands.size() == 3);
7724 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7725 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7726 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7727 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7728 spv::MemorySemanticsMakeVisibleKHRMask |
7729 spv::MemorySemanticsOutputMemoryKHRMask |
7730 spv::MemorySemanticsVolatileMask)) {
7731 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7732 }
7733 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7734 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7735 }
7736 return 0;
7737 }
7738 break;
7739
John Kessenicha28f7a72019-08-06 07:00:58 -06007740#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007741 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007742 if (typeProxy == glslang::EbtFloat16)
7743 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007744 libCall = spv::GLSLstd450InterpolateAtSample;
7745 break;
7746 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007747 if (typeProxy == glslang::EbtFloat16)
7748 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007749 libCall = spv::GLSLstd450InterpolateAtOffset;
7750 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007751 case glslang::EOpAddCarry:
7752 opCode = spv::OpIAddCarry;
7753 typeId = builder.makeStructResultType(typeId0, typeId0);
7754 consumedOperands = 2;
7755 break;
7756 case glslang::EOpSubBorrow:
7757 opCode = spv::OpISubBorrow;
7758 typeId = builder.makeStructResultType(typeId0, typeId0);
7759 consumedOperands = 2;
7760 break;
7761 case glslang::EOpUMulExtended:
7762 opCode = spv::OpUMulExtended;
7763 typeId = builder.makeStructResultType(typeId0, typeId0);
7764 consumedOperands = 2;
7765 break;
7766 case glslang::EOpIMulExtended:
7767 opCode = spv::OpSMulExtended;
7768 typeId = builder.makeStructResultType(typeId0, typeId0);
7769 consumedOperands = 2;
7770 break;
7771 case glslang::EOpBitfieldExtract:
7772 if (isUnsigned)
7773 opCode = spv::OpBitFieldUExtract;
7774 else
7775 opCode = spv::OpBitFieldSExtract;
7776 break;
7777 case glslang::EOpBitfieldInsert:
7778 opCode = spv::OpBitFieldInsert;
7779 break;
7780
7781 case glslang::EOpFma:
7782 libCall = spv::GLSLstd450Fma;
7783 break;
7784 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007785 {
7786 libCall = spv::GLSLstd450FrexpStruct;
7787 assert(builder.isPointerType(typeId1));
7788 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007789 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007790 if (width == 16)
7791 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7792 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007793 if (builder.getNumComponents(operands[0]) == 1)
7794 frexpIntType = builder.makeIntegerType(width, true);
7795 else
John Kessenich8985fc92020-03-03 10:25:07 -07007796 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7797 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007798 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7799 consumedOperands = 1;
7800 }
John Kessenich55e7d112015-11-15 21:33:39 -07007801 break;
7802 case glslang::EOpLdexp:
7803 libCall = spv::GLSLstd450Ldexp;
7804 break;
7805
Rex Xu574ab042016-04-14 16:53:07 +08007806 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007807 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007808
John Kessenich66011cb2018-03-06 16:12:04 -07007809 case glslang::EOpSubgroupBroadcast:
7810 case glslang::EOpSubgroupBallotBitExtract:
7811 case glslang::EOpSubgroupShuffle:
7812 case glslang::EOpSubgroupShuffleXor:
7813 case glslang::EOpSubgroupShuffleUp:
7814 case glslang::EOpSubgroupShuffleDown:
7815 case glslang::EOpSubgroupClusteredAdd:
7816 case glslang::EOpSubgroupClusteredMul:
7817 case glslang::EOpSubgroupClusteredMin:
7818 case glslang::EOpSubgroupClusteredMax:
7819 case glslang::EOpSubgroupClusteredAnd:
7820 case glslang::EOpSubgroupClusteredOr:
7821 case glslang::EOpSubgroupClusteredXor:
7822 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007823 case glslang::EOpSubgroupPartitionedAdd:
7824 case glslang::EOpSubgroupPartitionedMul:
7825 case glslang::EOpSubgroupPartitionedMin:
7826 case glslang::EOpSubgroupPartitionedMax:
7827 case glslang::EOpSubgroupPartitionedAnd:
7828 case glslang::EOpSubgroupPartitionedOr:
7829 case glslang::EOpSubgroupPartitionedXor:
7830 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7831 case glslang::EOpSubgroupPartitionedInclusiveMul:
7832 case glslang::EOpSubgroupPartitionedInclusiveMin:
7833 case glslang::EOpSubgroupPartitionedInclusiveMax:
7834 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7835 case glslang::EOpSubgroupPartitionedInclusiveOr:
7836 case glslang::EOpSubgroupPartitionedInclusiveXor:
7837 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7838 case glslang::EOpSubgroupPartitionedExclusiveMul:
7839 case glslang::EOpSubgroupPartitionedExclusiveMin:
7840 case glslang::EOpSubgroupPartitionedExclusiveMax:
7841 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7842 case glslang::EOpSubgroupPartitionedExclusiveOr:
7843 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007844 return createSubgroupOperation(op, typeId, operands, typeProxy);
7845
Rex Xu9d93a232016-05-05 12:30:44 +08007846 case glslang::EOpSwizzleInvocations:
7847 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7848 libCall = spv::SwizzleInvocationsAMD;
7849 break;
7850 case glslang::EOpSwizzleInvocationsMasked:
7851 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7852 libCall = spv::SwizzleInvocationsMaskedAMD;
7853 break;
7854 case glslang::EOpWriteInvocation:
7855 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7856 libCall = spv::WriteInvocationAMD;
7857 break;
7858
7859 case glslang::EOpMin3:
7860 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7861 if (isFloat)
7862 libCall = spv::FMin3AMD;
7863 else {
7864 if (isUnsigned)
7865 libCall = spv::UMin3AMD;
7866 else
7867 libCall = spv::SMin3AMD;
7868 }
7869 break;
7870 case glslang::EOpMax3:
7871 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7872 if (isFloat)
7873 libCall = spv::FMax3AMD;
7874 else {
7875 if (isUnsigned)
7876 libCall = spv::UMax3AMD;
7877 else
7878 libCall = spv::SMax3AMD;
7879 }
7880 break;
7881 case glslang::EOpMid3:
7882 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7883 if (isFloat)
7884 libCall = spv::FMid3AMD;
7885 else {
7886 if (isUnsigned)
7887 libCall = spv::UMid3AMD;
7888 else
7889 libCall = spv::SMid3AMD;
7890 }
7891 break;
7892
7893 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007894 if (typeProxy == glslang::EbtFloat16)
7895 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007896 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7897 libCall = spv::InterpolateAtVertexAMD;
7898 break;
Chao Chen3c366992018-09-19 11:41:59 -07007899
Daniel Kochdb32b242020-03-17 20:42:47 -04007900 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007901 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007902 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007903 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05007904 case glslang::EOpTraceNV:
7905 builder.createNoResultOp(spv::OpTraceNV, operands);
7906 return 0;
7907 case glslang::EOpTraceKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007908 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007909 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05007910 case glslang::EOpExecuteCallableNV:
7911 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
7912 return 0;
7913 case glslang::EOpExecuteCallableKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007914 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007915 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007916
7917 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007918 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7919 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007920 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007921 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7922 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007923 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007924 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7925 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007926 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007927 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7928 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007929 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007930 typeId = builder.makeBoolType();
7931 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007932 break;
7933 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007934 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007935 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007936 break;
7937 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007938 typeId = builder.makeFloatType(32);
7939 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007940 break;
7941 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007942 typeId = builder.makeIntType(32);
7943 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007944 break;
7945 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007946 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007947 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007948 break;
7949 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007950 typeId = builder.makeIntType(32);
7951 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007952 break;
7953 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007954 typeId = builder.makeIntType(32);
7955 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007956 break;
7957 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007958 typeId = builder.makeIntType(32);
7959 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007960 break;
7961 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007962 typeId = builder.makeIntType(32);
7963 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007964 break;
7965 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007966 typeId = builder.makeIntType(32);
7967 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007968 break;
7969 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007970 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7971 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007972 break;
7973 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007974 typeId = builder.makeBoolType();
7975 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007976 break;
7977 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007978 typeId = builder.makeBoolType();
7979 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007980 break;
7981 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007982 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7983 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007984 break;
7985 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007986 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7987 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007988 break;
7989 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007990 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7991 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007992 break;
7993 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007994 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7995 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007996 break;
7997 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007998 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007999 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008000 break;
8001 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04008002 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008003 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008004 break;
Chao Chen3c366992018-09-19 11:41:59 -07008005 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
8006 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
8007 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008008 case glslang::EOpCooperativeMatrixMulAdd:
8009 opCode = spv::OpCooperativeMatrixMulAddNV;
8010 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06008011#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06008012 default:
8013 return 0;
8014 }
8015
8016 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07008017 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05008018 // Use an extended instruction from the standard library.
8019 // Construct the call arguments, without modifying the original operands vector.
8020 // We might need the remaining arguments, e.g. in the EOpFrexp case.
8021 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08008022 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01008023 } else if (opCode == spv::OpDot && !isFloat) {
8024 // int dot(int, int)
8025 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
8026 const int componentCount = builder.getNumComponents(operands[0]);
8027 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
8028 builder.setPrecision(mulOp, precision);
8029 id = builder.createCompositeExtract(mulOp, typeId, 0);
8030 for (int i = 1; i < componentCount; ++i) {
8031 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07008032 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01008033 }
John Kessenich2359bd02015-12-06 19:29:11 -07008034 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07008035 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06008036 case 0:
8037 // should all be handled by visitAggregate and createNoArgOperation
8038 assert(0);
8039 return 0;
8040 case 1:
8041 // should all be handled by createUnaryOperation
8042 assert(0);
8043 return 0;
8044 case 2:
8045 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
8046 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008047 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008048 // anything 3 or over doesn't have l-value operands, so all should be consumed
8049 assert(consumedOperands == operands.size());
8050 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06008051 break;
8052 }
8053 }
8054
John Kessenichb9197c82019-08-11 07:41:45 -06008055#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07008056 // Decode the return types that were structures
8057 switch (op) {
8058 case glslang::EOpAddCarry:
8059 case glslang::EOpSubBorrow:
8060 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8061 id = builder.createCompositeExtract(id, typeId0, 0);
8062 break;
8063 case glslang::EOpUMulExtended:
8064 case glslang::EOpIMulExtended:
8065 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
8066 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8067 break;
8068 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08008069 {
8070 assert(operands.size() == 2);
8071 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
8072 // "exp" is floating-point type (from HLSL intrinsic)
8073 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
8074 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
8075 builder.createStore(member1, operands[1]);
8076 } else
8077 // "exp" is integer type (from GLSL built-in function)
8078 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
8079 id = builder.createCompositeExtract(id, typeId0, 0);
8080 }
John Kessenich55e7d112015-11-15 21:33:39 -07008081 break;
8082 default:
8083 break;
8084 }
John Kessenichb9197c82019-08-11 07:41:45 -06008085#endif
John Kessenich55e7d112015-11-15 21:33:39 -07008086
John Kessenich32cfd492016-02-02 12:37:46 -07008087 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06008088}
8089
Rex Xu9d93a232016-05-05 12:30:44 +08008090// Intrinsics with no arguments (or no return value, and no precision).
8091spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06008092{
Jeff Bolz36831c92018-09-05 10:11:41 -05008093 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07008094 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
8095 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06008096
8097 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06008098 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008099 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05008100 if (glslangIntermediate->usingVulkanMemoryModel()) {
8101 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8102 spv::MemorySemanticsOutputMemoryKHRMask |
8103 spv::MemorySemanticsAcquireReleaseMask);
8104 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
8105 } else {
8106 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
8107 }
John Kessenich82979362017-12-11 04:02:24 -07008108 } else {
8109 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8110 spv::MemorySemanticsWorkgroupMemoryMask |
8111 spv::MemorySemanticsAcquireReleaseMask);
8112 }
John Kessenich140f3df2015-06-26 16:58:36 -06008113 return 0;
8114 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008115 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8116 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008117 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008118 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008119 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8120 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008121 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008122 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008123 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8124 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008125 return 0;
8126 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008127 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8128 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008129 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008130#ifndef GLSLANG_WEB
8131 case glslang::EOpMemoryBarrierAtomicCounter:
8132 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8133 spv::MemorySemanticsAcquireReleaseMask);
8134 return 0;
8135 case glslang::EOpMemoryBarrierImage:
8136 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8137 spv::MemorySemanticsAcquireReleaseMask);
8138 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008139 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008140 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008141 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008142 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008143 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008144 case glslang::EOpDeviceMemoryBarrier:
8145 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8146 spv::MemorySemanticsImageMemoryMask |
8147 spv::MemorySemanticsAcquireReleaseMask);
8148 return 0;
8149 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8150 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8151 spv::MemorySemanticsImageMemoryMask |
8152 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008153 return 0;
8154 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008155 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8156 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008157 return 0;
8158 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008159 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8160 spv::MemorySemanticsWorkgroupMemoryMask |
8161 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008162 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008163 case glslang::EOpSubgroupBarrier:
8164 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8165 spv::MemorySemanticsAcquireReleaseMask);
8166 return spv::NoResult;
8167 case glslang::EOpSubgroupMemoryBarrier:
8168 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8169 spv::MemorySemanticsAcquireReleaseMask);
8170 return spv::NoResult;
8171 case glslang::EOpSubgroupMemoryBarrierBuffer:
8172 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8173 spv::MemorySemanticsAcquireReleaseMask);
8174 return spv::NoResult;
8175 case glslang::EOpSubgroupMemoryBarrierImage:
8176 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8177 spv::MemorySemanticsAcquireReleaseMask);
8178 return spv::NoResult;
8179 case glslang::EOpSubgroupMemoryBarrierShared:
8180 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8181 spv::MemorySemanticsAcquireReleaseMask);
8182 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008183
8184 case glslang::EOpEmitVertex:
8185 builder.createNoResultOp(spv::OpEmitVertex);
8186 return 0;
8187 case glslang::EOpEndPrimitive:
8188 builder.createNoResultOp(spv::OpEndPrimitive);
8189 return 0;
8190
John Kessenich66011cb2018-03-06 16:12:04 -07008191 case glslang::EOpSubgroupElect: {
8192 std::vector<spv::Id> operands;
8193 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8194 }
Rex Xu9d93a232016-05-05 12:30:44 +08008195 case glslang::EOpTime:
8196 {
8197 std::vector<spv::Id> args; // Dummy arguments
8198 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8199 return builder.setPrecision(id, precision);
8200 }
Daniel Kochffccefd2020-11-23 15:41:27 -05008201 case glslang::EOpIgnoreIntersectionNV:
8202 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008203 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05008204 case glslang::EOpTerminateRayNV:
8205 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008206 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008207 case glslang::EOpRayQueryInitialize:
8208 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8209 return 0;
8210 case glslang::EOpRayQueryTerminate:
8211 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8212 return 0;
8213 case glslang::EOpRayQueryGenerateIntersection:
8214 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8215 return 0;
8216 case glslang::EOpRayQueryConfirmIntersection:
8217 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8218 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008219 case glslang::EOpBeginInvocationInterlock:
8220 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8221 return 0;
8222 case glslang::EOpEndInvocationInterlock:
8223 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8224 return 0;
8225
Jeff Bolzba6170b2019-07-01 09:23:23 -05008226 case glslang::EOpIsHelperInvocation:
8227 {
8228 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008229 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8230 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8231 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008232 }
8233
amhagan91fb0092019-07-10 21:14:38 -04008234 case glslang::EOpReadClockSubgroupKHR: {
8235 std::vector<spv::Id> args;
8236 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8237 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8238 builder.addCapability(spv::CapabilityShaderClockKHR);
8239 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8240 }
8241
8242 case glslang::EOpReadClockDeviceKHR: {
8243 std::vector<spv::Id> args;
8244 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8245 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8246 builder.addCapability(spv::CapabilityShaderClockKHR);
8247 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8248 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008249#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008250 default:
John Kessenich155d3512019-08-08 23:29:20 -06008251 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008252 }
John Kessenich155d3512019-08-08 23:29:20 -06008253
8254 logger->missingFunctionality("unknown operation with no arguments");
8255
8256 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008257}
8258
8259spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8260{
John Kessenich2f273362015-07-18 22:34:27 -06008261 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008262 spv::Id id;
8263 if (symbolValues.end() != iter) {
8264 id = iter->second;
8265 return id;
8266 }
8267
8268 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008269 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008270 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008271 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008272 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008273 if (forcedType.second != spv::NoType)
8274 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008275
Rex Xuc884b4a2016-06-29 15:03:44 +08008276 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008277 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8278 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8279 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008280#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008281 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008282 if (symbol->getQualifier().hasComponent())
8283 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8284 if (symbol->getQualifier().hasIndex())
8285 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008286#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008287 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008288 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008289 // atomic counters use this:
8290 if (symbol->getQualifier().hasOffset())
8291 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008292 }
8293
scygan2c864272016-05-18 18:09:17 +02008294 if (symbol->getQualifier().hasLocation())
8295 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008296 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008297 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008298 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008299 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008300 }
John Kessenich140f3df2015-06-26 16:58:36 -06008301 if (symbol->getQualifier().hasSet())
8302 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008303 else if (IsDescriptorResource(symbol->getType())) {
8304 // default to 0
8305 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8306 }
John Kessenich140f3df2015-06-26 16:58:36 -06008307 if (symbol->getQualifier().hasBinding())
8308 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008309 else if (IsDescriptorResource(symbol->getType())) {
8310 // default to 0
8311 builder.addDecoration(id, spv::DecorationBinding, 0);
8312 }
John Kessenich6c292d32016-02-15 20:58:50 -07008313 if (symbol->getQualifier().hasAttachment())
8314 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008315 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008316 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008317 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008318 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008319 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8320 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8321 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8322 }
8323 if (symbol->getQualifier().hasXfbOffset())
8324 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008325 }
8326
John Kessenichb9197c82019-08-11 07:41:45 -06008327 // add built-in variable decoration
8328 if (builtIn != spv::BuiltInMax) {
8329 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8330 }
8331
8332#ifndef GLSLANG_WEB
Daniel Kochffccefd2020-11-23 15:41:27 -05008333 // Subgroup builtins which have input storage class are volatile for ray tracing stages.
8334 if (symbol->getType().isImage() || symbol->getQualifier().isPipeInput()) {
Rex Xu1da878f2016-02-21 20:59:01 +08008335 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008336 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8337 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008338 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008339 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008340 }
8341
chaoc0ad6a4e2016-12-19 16:29:34 -08008342 if (builtIn == spv::BuiltInSampleMask) {
8343 spv::Decoration decoration;
8344 // GL_NV_sample_mask_override_coverage extension
8345 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008346 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008347 else
8348 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008349 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008350 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008351 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008352 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8353 }
8354 }
chaoc771d89f2017-01-13 01:10:53 -08008355 else if (builtIn == spv::BuiltInLayer) {
8356 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008357 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008358 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008359 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8360 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8361 }
John Kessenichb41bff62017-08-11 13:07:17 -06008362 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008363 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8364 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008365 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8366 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8367 }
8368 }
8369
chaoc6e5acae2016-12-20 13:28:52 -08008370 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008371 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008372 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008373 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8374 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008375 if (symbol->getQualifier().pervertexNV) {
8376 builder.addDecoration(id, spv::DecorationPerVertexNV);
8377 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8378 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8379 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008380
John Kessenich5d610ee2018-03-07 18:05:55 -07008381 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8382 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8383 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8384 symbol->getType().getQualifier().semanticName);
8385 }
8386
John Kessenich7015bd62019-08-01 03:28:08 -06008387 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008388 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8389 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008390 }
John Kessenichb9197c82019-08-11 07:41:45 -06008391#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008392
John Kessenich140f3df2015-06-26 16:58:36 -06008393 return id;
8394}
8395
John Kessenicha28f7a72019-08-06 07:00:58 -06008396#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008397// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8398void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8399{
8400 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008401 if (qualifier.perPrimitiveNV) {
8402 // Need to add capability/extension for fragment shader.
8403 // Mesh shader already adds this by default.
8404 if (glslangIntermediate->getStage() == EShLangFragment) {
8405 builder.addCapability(spv::CapabilityMeshShadingNV);
8406 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8407 }
Chao Chen3c366992018-09-19 11:41:59 -07008408 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008409 }
Chao Chen3c366992018-09-19 11:41:59 -07008410 if (qualifier.perViewNV)
8411 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8412 if (qualifier.perTaskNV)
8413 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8414 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008415 if (qualifier.perPrimitiveNV) {
8416 // Need to add capability/extension for fragment shader.
8417 // Mesh shader already adds this by default.
8418 if (glslangIntermediate->getStage() == EShLangFragment) {
8419 builder.addCapability(spv::CapabilityMeshShadingNV);
8420 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8421 }
Chao Chen3c366992018-09-19 11:41:59 -07008422 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008423 }
Chao Chen3c366992018-09-19 11:41:59 -07008424 if (qualifier.perViewNV)
8425 builder.addDecoration(id, spv::DecorationPerViewNV);
8426 if (qualifier.perTaskNV)
8427 builder.addDecoration(id, spv::DecorationPerTaskNV);
8428 }
8429}
8430#endif
8431
John Kessenich55e7d112015-11-15 21:33:39 -07008432// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008433// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008434//
8435// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8436//
8437// Recursively walk the nodes. The nodes form a tree whose leaves are
8438// regular constants, which themselves are trees that createSpvConstant()
8439// recursively walks. So, this function walks the "top" of the tree:
8440// - emit specialization constant-building instructions for specConstant
8441// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008442spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008443{
John Kessenich7cc0e282016-03-20 00:46:02 -06008444 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008445
qining4f4bb812016-04-03 23:55:17 -04008446 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008447 if (! node.getQualifier().specConstant) {
8448 // hand off to the non-spec-constant path
8449 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8450 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008451 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8452 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8453 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008454 }
8455
8456 // We now know we have a specialization constant to build
8457
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008458 // Extra capabilities may be needed.
8459 if (node.getType().contains8BitInt())
8460 builder.addCapability(spv::CapabilityInt8);
8461 if (node.getType().contains16BitFloat())
8462 builder.addCapability(spv::CapabilityFloat16);
8463 if (node.getType().contains16BitInt())
8464 builder.addCapability(spv::CapabilityInt16);
8465 if (node.getType().contains64BitInt())
8466 builder.addCapability(spv::CapabilityInt64);
8467 if (node.getType().containsDouble())
8468 builder.addCapability(spv::CapabilityFloat64);
8469
John Kessenichd94c0032016-05-30 19:29:40 -06008470 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008471 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8472 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8473 std::vector<spv::Id> dimConstId;
8474 for (int dim = 0; dim < 3; ++dim) {
8475 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8476 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008477 if (specConst) {
8478 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8479 glslangIntermediate->getLocalSizeSpecId(dim));
8480 }
qining4f4bb812016-04-03 23:55:17 -04008481 }
8482 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8483 }
8484
8485 // An AST node labelled as specialization constant should be a symbol node.
8486 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8487 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008488 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008489 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008490 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8491 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8492 // will set the builder into spec constant op instruction generating mode.
8493 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008494 result = accessChainLoad(sub_tree->getType());
8495 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008496 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008497 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008498 } else {
8499 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008500 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008501 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008502 builder.addName(result, sn->getName().c_str());
8503 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008504 }
qining4f4bb812016-04-03 23:55:17 -04008505
8506 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8507 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008508 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008509 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008510}
8511
John Kessenich140f3df2015-06-26 16:58:36 -06008512// Use 'consts' as the flattened glslang source of scalar constants to recursively
8513// build the aggregate SPIR-V constant.
8514//
8515// If there are not enough elements present in 'consts', 0 will be substituted;
8516// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8517//
John Kessenich8985fc92020-03-03 10:25:07 -07008518spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8519 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008520{
8521 // vector of constants for SPIR-V
8522 std::vector<spv::Id> spvConsts;
8523
8524 // Type is used for struct and array constants
8525 spv::Id typeId = convertGlslangToSpvType(glslangType);
8526
8527 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008528 glslang::TType elementType(glslangType, 0);
8529 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008530 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008531 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008532 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008533 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008534 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008535 } else if (glslangType.isCoopMat()) {
8536 glslang::TType componentType(glslangType.getBasicType());
8537 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008538 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008539 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8540 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008541 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008542 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008543 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8544 bool zero = nextConst >= consts.size();
8545 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008546 case glslang::EbtInt:
8547 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8548 break;
8549 case glslang::EbtUint:
8550 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8551 break;
8552 case glslang::EbtFloat:
8553 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8554 break;
8555 case glslang::EbtBool:
8556 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8557 break;
8558#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008559 case glslang::EbtInt8:
8560 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8561 break;
8562 case glslang::EbtUint8:
8563 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8564 break;
8565 case glslang::EbtInt16:
8566 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8567 break;
8568 case glslang::EbtUint16:
8569 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8570 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008571 case glslang::EbtInt64:
8572 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8573 break;
8574 case glslang::EbtUint64:
8575 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8576 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008577 case glslang::EbtDouble:
8578 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8579 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008580 case glslang::EbtFloat16:
8581 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8582 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008583#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008584 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008585 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008586 break;
8587 }
8588 ++nextConst;
8589 }
8590 } else {
8591 // we have a non-aggregate (scalar) constant
8592 bool zero = nextConst >= consts.size();
8593 spv::Id scalar = 0;
8594 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008595 case glslang::EbtInt:
8596 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8597 break;
8598 case glslang::EbtUint:
8599 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8600 break;
8601 case glslang::EbtFloat:
8602 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8603 break;
8604 case glslang::EbtBool:
8605 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8606 break;
8607#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008608 case glslang::EbtInt8:
8609 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8610 break;
8611 case glslang::EbtUint8:
8612 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8613 break;
8614 case glslang::EbtInt16:
8615 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8616 break;
8617 case glslang::EbtUint16:
8618 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8619 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008620 case glslang::EbtInt64:
8621 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8622 break;
8623 case glslang::EbtUint64:
8624 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8625 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008626 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008627 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008628 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008629 case glslang::EbtFloat16:
8630 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8631 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008632 case glslang::EbtReference:
8633 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8634 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8635 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008636#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008637 case glslang::EbtString:
8638 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8639 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008640 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008641 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008642 break;
8643 }
8644 ++nextConst;
8645 return scalar;
8646 }
8647
8648 return builder.makeCompositeConstant(typeId, spvConsts);
8649}
8650
John Kessenich7c1aa102015-10-15 13:29:11 -06008651// Return true if the node is a constant or symbol whose reading has no
8652// non-trivial observable cost or effect.
8653bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8654{
8655 // don't know what this is
8656 if (node == nullptr)
8657 return false;
8658
8659 // a constant is safe
8660 if (node->getAsConstantUnion() != nullptr)
8661 return true;
8662
8663 // not a symbol means non-trivial
8664 if (node->getAsSymbolNode() == nullptr)
8665 return false;
8666
8667 // a symbol, depends on what's being read
8668 switch (node->getType().getQualifier().storage) {
8669 case glslang::EvqTemporary:
8670 case glslang::EvqGlobal:
8671 case glslang::EvqIn:
8672 case glslang::EvqInOut:
8673 case glslang::EvqConst:
8674 case glslang::EvqConstReadOnly:
8675 case glslang::EvqUniform:
8676 return true;
8677 default:
8678 return false;
8679 }
qining25262b32016-05-06 17:25:16 -04008680}
John Kessenich7c1aa102015-10-15 13:29:11 -06008681
8682// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008683// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008684// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008685// Return true if trivial.
8686bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8687{
8688 if (node == nullptr)
8689 return false;
8690
John Kessenich84cc15f2017-05-24 16:44:47 -06008691 // count non scalars as trivial, as well as anything coming from HLSL
8692 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008693 return true;
8694
John Kessenich7c1aa102015-10-15 13:29:11 -06008695 // symbols and constants are trivial
8696 if (isTrivialLeaf(node))
8697 return true;
8698
8699 // otherwise, it needs to be a simple operation or one or two leaf nodes
8700
8701 // not a simple operation
8702 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8703 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8704 if (binaryNode == nullptr && unaryNode == nullptr)
8705 return false;
8706
8707 // not on leaf nodes
8708 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8709 return false;
8710
8711 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8712 return false;
8713 }
8714
8715 switch (node->getAsOperator()->getOp()) {
8716 case glslang::EOpLogicalNot:
8717 case glslang::EOpConvIntToBool:
8718 case glslang::EOpConvUintToBool:
8719 case glslang::EOpConvFloatToBool:
8720 case glslang::EOpConvDoubleToBool:
8721 case glslang::EOpEqual:
8722 case glslang::EOpNotEqual:
8723 case glslang::EOpLessThan:
8724 case glslang::EOpGreaterThan:
8725 case glslang::EOpLessThanEqual:
8726 case glslang::EOpGreaterThanEqual:
8727 case glslang::EOpIndexDirect:
8728 case glslang::EOpIndexDirectStruct:
8729 case glslang::EOpLogicalXor:
8730 case glslang::EOpAny:
8731 case glslang::EOpAll:
8732 return true;
8733 default:
8734 return false;
8735 }
8736}
8737
8738// Emit short-circuiting code, where 'right' is never evaluated unless
8739// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008740spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8741 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008742{
8743 spv::Id boolTypeId = builder.makeBoolType();
8744
8745 // emit left operand
8746 builder.clearAccessChain();
8747 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008748 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008749
8750 // Operands to accumulate OpPhi operands
8751 std::vector<spv::Id> phiOperands;
8752 // accumulate left operand's phi information
8753 phiOperands.push_back(leftId);
8754 phiOperands.push_back(builder.getBuildPoint()->getId());
8755
8756 // Make the two kinds of operation symmetric with a "!"
8757 // || => emit "if (! left) result = right"
8758 // && => emit "if ( left) result = right"
8759 //
8760 // TODO: this runtime "not" for || could be avoided by adding functionality
8761 // to 'builder' to have an "else" without an "then"
8762 if (op == glslang::EOpLogicalOr)
8763 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8764
8765 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008766 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008767
8768 // emit right operand as the "then" part of the "if"
8769 builder.clearAccessChain();
8770 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008771 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008772
8773 // accumulate left operand's phi information
8774 phiOperands.push_back(rightId);
8775 phiOperands.push_back(builder.getBuildPoint()->getId());
8776
8777 // finish the "if"
8778 ifBuilder.makeEndIf();
8779
8780 // phi together the two results
8781 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8782}
8783
John Kessenicha28f7a72019-08-06 07:00:58 -06008784#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008785// Return type Id of the imported set of extended instructions corresponds to the name.
8786// Import this set if it has not been imported yet.
8787spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8788{
8789 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8790 return extBuiltinMap[name];
8791 else {
Rex Xu51596642016-09-21 18:56:12 +08008792 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008793 spv::Id extBuiltins = builder.import(name);
8794 extBuiltinMap[name] = extBuiltins;
8795 return extBuiltins;
8796 }
8797}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008798#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008799
John Kessenich140f3df2015-06-26 16:58:36 -06008800}; // end anonymous namespace
8801
8802namespace glslang {
8803
John Kessenich68d78fd2015-07-12 19:28:10 -06008804void GetSpirvVersion(std::string& version)
8805{
John Kessenich9e55f632015-07-15 10:03:39 -06008806 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008807 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008808 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008809 version = buf;
8810}
8811
John Kessenicha372a3e2017-11-02 22:32:14 -06008812// For low-order part of the generator's magic number. Bump up
8813// when there is a change in the style (e.g., if SSA form changes,
8814// or a different instruction sequence to do something gets used).
8815int GetSpirvGeneratorVersion()
8816{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008817 // return 1; // start
8818 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008819 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008820 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008821 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008822 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8823 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008824 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008825 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008826 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8827 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008828}
8829
John Kessenich140f3df2015-06-26 16:58:36 -06008830// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008831void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008832{
8833 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008834 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008835 if (out.fail())
8836 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008837 for (int i = 0; i < (int)spirv.size(); ++i) {
8838 unsigned int word = spirv[i];
8839 out.write((const char*)&word, 4);
8840 }
8841 out.close();
8842}
8843
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008844// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008845void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008846{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008847#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008848 std::ofstream out;
8849 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008850 if (out.fail())
8851 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008852 out << "\t// " <<
8853 GetSpirvGeneratorVersion() <<
8854 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8855 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008856 if (varName != nullptr) {
8857 out << "\t #pragma once" << std::endl;
8858 out << "const uint32_t " << varName << "[] = {" << std::endl;
8859 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008860 const int WORDS_PER_LINE = 8;
8861 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8862 out << "\t";
8863 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8864 const unsigned int word = spirv[i + j];
8865 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8866 if (i + j + 1 < (int)spirv.size()) {
8867 out << ",";
8868 }
8869 }
8870 out << std::endl;
8871 }
Flavio15017db2017-02-15 14:29:33 -08008872 if (varName != nullptr) {
8873 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008874 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008875 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008876 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008877#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008878}
8879
John Kessenich140f3df2015-06-26 16:58:36 -06008880//
8881// Set up the glslang traversal
8882//
John Kessenich4e11b612018-08-30 16:56:59 -06008883void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008884{
Lei Zhang17535f72016-05-04 15:55:59 -04008885 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008886 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008887}
8888
John Kessenich4e11b612018-08-30 16:56:59 -06008889void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008890 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008891{
John Kessenich140f3df2015-06-26 16:58:36 -06008892 TIntermNode* root = intermediate.getTreeRoot();
8893
8894 if (root == 0)
8895 return;
8896
John Kessenich4e11b612018-08-30 16:56:59 -06008897 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008898 if (options == nullptr)
8899 options = &defaultOptions;
8900
John Kessenich4e11b612018-08-30 16:56:59 -06008901 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008902
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008903 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008904 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008905 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008906 it.dumpSpv(spirv);
8907
GregFfb03a552018-03-29 11:49:14 -06008908#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008909 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8910 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008911 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008912 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8913 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008914 prelegalization = false;
8915 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008916 else if (options->stripDebugInfo) {
8917 // Strip debug info even if optimization is disabled.
8918 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8919 }
John Kessenich717c80a2018-08-23 15:17:10 -06008920
John Kessenich4e11b612018-08-30 16:56:59 -06008921 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008922 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008923
John Kessenich717c80a2018-08-23 15:17:10 -06008924 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008925 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008926
GregFcd1f1692017-09-21 18:40:22 -06008927#endif
8928
John Kessenich4e11b612018-08-30 16:56:59 -06008929 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008930}
8931
8932}; // end namespace glslang