blob: 4a489dfe8f89f974cf71ed7f6358176ed71a8440 [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:
Daniel Koch4d41da32020-11-24 23:06:16 -05003781 switch (glslangIntermediate->getStage()) {
3782 case EShLangRayGen:
3783 case EShLangIntersect:
3784 case EShLangAnyHit:
3785 case EShLangClosestHit:
3786 case EShLangMiss:
3787 case EShLangCallable:
3788 // these all should have the RayTracingNV/KHR capability already
3789 break;
3790 default:
3791 {
3792 auto& extensions = glslangIntermediate->getRequestedExtensions();
3793 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3794 builder.addExtension(spv::E_SPV_KHR_ray_query);
3795 builder.addCapability(spv::CapabilityRayQueryKHR);
3796 }
3797 }
3798 break;
3799 }
Daniel Kochdb32b242020-03-17 20:42:47 -04003800 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003801 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003802 case glslang::EbtRayQuery:
Daniel Koch4d41da32020-11-24 23:06:16 -05003803 {
3804 auto& extensions = glslangIntermediate->getRequestedExtensions();
3805 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3806 builder.addExtension(spv::E_SPV_KHR_ray_query);
3807 builder.addCapability(spv::CapabilityRayQueryKHR);
3808 }
3809 spvType = builder.makeRayQueryType();
3810 }
Torosdagli06c2eee2020-03-19 11:09:57 -04003811 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003812 case glslang::EbtReference:
3813 {
3814 // Make the forward pointer, then recurse to convert the structure type, then
3815 // patch up the forward pointer with a real pointer type.
3816 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3817 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3818 forwardPointers[type.getReferentType()] = forwardId;
3819 }
3820 spvType = forwardPointers[type.getReferentType()];
3821 if (!forwardReferenceOnly) {
3822 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3823 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3824 forwardPointers[type.getReferentType()],
3825 referentType);
3826 }
3827 }
3828 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003829#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003830 case glslang::EbtSampler:
3831 {
3832 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003833 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003834 spvType = builder.makeSamplerType();
3835 } else {
3836 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003837 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3838 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3839 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3840 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003841 // already has both image and sampler, make the combined type
3842 spvType = builder.makeSampledImageType(spvType);
3843 }
John Kessenich55e7d112015-11-15 21:33:39 -07003844 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003845 }
John Kessenich140f3df2015-06-26 16:58:36 -06003846 break;
3847 case glslang::EbtStruct:
3848 case glslang::EbtBlock:
3849 {
3850 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003851 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003852
3853 // Try to share structs for different layouts, but not yet for other
3854 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003855 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003856 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003857 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003858 break;
3859
3860 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003861 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003862 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003863 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003864 }
3865 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003866 case glslang::EbtString:
3867 // no type used for OpString
3868 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003869 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003870 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003871 break;
3872 }
3873
3874 if (type.isMatrix())
3875 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3876 else {
3877 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3878 if (type.getVectorSize() > 1)
3879 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3880 }
3881
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003882 if (type.isCoopMat()) {
3883 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3884 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3885 if (type.getBasicType() == glslang::EbtFloat16)
3886 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003887 if (type.getBasicType() == glslang::EbtUint8 ||
3888 type.getBasicType() == glslang::EbtInt8) {
3889 builder.addCapability(spv::CapabilityInt8);
3890 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003891
3892 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3893 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3894 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3895
3896 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3897 }
3898
John Kessenich140f3df2015-06-26 16:58:36 -06003899 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003900 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3901
John Kessenichc9a80832015-09-12 12:17:44 -06003902 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003903 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003904 // We need to decorate array strides for types needing explicit layout, except blocks.
3905 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003906 // Use a dummy glslang type for querying internal strides of
3907 // arrays of arrays, but using just a one-dimensional array.
3908 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003909 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3910 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003911
3912 // Will compute the higher-order strides here, rather than making a whole
3913 // pile of types and doing repetitive recursion on their contents.
3914 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3915 }
John Kessenichf8842e52016-01-04 19:22:56 -07003916
3917 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003918 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003919 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003920 if (stride > 0)
3921 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003922 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003923 }
3924 } else {
3925 // single-dimensional array, and don't yet have stride
3926
John Kessenichf8842e52016-01-04 19:22:56 -07003927 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003928 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3929 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003930 }
John Kessenich31ed4832015-09-09 17:51:38 -06003931
John Kessenichead86222018-03-28 18:01:20 -06003932 // Do the outer dimension, which might not be known for a runtime-sized array.
3933 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3934 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003935 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003936 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003937#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003938 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003939 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003940 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3941 }
John Kessenichb9197c82019-08-11 07:41:45 -06003942#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003943 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003944 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003945 if (stride > 0)
3946 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003947 }
3948
3949 return spvType;
3950}
3951
John Kessenich0e737842017-03-24 18:38:16 -06003952// TODO: this functionality should exist at a higher level, in creating the AST
3953//
3954// Identify interface members that don't have their required extension turned on.
3955//
3956bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3957{
John Kessenicha28f7a72019-08-06 07:00:58 -06003958#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003959 auto& extensions = glslangIntermediate->getRequestedExtensions();
3960
Rex Xubcf291a2017-03-29 23:01:36 +08003961 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3962 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3963 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003964 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3965 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3966 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003967
3968 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3969 if (member.getFieldName() == "gl_ViewportMask" &&
3970 extensions.find("GL_NV_viewport_array2") == extensions.end())
3971 return true;
3972 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3973 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3974 return true;
3975 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3976 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3977 return true;
3978 }
3979#endif
John Kessenich0e737842017-03-24 18:38:16 -06003980
3981 return false;
3982};
3983
John Kessenich6090df02016-06-30 21:18:02 -06003984// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3985// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3986// Mutually recursive with convertGlslangToSpvType().
3987spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3988 const glslang::TTypeList* glslangMembers,
3989 glslang::TLayoutPacking explicitLayout,
3990 const glslang::TQualifier& qualifier)
3991{
3992 // Create a vector of struct types for SPIR-V to consume
3993 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003994 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3995 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003996 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003997 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3998 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3999 if (glslangMember.hiddenMember()) {
4000 ++memberDelta;
4001 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08004002 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06004003 } else {
John Kessenich0e737842017-03-24 18:38:16 -06004004 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004005 if (filterMember(glslangMember)) {
4006 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08004007 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06004008 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004009 }
Roy05a5b532020-01-03 16:21:34 +08004010 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06004011 }
John Kessenich6090df02016-06-30 21:18:02 -06004012 // modify just this child's view of the qualifier
4013 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4014 InheritQualifiers(memberQualifier, qualifier);
4015
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004016 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06004017 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004018 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06004019
4020 // recurse
John Kessenichead86222018-03-28 18:01:20 -06004021 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
4022 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004023
4024 // Make forward pointers for any pointer members, and create a list of members to
4025 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06004026 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004027 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
4028 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
4029 }
4030 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004031 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4032 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004033 } else {
4034 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004035 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4036 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004037 }
John Kessenich6090df02016-06-30 21:18:02 -06004038 }
4039 }
4040
4041 // Make the SPIR-V type
4042 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06004043 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06004044 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
4045
4046 // Decorate it
4047 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
4048
John Kessenichd72f4882019-01-16 14:55:37 +07004049 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004050 auto it = deferredForwardPointers[i];
4051 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
4052 }
4053
John Kessenich6090df02016-06-30 21:18:02 -06004054 return spvType;
4055}
4056
4057void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
4058 const glslang::TTypeList* glslangMembers,
4059 glslang::TLayoutPacking explicitLayout,
4060 const glslang::TQualifier& qualifier,
4061 spv::Id spvType)
4062{
4063 // Name and decorate the non-hidden members
4064 int offset = -1;
4065 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08004066 bool memberLocationInvalid = type.isArrayOfArrays() ||
4067 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06004068 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4069 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4070 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06004071 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08004072 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06004073 if (filterMember(glslangMember))
4074 continue;
4075 }
John Kessenich6090df02016-06-30 21:18:02 -06004076
4077 // modify just this child's view of the qualifier
4078 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4079 InheritQualifiers(memberQualifier, qualifier);
4080
4081 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07004082 if (member < 0)
4083 continue;
4084
4085 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
4086 builder.addMemberDecoration(spvType, member,
4087 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
4088 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
4089 // Add interpolation and auxiliary storage decorations only to
4090 // top-level members of Input and Output storage classes
4091 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4092 type.getQualifier().storage == glslang::EvqVaryingOut) {
4093 if (type.getBasicType() == glslang::EbtBlock ||
4094 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4095 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4096 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004097#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004098 addMeshNVDecoration(spvType, member, memberQualifier);
4099#endif
John Kessenich6090df02016-06-30 21:18:02 -06004100 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004101 }
4102 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004103
John Kessenichb9197c82019-08-11 07:41:45 -06004104#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004105 if (type.getBasicType() == glslang::EbtBlock &&
4106 qualifier.storage == glslang::EvqBuffer) {
4107 // Add memory decorations only to top-level members of shader storage block
4108 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004109 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004110 for (unsigned int i = 0; i < memory.size(); ++i)
4111 builder.addMemberDecoration(spvType, member, memory[i]);
4112 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004113
John Kessenichb9197c82019-08-11 07:41:45 -06004114#endif
John Kessenich6090df02016-06-30 21:18:02 -06004115
John Kessenich5d610ee2018-03-07 18:05:55 -07004116 // Location assignment was already completed correctly by the front end,
4117 // just track whether a member needs to be decorated.
4118 // Ignore member locations if the container is an array, as that's
4119 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004120 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004121 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004122
John Kessenich5d610ee2018-03-07 18:05:55 -07004123 if (qualifier.hasLocation()) // track for upcoming inheritance
4124 locationOffset += glslangIntermediate->computeTypeLocationSize(
4125 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004126
John Kessenich5d610ee2018-03-07 18:05:55 -07004127 // component, XFB, others
4128 if (glslangMember.getQualifier().hasComponent())
4129 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4130 glslangMember.getQualifier().layoutComponent);
4131 if (glslangMember.getQualifier().hasXfbOffset())
4132 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4133 glslangMember.getQualifier().layoutXfbOffset);
4134 else if (explicitLayout != glslang::ElpNone) {
4135 // figure out what to do with offset, which is accumulating
4136 int nextOffset;
4137 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4138 if (offset >= 0)
4139 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4140 offset = nextOffset;
4141 }
John Kessenich6090df02016-06-30 21:18:02 -06004142
John Kessenich5d610ee2018-03-07 18:05:55 -07004143 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4144 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4145 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004146
John Kessenich5d610ee2018-03-07 18:05:55 -07004147 // built-in variable decorations
4148 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4149 if (builtIn != spv::BuiltInMax)
4150 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004151
John Kessenichb9197c82019-08-11 07:41:45 -06004152#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004153 // nonuniform
4154 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4155
John Kessenichead86222018-03-28 18:01:20 -06004156 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4157 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4158 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4159 memberQualifier.semanticName);
4160 }
4161
John Kessenich5d610ee2018-03-07 18:05:55 -07004162 if (builtIn == spv::BuiltInLayer) {
4163 // SPV_NV_viewport_array2 extension
4164 if (glslangMember.getQualifier().layoutViewportRelative){
4165 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4166 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4167 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004168 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004169 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4170 builder.addMemberDecoration(spvType, member,
4171 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4172 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4173 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4174 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004175 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004176 }
4177 if (glslangMember.getQualifier().layoutPassthrough) {
4178 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4179 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4180 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4181 }
chaoc771d89f2017-01-13 01:10:53 -08004182#endif
John Kessenich6090df02016-06-30 21:18:02 -06004183 }
4184
4185 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004186 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4187 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004188}
4189
John Kessenich6c292d32016-02-15 20:58:50 -07004190// Turn the expression forming the array size into an id.
4191// This is not quite trivial, because of specialization constants.
4192// Sometimes, a raw constant is turned into an Id, and sometimes
4193// a specialization constant expression is.
4194spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4195{
4196 // First, see if this is sized with a node, meaning a specialization constant:
4197 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4198 if (specNode != nullptr) {
4199 builder.clearAccessChain();
4200 specNode->traverse(this);
4201 return accessChainLoad(specNode->getAsTyped()->getType());
4202 }
qining25262b32016-05-06 17:25:16 -04004203
John Kessenich6c292d32016-02-15 20:58:50 -07004204 // Otherwise, need a compile-time (front end) size, get it:
4205 int size = arraySizes.getDimSize(dim);
4206 assert(size > 0);
4207 return builder.makeUintConstant(size);
4208}
4209
John Kessenich103bef92016-02-08 21:38:15 -07004210// Wrap the builder's accessChainLoad to:
4211// - localize handling of RelaxedPrecision
4212// - use the SPIR-V inferred type instead of another conversion of the glslang type
4213// (avoids unnecessary work and possible type punning for structures)
4214// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004215spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4216{
John Kessenich103bef92016-02-08 21:38:15 -07004217 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004218
4219 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4220 coherentFlags |= TranslateCoherent(type);
4221
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004222 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004223 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004224
John Kessenich5611c6d2018-04-05 11:25:02 -06004225 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
greg-lunarg639f5462020-11-12 11:10:07 -07004226 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004227 TranslateNonUniformDecoration(type.getQualifier()),
4228 nominalTypeId,
4229 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4230 TranslateMemoryScope(coherentFlags),
4231 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004232
4233 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004234 if (type.getBasicType() == glslang::EbtBool) {
4235 if (builder.isScalarType(nominalTypeId)) {
4236 // Conversion for bool
4237 spv::Id boolType = builder.makeBoolType();
4238 if (nominalTypeId != boolType)
4239 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4240 } else if (builder.isVectorType(nominalTypeId)) {
4241 // Conversion for bvec
4242 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4243 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4244 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004245 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4246 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004247 }
4248 }
John Kessenich103bef92016-02-08 21:38:15 -07004249
4250 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004251}
4252
Rex Xu27253232016-02-23 17:51:09 +08004253// Wrap the builder's accessChainStore to:
4254// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004255//
4256// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004257void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4258{
4259 // Need to convert to abstract types when necessary
4260 if (type.getBasicType() == glslang::EbtBool) {
4261 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4262
4263 if (builder.isScalarType(nominalTypeId)) {
4264 // Conversion for bool
4265 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004266 if (nominalTypeId != boolType) {
4267 // keep these outside arguments, for determinant order-of-evaluation
4268 spv::Id one = builder.makeUintConstant(1);
4269 spv::Id zero = builder.makeUintConstant(0);
4270 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4271 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004272 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004273 } else if (builder.isVectorType(nominalTypeId)) {
4274 // Conversion for bvec
4275 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4276 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004277 if (nominalTypeId != bvecType) {
4278 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004279 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4280 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4281 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004282 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004283 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4284 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004285 }
4286 }
4287
Jeff Bolz36831c92018-09-05 10:11:41 -05004288 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4289 coherentFlags |= TranslateCoherent(type);
4290
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004291 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004292 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004293
greg-lunarg639f5462020-11-12 11:10:07 -07004294 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004295 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4296 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004297 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004298}
4299
John Kessenich4bf71552016-09-02 11:20:21 -06004300// For storing when types match at the glslang level, but not might match at the
4301// SPIR-V level.
4302//
4303// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004304// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004305// as in a member-decorated way.
4306//
4307// NOTE: This function can handle any store request; if it's not special it
4308// simplifies to a simple OpStore.
4309//
4310// Implicitly uses the existing builder.accessChain as the storage target.
4311void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4312{
John Kessenichb3e24e42016-09-11 12:33:43 -06004313 // we only do the complex path here if it's an aggregate
4314 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004315 accessChainStore(type, rValue);
4316 return;
4317 }
4318
John Kessenichb3e24e42016-09-11 12:33:43 -06004319 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004320 spv::Id rType = builder.getTypeId(rValue);
4321 spv::Id lValue = builder.accessChainGetLValue();
4322 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4323 if (lType == rType) {
4324 accessChainStore(type, rValue);
4325 return;
4326 }
4327
John Kessenichb3e24e42016-09-11 12:33:43 -06004328 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004329 // where the two types were the same type in GLSL. This requires member
4330 // by member copy, recursively.
4331
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004332 // SPIR-V 1.4 added an instruction to do help do this.
4333 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4334 // However, bool in uniform space is changed to int, so
4335 // OpCopyLogical does not work for that.
4336 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4337 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4338 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4339 if (lBool == rBool) {
4340 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4341 accessChainStore(type, logicalCopy);
4342 return;
4343 }
4344 }
4345
John Kessenichb3e24e42016-09-11 12:33:43 -06004346 // If an array, copy element by element.
4347 if (type.isArray()) {
4348 glslang::TType glslangElementType(type, 0);
4349 spv::Id elementRType = builder.getContainedTypeId(rType);
4350 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4351 // get the source member
4352 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004353
John Kessenichb3e24e42016-09-11 12:33:43 -06004354 // set up the target storage
4355 builder.clearAccessChain();
4356 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004357 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4358 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004359
John Kessenichb3e24e42016-09-11 12:33:43 -06004360 // store the member
4361 multiTypeStore(glslangElementType, elementRValue);
4362 }
4363 } else {
4364 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004365
John Kessenichb3e24e42016-09-11 12:33:43 -06004366 // loop over structure members
4367 const glslang::TTypeList& members = *type.getStruct();
4368 for (int m = 0; m < (int)members.size(); ++m) {
4369 const glslang::TType& glslangMemberType = *members[m].type;
4370
4371 // get the source member
4372 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4373 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4374
4375 // set up the target storage
4376 builder.clearAccessChain();
4377 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004378 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4379 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004380
4381 // store the member
4382 multiTypeStore(glslangMemberType, memberRValue);
4383 }
John Kessenich4bf71552016-09-02 11:20:21 -06004384 }
4385}
4386
John Kessenichf85e8062015-12-19 13:57:10 -07004387// Decide whether or not this type should be
4388// decorated with offsets and strides, and if so
4389// whether std140 or std430 rules should be applied.
4390glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004391{
John Kessenichf85e8062015-12-19 13:57:10 -07004392 // has to be a block
4393 if (type.getBasicType() != glslang::EbtBlock)
4394 return glslang::ElpNone;
4395
Chao Chen3c366992018-09-19 11:41:59 -07004396 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004397 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004398 type.getQualifier().storage != glslang::EvqBuffer &&
4399 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004400 return glslang::ElpNone;
4401
4402 // return the layout to use
4403 switch (type.getQualifier().layoutPacking) {
4404 case glslang::ElpStd140:
4405 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004406 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004407 return type.getQualifier().layoutPacking;
4408 default:
4409 return glslang::ElpNone;
4410 }
John Kessenich31ed4832015-09-09 17:51:38 -06004411}
4412
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004413// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004414int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4415 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004416{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004417 int size;
John Kessenich49987892015-12-29 17:11:44 -07004418 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004419 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4420 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004421
4422 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004423}
4424
John Kessenich49987892015-12-29 17:11:44 -07004425// 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 -07004426// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004427int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4428 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004429{
John Kessenich49987892015-12-29 17:11:44 -07004430 glslang::TType elementType;
4431 elementType.shallowCopy(matrixType);
4432 elementType.clearArraySizes();
4433
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004434 int size;
John Kessenich49987892015-12-29 17:11:44 -07004435 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004436 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4437 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004438
4439 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004440}
4441
John Kessenich5e4b1242015-08-06 22:53:06 -06004442// Given a member type of a struct, realign the current offset for it, and compute
4443// the next (not yet aligned) offset for the next member, which will get aligned
4444// on the next call.
4445// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4446// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4447// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004448void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4449 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004450{
4451 // this will get a positive value when deemed necessary
4452 nextOffset = -1;
4453
John Kessenich5e4b1242015-08-06 22:53:06 -06004454 // override anything in currentOffset with user-set offset
4455 if (memberType.getQualifier().hasOffset())
4456 currentOffset = memberType.getQualifier().layoutOffset;
4457
4458 // It could be that current linker usage in glslang updated all the layoutOffset,
4459 // in which case the following code does not matter. But, that's not quite right
4460 // once cross-compilation unit GLSL validation is done, as the original user
4461 // settings are needed in layoutOffset, and then the following will come into play.
4462
John Kessenichf85e8062015-12-19 13:57:10 -07004463 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004464 if (! memberType.getQualifier().hasOffset())
4465 currentOffset = -1;
4466
4467 return;
4468 }
4469
John Kessenichf85e8062015-12-19 13:57:10 -07004470 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004471 if (currentOffset < 0)
4472 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004473
John Kessenich5e4b1242015-08-06 22:53:06 -06004474 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4475 // but possibly not yet correctly aligned.
4476
4477 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004478 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004479 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4480 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004481
4482 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004483 // TODO: make this consistent in early phases of code:
4484 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4485 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4486 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004487 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004488 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004489 int dummySize;
4490 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4491 if (componentAlignment <= 4)
4492 memberAlignment = componentAlignment;
4493 }
4494
4495 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004496 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004497
4498 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004499 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4500 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004501 glslang::RoundToPow2(currentOffset, 16);
4502
John Kessenich5e4b1242015-08-06 22:53:06 -06004503 nextOffset = currentOffset + memberSize;
4504}
4505
David Netoa901ffe2016-06-08 14:11:40 +01004506void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004507{
David Netoa901ffe2016-06-08 14:11:40 +01004508 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4509 switch (glslangBuiltIn)
4510 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004511 case glslang::EbvPointSize:
4512#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004513 case glslang::EbvClipDistance:
4514 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004515 case glslang::EbvViewportMaskNV:
4516 case glslang::EbvSecondaryPositionNV:
4517 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004518 case glslang::EbvPositionPerViewNV:
4519 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004520 case glslang::EbvTaskCountNV:
4521 case glslang::EbvPrimitiveCountNV:
4522 case glslang::EbvPrimitiveIndicesNV:
4523 case glslang::EbvClipDistancePerViewNV:
4524 case glslang::EbvCullDistancePerViewNV:
4525 case glslang::EbvLayerPerViewNV:
4526 case glslang::EbvMeshViewCountNV:
4527 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004528#endif
David Netoa901ffe2016-06-08 14:11:40 +01004529 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4530 // Alternately, we could just call this for any glslang built-in, since the
4531 // capability already guards against duplicates.
4532 TranslateBuiltInDecoration(glslangBuiltIn, false);
4533 break;
4534 default:
4535 // Capabilities were already generated when the struct was declared.
4536 break;
4537 }
John Kessenichebb50532016-05-16 19:22:05 -06004538}
4539
John Kessenich6fccb3c2016-09-19 16:01:41 -06004540bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004541{
John Kessenicheee9d532016-09-19 18:09:30 -06004542 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004543}
4544
John Kessenichd41993d2017-09-10 15:21:05 -06004545// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004546// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4547// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004548bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004549{
John Kessenich6a14f782017-12-04 02:48:10 -07004550 assert(qualifier == glslang::EvqIn ||
4551 qualifier == glslang::EvqOut ||
4552 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004553 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004554 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004555 return qualifier != glslang::EvqConstReadOnly &&
4556 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004557}
4558
4559// Is parameter pass-by-original?
4560bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4561 bool implicitThisParam)
4562{
4563 if (implicitThisParam) // implicit this
4564 return true;
4565 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004566 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004567 return paramType.containsOpaque() || // sampler, etc.
4568 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4569}
4570
John Kessenich140f3df2015-06-26 16:58:36 -06004571// Make all the functions, skeletally, without actually visiting their bodies.
4572void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4573{
John Kessenich8985fc92020-03-03 10:25:07 -07004574 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4575 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004576 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4577 if (paramPrecision != spv::NoPrecision)
4578 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004579 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004580 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004581 // Original and non-writable params pass the pointer directly and
4582 // use restrict/aliased, others are stored to a pointer in Function
4583 // memory and use RestrictPointer/AliasedPointer.
4584 if (originalParam(type.getQualifier().storage, type, false) ||
4585 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004586 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4587 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004588 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004589 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4590 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004591 }
4592 }
John Kessenichfad62972017-07-18 02:35:46 -06004593 };
4594
John Kessenich140f3df2015-06-26 16:58:36 -06004595 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4596 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004597 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004598 continue;
4599
4600 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004601 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004602 //
qining25262b32016-05-06 17:25:16 -04004603 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004604 // function. What it is an address of varies:
4605 //
John Kessenich4bf71552016-09-02 11:20:21 -06004606 // - "in" parameters not marked as "const" can be written to without modifying the calling
4607 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004608 //
4609 // - "const in" parameters can just be the r-value, as no writes need occur.
4610 //
John Kessenich4bf71552016-09-02 11:20:21 -06004611 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4612 // 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 -06004613
4614 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004615 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004616 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4617
John Kessenich155d3512019-08-08 23:29:20 -06004618#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004619 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4620 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004621#else
4622 bool implicitThis = false;
4623#endif
John Kessenich37789792017-03-21 23:56:40 -06004624
John Kessenichfad62972017-07-18 02:35:46 -06004625 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004626 for (int p = 0; p < (int)parameters.size(); ++p) {
4627 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4628 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004629 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004630 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004631 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004632 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4633 else
John Kessenich4bf71552016-09-02 11:20:21 -06004634 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004635 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004636 paramTypes.push_back(typeId);
4637 }
4638
4639 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004640 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4641 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004642 glslFunction->getName().c_str(), paramTypes,
4643 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004644 if (implicitThis)
4645 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004646
4647 // Track function to emit/call later
4648 functionMap[glslFunction->getName().c_str()] = function;
4649
4650 // Set the parameter id's
4651 for (int p = 0; p < (int)parameters.size(); ++p) {
4652 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4653 // give a name too
4654 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004655
4656 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004657 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004658 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004659 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004660 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004661 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004662 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004663 }
4664 }
4665}
4666
4667// Process all the initializers, while skipping the functions and link objects
4668void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4669{
4670 builder.setBuildPoint(shaderEntry->getLastBlock());
4671 for (int i = 0; i < (int)initializers.size(); ++i) {
4672 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004673 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4674 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004675
4676 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004677 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004678 initializer->traverse(this);
4679 }
4680 }
4681}
Daniel Kochffccefd2020-11-23 15:41:27 -05004682// Walk over all linker objects to create a map for payload and callable data linker objects
4683// and their location to be used during codegen for OpTraceKHR and OpExecuteCallableKHR
4684// This is done here since it is possible that these linker objects are not be referenced in the AST
4685void TGlslangToSpvTraverser::collectRayTracingLinkerObjects()
4686{
4687 glslang::TIntermAggregate* linkerObjects = glslangIntermediate->findLinkerObjects();
4688 for (auto& objSeq : linkerObjects->getSequence()) {
4689 auto objNode = objSeq->getAsSymbolNode();
4690 if (objNode != nullptr) {
4691 if (objNode->getQualifier().hasLocation()) {
4692 unsigned int location = objNode->getQualifier().layoutLocation;
4693 auto st = objNode->getQualifier().storage;
4694 int set;
4695 switch (st)
4696 {
4697 case glslang::EvqPayload:
4698 case glslang::EvqPayloadIn:
4699 set = 0;
4700 break;
4701 case glslang::EvqCallableData:
4702 case glslang::EvqCallableDataIn:
4703 set = 1;
4704 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004705
Daniel Kochffccefd2020-11-23 15:41:27 -05004706 default:
4707 set = -1;
4708 }
4709 if (set != -1)
4710 locationToSymbol[set].insert(std::make_pair(location, objNode));
4711 }
4712 }
4713 }
4714}
John Kessenich140f3df2015-06-26 16:58:36 -06004715// Process all the functions, while skipping initializers.
4716void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4717{
4718 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4719 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004720 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004721 node->traverse(this);
4722 }
4723}
4724
4725void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4726{
qining25262b32016-05-06 17:25:16 -04004727 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004728 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004729 currentFunction = functionMap[node->getName().c_str()];
4730 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004731 builder.setBuildPoint(functionBlock);
4732}
4733
John Kessenich8985fc92020-03-03 10:25:07 -07004734void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4735 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004736{
Rex Xufc618912015-09-09 16:42:49 +08004737 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004738
4739 glslang::TSampler sampler = {};
4740 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004741#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004742 bool f16ShadowCompare = false;
4743#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004744 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004745 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4746 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004747#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004748 f16ShadowCompare = sampler.shadow &&
4749 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004750#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004751 }
4752
John Kessenich140f3df2015-06-26 16:58:36 -06004753 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4754 builder.clearAccessChain();
4755 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004756
John Kessenicha28f7a72019-08-06 07:00:58 -06004757#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004758 // Special case l-value operands
4759 bool lvalue = false;
4760 switch (node.getOp()) {
4761 case glslang::EOpImageAtomicAdd:
4762 case glslang::EOpImageAtomicMin:
4763 case glslang::EOpImageAtomicMax:
4764 case glslang::EOpImageAtomicAnd:
4765 case glslang::EOpImageAtomicOr:
4766 case glslang::EOpImageAtomicXor:
4767 case glslang::EOpImageAtomicExchange:
4768 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004769 case glslang::EOpImageAtomicLoad:
4770 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004771 if (i == 0)
4772 lvalue = true;
4773 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004774 case glslang::EOpSparseImageLoad:
4775 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4776 lvalue = true;
4777 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004778 case glslang::EOpSparseTexture:
4779 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4780 lvalue = true;
4781 break;
4782 case glslang::EOpSparseTextureClamp:
4783 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4784 lvalue = true;
4785 break;
4786 case glslang::EOpSparseTextureLod:
4787 case glslang::EOpSparseTextureOffset:
4788 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4789 lvalue = true;
4790 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004791 case glslang::EOpSparseTextureFetch:
4792 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4793 lvalue = true;
4794 break;
4795 case glslang::EOpSparseTextureFetchOffset:
4796 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4797 lvalue = true;
4798 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004799 case glslang::EOpSparseTextureLodOffset:
4800 case glslang::EOpSparseTextureGrad:
4801 case glslang::EOpSparseTextureOffsetClamp:
4802 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4803 lvalue = true;
4804 break;
4805 case glslang::EOpSparseTextureGradOffset:
4806 case glslang::EOpSparseTextureGradClamp:
4807 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4808 lvalue = true;
4809 break;
4810 case glslang::EOpSparseTextureGradOffsetClamp:
4811 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4812 lvalue = true;
4813 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004814 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004815 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4816 lvalue = true;
4817 break;
4818 case glslang::EOpSparseTextureGatherOffset:
4819 case glslang::EOpSparseTextureGatherOffsets:
4820 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4821 lvalue = true;
4822 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004823 case glslang::EOpSparseTextureGatherLod:
4824 if (i == 3)
4825 lvalue = true;
4826 break;
4827 case glslang::EOpSparseTextureGatherLodOffset:
4828 case glslang::EOpSparseTextureGatherLodOffsets:
4829 if (i == 4)
4830 lvalue = true;
4831 break;
Rex Xu129799a2017-07-05 17:23:28 +08004832 case glslang::EOpSparseImageLoadLod:
4833 if (i == 3)
4834 lvalue = true;
4835 break;
Chao Chen3a137962018-09-19 11:41:27 -07004836 case glslang::EOpImageSampleFootprintNV:
4837 if (i == 4)
4838 lvalue = true;
4839 break;
4840 case glslang::EOpImageSampleFootprintClampNV:
4841 case glslang::EOpImageSampleFootprintLodNV:
4842 if (i == 5)
4843 lvalue = true;
4844 break;
4845 case glslang::EOpImageSampleFootprintGradNV:
4846 if (i == 6)
4847 lvalue = true;
4848 break;
4849 case glslang::EOpImageSampleFootprintGradClampNV:
4850 if (i == 7)
4851 lvalue = true;
4852 break;
Rex Xufc618912015-09-09 16:42:49 +08004853 default:
4854 break;
4855 }
4856
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004857 if (lvalue) {
greg-lunarg639f5462020-11-12 11:10:07 -07004858 spv::Id lvalue_id = builder.accessChainGetLValue();
4859 arguments.push_back(lvalue_id);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004860 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
greg-lunarg639f5462020-11-12 11:10:07 -07004861 builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004862 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4863 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004864#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004865 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004866 }
4867}
4868
John Kessenichfc51d282015-08-19 13:34:18 -06004869void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004870{
John Kessenichfc51d282015-08-19 13:34:18 -06004871 builder.clearAccessChain();
4872 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004873 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004874}
John Kessenich140f3df2015-06-26 16:58:36 -06004875
John Kessenichfc51d282015-08-19 13:34:18 -06004876spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4877{
John Kesseniche485c7a2017-05-31 18:50:53 -06004878 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004879 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004880
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004881 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004882
John Kessenichfc51d282015-08-19 13:34:18 -06004883 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004884
John Kessenichf43c7392019-03-31 10:51:57 -06004885 const glslang::TType &imageType = node->getAsAggregate()
4886 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4887 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004888 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004889#ifdef GLSLANG_WEB
4890 const bool f16ShadowCompare = false;
4891#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004892 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004893 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4894 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004895#endif
4896
John Kessenichf43c7392019-03-31 10:51:57 -06004897 const auto signExtensionMask = [&]() {
4898 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4899 if (sampler.type == glslang::EbtUint)
4900 return spv::ImageOperandsZeroExtendMask;
4901 else if (sampler.type == glslang::EbtInt)
4902 return spv::ImageOperandsSignExtendMask;
4903 }
4904 return spv::ImageOperandsMaskNone;
4905 };
4906
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004907 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4908
John Kessenichfc51d282015-08-19 13:34:18 -06004909 std::vector<spv::Id> arguments;
4910 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004911 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004912 else
4913 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004914 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004915
4916 spv::Builder::TextureParameters params = { };
4917 params.sampler = arguments[0];
4918
Rex Xu04db3f52015-09-16 11:44:02 +08004919 glslang::TCrackedTextureOp cracked;
4920 node->crackTexture(sampler, cracked);
4921
amhagan05506bb2017-06-13 16:53:02 -04004922 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004923
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004924 if (builder.isSampledImage(params.sampler) &&
4925 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4926 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4927 if (imageType.getQualifier().isNonUniform()) {
4928 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4929 }
4930 }
John Kessenichfc51d282015-08-19 13:34:18 -06004931 // Check for queries
4932 if (cracked.query) {
4933 switch (node->getOp()) {
4934 case glslang::EOpImageQuerySize:
4935 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004936 if (arguments.size() > 1) {
4937 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004938 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004939 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004940 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004941#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004942 case glslang::EOpImageQuerySamples:
4943 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004944 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004945 case glslang::EOpTextureQueryLod:
4946 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004947 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004948 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004949 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004950 case glslang::EOpSparseTexelsResident:
4951 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004952#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004953 default:
4954 assert(0);
4955 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004956 }
John Kessenich140f3df2015-06-26 16:58:36 -06004957 }
4958
LoopDawg4425f242018-02-18 11:40:01 -07004959 int components = node->getType().getVectorSize();
4960
4961 if (node->getOp() == glslang::EOpTextureFetch) {
4962 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4963 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4964 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4965 // here around e.g. which ones return scalars or other types.
4966 components = 4;
4967 }
4968
4969 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4970
4971 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4972
Rex Xufc618912015-09-09 16:42:49 +08004973 // Check for image functions other than queries
4974 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004975 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004976 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004977 spv::IdImmediate image = { true, *(opIt++) };
4978 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004979
4980 // Handle subpass operations
4981 // TODO: GLSL should change to have the "MS" only on the type rather than the
4982 // built-in function.
4983 if (cracked.subpass) {
4984 // add on the (0,0) coordinate
4985 spv::Id zero = builder.makeIntConstant(0);
4986 std::vector<spv::Id> comps;
4987 comps.push_back(zero);
4988 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004989 spv::IdImmediate coord = { true,
4990 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4991 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004992 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4993 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004994 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004995 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4996 }
4997 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004998 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004999 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005000 spv::IdImmediate imageOperand = { true, *(opIt++) };
5001 operands.push_back(imageOperand);
5002 }
John Kessenich6c292d32016-02-15 20:58:50 -07005003 }
John Kessenichfe4e5722017-10-19 02:07:30 -06005004 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
5005 builder.setPrecision(result, precision);
5006 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07005007 }
5008
John Kessenich149afc32018-08-14 13:31:43 -06005009 spv::IdImmediate coord = { true, *(opIt++) };
5010 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08005011 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005012 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005013 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005014 mask = mask | spv::ImageOperandsSampleMask;
5015 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005016 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005017 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5018 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05005019 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07005020 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005021 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5022 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005023 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005024 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005025 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5026 operands.push_back(imageOperands);
5027 }
5028 if (mask & spv::ImageOperandsSampleMask) {
5029 spv::IdImmediate imageOperand = { true, *opIt++ };
5030 operands.push_back(imageOperand);
5031 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005032 if (mask & spv::ImageOperandsLodMask) {
5033 spv::IdImmediate imageOperand = { true, *opIt++ };
5034 operands.push_back(imageOperand);
5035 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005036 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005037 spv::IdImmediate imageOperand = { true,
5038 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005039 operands.push_back(imageOperand);
5040 }
5041
John Kessenich149afc32018-08-14 13:31:43 -06005042 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005043 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06005044
John Kessenich149afc32018-08-14 13:31:43 -06005045 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07005046 builder.setPrecision(result[0], precision);
5047
5048 // If needed, add a conversion constructor to the proper size.
5049 if (components != node->getType().getVectorSize())
5050 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5051
5052 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08005053 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08005054
Jeff Bolz36831c92018-09-05 10:11:41 -05005055 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005056 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06005057 spv::IdImmediate texel = { true, *(opIt + 1) };
5058 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06005059 } else {
5060 spv::IdImmediate texel = { true, *opIt };
5061 operands.push_back(texel);
5062 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005063
5064 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005065 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005066 mask = mask | spv::ImageOperandsSampleMask;
5067 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005068 if (cracked.lod) {
5069 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5070 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5071 mask = mask | spv::ImageOperandsLodMask;
5072 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005073 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5074 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005075 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005076 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005077 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5078 operands.push_back(imageOperands);
5079 }
5080 if (mask & spv::ImageOperandsSampleMask) {
5081 spv::IdImmediate imageOperand = { true, *opIt++ };
5082 operands.push_back(imageOperand);
5083 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005084 if (mask & spv::ImageOperandsLodMask) {
5085 spv::IdImmediate imageOperand = { true, *opIt++ };
5086 operands.push_back(imageOperand);
5087 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005088 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005089 spv::IdImmediate imageOperand = { true,
5090 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005091 operands.push_back(imageOperand);
5092 }
5093
John Kessenich56bab042015-09-16 10:54:31 -06005094 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06005095 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005096 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06005097 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06005098 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
5099 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08005100 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06005101 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08005102 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
5103
Jeff Bolz36831c92018-09-05 10:11:41 -05005104 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005105 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005106 mask = mask | spv::ImageOperandsSampleMask;
5107 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005108 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005109 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5110 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5111
Jeff Bolz36831c92018-09-05 10:11:41 -05005112 mask = mask | spv::ImageOperandsLodMask;
5113 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005114 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5115 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005116 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005117 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005118 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06005119 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05005120 }
5121 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06005122 spv::IdImmediate imageOperand = { true, *opIt++ };
5123 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05005124 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005125 if (mask & spv::ImageOperandsLodMask) {
5126 spv::IdImmediate imageOperand = { true, *opIt++ };
5127 operands.push_back(imageOperand);
5128 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005129 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005130 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5131 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005132 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005133 }
5134
5135 // Create the return type that was a special structure
5136 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005137 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005138 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5139 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5140
5141 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5142
5143 // Decode the return type
5144 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5145 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005146 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005147 // Process image atomic operations
5148
5149 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5150 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005151 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005152 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005153 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005154
Jeff Bolz36831c92018-09-05 10:11:41 -05005155 spv::Id resultTypeId;
5156 // imageAtomicStore has a void return type so base the pointer type on
5157 // the type of the value operand.
5158 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005159 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005160 } else {
5161 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5162 }
John Kessenich56bab042015-09-16 10:54:31 -06005163 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005164 if (imageType.getQualifier().nonUniform) {
5165 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5166 }
Rex Xufc618912015-09-09 16:42:49 +08005167
5168 std::vector<spv::Id> operands;
5169 operands.push_back(pointer);
5170 for (; opIt != arguments.end(); ++opIt)
5171 operands.push_back(*opIt);
5172
John Kessenich8985fc92020-03-03 10:25:07 -07005173 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5174 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005175 }
5176 }
5177
John Kessenicha28f7a72019-08-06 07:00:58 -06005178#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005179 // Check for fragment mask functions other than queries
5180 if (cracked.fragMask) {
5181 assert(sampler.ms);
5182
5183 auto opIt = arguments.begin();
5184 std::vector<spv::Id> operands;
5185
amhagan05506bb2017-06-13 16:53:02 -04005186 operands.push_back(params.sampler);
5187 ++opIt;
5188
5189 if (sampler.isSubpass()) {
5190 // add on the (0,0) coordinate
5191 spv::Id zero = builder.makeIntConstant(0);
5192 std::vector<spv::Id> comps;
5193 comps.push_back(zero);
5194 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005195 operands.push_back(builder.makeCompositeConstant(
5196 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005197 }
5198
5199 for (; opIt != arguments.end(); ++opIt)
5200 operands.push_back(*opIt);
5201
5202 spv::Op fragMaskOp = spv::OpNop;
5203 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5204 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5205 else if (node->getOp() == glslang::EOpFragmentFetch)
5206 fragMaskOp = spv::OpFragmentFetchAMD;
5207
5208 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5209 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5210 return builder.createOp(fragMaskOp, resultType(), operands);
5211 }
5212#endif
5213
Rex Xufc618912015-09-09 16:42:49 +08005214 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005215 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005216 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005217 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005218
John Kessenichfc51d282015-08-19 13:34:18 -06005219 // check for bias argument
5220 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005221 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005222 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005223 if (cracked.gather)
5224 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005225
5226 if (f16ShadowCompare)
5227 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005228 if (cracked.offset)
5229 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005230 else if (cracked.offsets)
5231 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005232 if (cracked.grad)
5233 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005234 if (cracked.lodClamp)
5235 ++nonBiasArgCount;
5236 if (sparse)
5237 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005238 if (imageFootprint)
5239 //Following three extra arguments
5240 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5241 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005242 if ((int)arguments.size() > nonBiasArgCount)
5243 bias = true;
5244 }
5245
John Kessenicha28f7a72019-08-06 07:00:58 -06005246#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005247 if (cracked.gather) {
5248 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5249 if (bias || cracked.lod ||
5250 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5251 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005252 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005253 }
5254 }
5255#endif
5256
John Kessenichfc51d282015-08-19 13:34:18 -06005257 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005258
John Kessenichfc51d282015-08-19 13:34:18 -06005259 params.coords = arguments[1];
5260 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005261 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005262
5263 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005264 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005265 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005266 ++extraArgs;
5267 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005268 params.Dref = arguments[2];
5269 ++extraArgs;
5270 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005271 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005272 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005273 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005274 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005275 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005276 dRefComp = builder.getNumComponents(params.coords) - 1;
5277 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005278 params.Dref = builder.createCompositeExtract(params.coords,
5279 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005280 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005281
5282 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005283 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005284 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005285 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005286 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5287 !(glslangIntermediate->getStage() == EShLangCompute &&
5288 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005289 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5290 noImplicitLod = true;
5291 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005292
5293 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005294 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005295 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005296 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005297 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005298
5299 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005300 if (cracked.grad) {
5301 params.gradX = arguments[2 + extraArgs];
5302 params.gradY = arguments[3 + extraArgs];
5303 extraArgs += 2;
5304 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005305
5306 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005307 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005308 params.offset = arguments[2 + extraArgs];
5309 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005310 } else if (cracked.offsets) {
5311 params.offsets = arguments[2 + extraArgs];
5312 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005313 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005314
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005315#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005316 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005317 if (cracked.lodClamp) {
5318 params.lodClamp = arguments[2 + extraArgs];
5319 ++extraArgs;
5320 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005321 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005322 if (sparse) {
5323 params.texelOut = arguments[2 + extraArgs];
5324 ++extraArgs;
5325 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005326 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005327 if (cracked.gather && ! sampler.shadow) {
5328 // default component is 0, if missing, otherwise an argument
5329 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005330 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005331 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005332 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005333 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005334 }
Chao Chen3a137962018-09-19 11:41:27 -07005335 spv::Id resultStruct = spv::NoResult;
5336 if (imageFootprint) {
5337 //Following three extra arguments
5338 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5339 params.granularity = arguments[2 + extraArgs];
5340 params.coarse = arguments[3 + extraArgs];
5341 resultStruct = arguments[4 + extraArgs];
5342 extraArgs += 3;
5343 }
5344#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005345 // bias
5346 if (bias) {
5347 params.bias = arguments[2 + extraArgs];
5348 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005349 }
John Kessenichfc51d282015-08-19 13:34:18 -06005350
John Kessenicha28f7a72019-08-06 07:00:58 -06005351#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005352 if (imageFootprint) {
5353 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5354 builder.addCapability(spv::CapabilityImageFootprintNV);
5355
5356
5357 //resultStructType(OpenGL type) contains 5 elements:
5358 //struct gl_TextureFootprint2DNV {
5359 // uvec2 anchor;
5360 // uvec2 offset;
5361 // uvec2 mask;
5362 // uint lod;
5363 // uint granularity;
5364 //};
5365 //or
5366 //struct gl_TextureFootprint3DNV {
5367 // uvec3 anchor;
5368 // uvec3 offset;
5369 // uvec2 mask;
5370 // uint lod;
5371 // uint granularity;
5372 //};
5373 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5374 assert(builder.isStructType(resultStructType));
5375
5376 //resType (SPIR-V type) contains 6 elements:
5377 //Member 0 must be a Boolean type scalar(LOD),
5378 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5379 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5380 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5381 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5382 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5383 std::vector<spv::Id> members;
5384 members.push_back(resultType());
5385 for (int i = 0; i < 5; i++) {
5386 members.push_back(builder.getContainedTypeId(resultStructType, i));
5387 }
5388 spv::Id resType = builder.makeStructType(members, "ResType");
5389
5390 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005391 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5392 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005393
5394 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5395 for (int i = 0; i < 5; i++) {
5396 builder.clearAccessChain();
5397 builder.setAccessChainLValue(resultStruct);
5398
5399 //Accessing to a struct we created, no coherent flag is set
5400 spv::Builder::AccessChain::CoherentFlags flags;
5401 flags.clear();
5402
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005403 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005404 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005405 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005406 }
5407 return builder.createCompositeExtract(res, resultType(), 0);
5408 }
5409#endif
5410
John Kessenich65336482016-06-16 14:06:26 -06005411 // projective component (might not to move)
5412 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5413 // are divided by the last component of P."
5414 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5415 // unused components will appear after all used components."
5416 if (cracked.proj) {
5417 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5418 int projTargetComp;
5419 switch (sampler.dim) {
5420 case glslang::Esd1D: projTargetComp = 1; break;
5421 case glslang::Esd2D: projTargetComp = 2; break;
5422 case glslang::EsdRect: projTargetComp = 2; break;
5423 default: projTargetComp = projSourceComp; break;
5424 }
5425 // copy the projective coordinate if we have to
5426 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005427 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005428 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005429 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005430 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005431 }
5432 }
5433
John Kessenichf8d1d742019-10-21 06:55:11 -06005434#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005435 // nonprivate
5436 if (imageType.getQualifier().nonprivate) {
5437 params.nonprivate = true;
5438 }
5439
5440 // volatile
5441 if (imageType.getQualifier().volatil) {
5442 params.volatil = true;
5443 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005444#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005445
St0fFa1184dd2018-04-09 21:08:14 +02005446 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005447 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5448 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005449 );
LoopDawg4425f242018-02-18 11:40:01 -07005450
5451 if (components != node->getType().getVectorSize())
5452 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5453
5454 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005455}
5456
5457spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5458{
5459 // Grab the function's pointer from the previously created function
5460 spv::Function* function = functionMap[node->getName().c_str()];
5461 if (! function)
5462 return 0;
5463
5464 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5465 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5466
5467 // See comments in makeFunctions() for details about the semantics for parameter passing.
5468 //
5469 // These imply we need a four step process:
5470 // 1. Evaluate the arguments
5471 // 2. Allocate and make copies of in, out, and inout arguments
5472 // 3. Make the call
5473 // 4. Copy back the results
5474
John Kessenichd3ed90b2018-05-04 11:43:03 -06005475 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005476 std::vector<spv::Builder::AccessChain> lValues;
5477 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005478 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005480 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005481 // build l-value
5482 builder.clearAccessChain();
5483 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005484 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005485 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005486 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005487 // save l-value
5488 lValues.push_back(builder.getAccessChain());
5489 } else {
5490 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005491 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005492 }
5493 }
5494
5495 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5496 // copy the original into that space.
5497 //
5498 // Also, build up the list of actual arguments to pass in for the call
5499 int lValueCount = 0;
5500 int rValueCount = 0;
5501 std::vector<spv::Id> spvArgs;
5502 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5503 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005504 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005505 builder.setAccessChain(lValues[lValueCount]);
5506 arg = builder.accessChainGetLValue();
5507 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005508 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005509 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005510 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005511 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005512 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5513 // need to copy the input into output space
5514 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005515 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005516 builder.clearAccessChain();
5517 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005518 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005519 }
5520 ++lValueCount;
5521 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005522 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005523 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005524 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005525 {
John Kessenich435dd802020-06-30 01:27:08 -06005526 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005527 builder.clearAccessChain();
5528 builder.setAccessChainLValue(argCopy);
5529 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005530 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005531 } else
5532 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005533 ++rValueCount;
5534 }
5535 spvArgs.push_back(arg);
5536 }
5537
5538 // 3. Make the call.
5539 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005540 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
greg-lunarg639f5462020-11-12 11:10:07 -07005541 builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005542
5543 // 4. Copy back out an "out" arguments.
5544 lValueCount = 0;
5545 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005546 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005547 ++lValueCount;
5548 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005549 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005550 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
greg-lunarg639f5462020-11-12 11:10:07 -07005551 builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005552 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005553 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005554 }
5555 ++lValueCount;
5556 }
5557 }
5558
5559 return result;
5560}
5561
5562// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005563spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005564 spv::Id typeId, spv::Id left, spv::Id right,
5565 glslang::TBasicType typeProxy, bool reduceComparison)
5566{
John Kessenich66011cb2018-03-06 16:12:04 -07005567 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5568 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005569 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005570
5571 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005572 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005573 bool comparison = false;
5574
5575 switch (op) {
5576 case glslang::EOpAdd:
5577 case glslang::EOpAddAssign:
5578 if (isFloat)
5579 binOp = spv::OpFAdd;
5580 else
5581 binOp = spv::OpIAdd;
5582 break;
5583 case glslang::EOpSub:
5584 case glslang::EOpSubAssign:
5585 if (isFloat)
5586 binOp = spv::OpFSub;
5587 else
5588 binOp = spv::OpISub;
5589 break;
5590 case glslang::EOpMul:
5591 case glslang::EOpMulAssign:
5592 if (isFloat)
5593 binOp = spv::OpFMul;
5594 else
5595 binOp = spv::OpIMul;
5596 break;
5597 case glslang::EOpVectorTimesScalar:
5598 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005599 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005600 if (builder.isVector(right))
5601 std::swap(left, right);
5602 assert(builder.isScalar(right));
5603 needMatchingVectors = false;
5604 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005605 } else if (isFloat)
5606 binOp = spv::OpFMul;
5607 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005608 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005609 break;
5610 case glslang::EOpVectorTimesMatrix:
5611 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005612 binOp = spv::OpVectorTimesMatrix;
5613 break;
5614 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005615 binOp = spv::OpMatrixTimesVector;
5616 break;
5617 case glslang::EOpMatrixTimesScalar:
5618 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005619 binOp = spv::OpMatrixTimesScalar;
5620 break;
5621 case glslang::EOpMatrixTimesMatrix:
5622 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005623 binOp = spv::OpMatrixTimesMatrix;
5624 break;
5625 case glslang::EOpOuterProduct:
5626 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005627 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005628 break;
5629
5630 case glslang::EOpDiv:
5631 case glslang::EOpDivAssign:
5632 if (isFloat)
5633 binOp = spv::OpFDiv;
5634 else if (isUnsigned)
5635 binOp = spv::OpUDiv;
5636 else
5637 binOp = spv::OpSDiv;
5638 break;
5639 case glslang::EOpMod:
5640 case glslang::EOpModAssign:
5641 if (isFloat)
5642 binOp = spv::OpFMod;
5643 else if (isUnsigned)
5644 binOp = spv::OpUMod;
5645 else
5646 binOp = spv::OpSMod;
5647 break;
5648 case glslang::EOpRightShift:
5649 case glslang::EOpRightShiftAssign:
5650 if (isUnsigned)
5651 binOp = spv::OpShiftRightLogical;
5652 else
5653 binOp = spv::OpShiftRightArithmetic;
5654 break;
5655 case glslang::EOpLeftShift:
5656 case glslang::EOpLeftShiftAssign:
5657 binOp = spv::OpShiftLeftLogical;
5658 break;
5659 case glslang::EOpAnd:
5660 case glslang::EOpAndAssign:
5661 binOp = spv::OpBitwiseAnd;
5662 break;
5663 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005664 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005665 binOp = spv::OpLogicalAnd;
5666 break;
5667 case glslang::EOpInclusiveOr:
5668 case glslang::EOpInclusiveOrAssign:
5669 binOp = spv::OpBitwiseOr;
5670 break;
5671 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005672 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005673 binOp = spv::OpLogicalOr;
5674 break;
5675 case glslang::EOpExclusiveOr:
5676 case glslang::EOpExclusiveOrAssign:
5677 binOp = spv::OpBitwiseXor;
5678 break;
5679 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005680 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005681 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005682 break;
5683
Ian Romanickb3bd4022019-01-21 08:57:25 -08005684 case glslang::EOpAbsDifference:
5685 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5686 break;
5687
5688 case glslang::EOpAddSaturate:
5689 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5690 break;
5691
5692 case glslang::EOpSubSaturate:
5693 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5694 break;
5695
5696 case glslang::EOpAverage:
5697 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5698 break;
5699
5700 case glslang::EOpAverageRounded:
5701 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5702 break;
5703
5704 case glslang::EOpMul32x16:
5705 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5706 break;
5707
John Kessenich140f3df2015-06-26 16:58:36 -06005708 case glslang::EOpLessThan:
5709 case glslang::EOpGreaterThan:
5710 case glslang::EOpLessThanEqual:
5711 case glslang::EOpGreaterThanEqual:
5712 case glslang::EOpEqual:
5713 case glslang::EOpNotEqual:
5714 case glslang::EOpVectorEqual:
5715 case glslang::EOpVectorNotEqual:
5716 comparison = true;
5717 break;
5718 default:
5719 break;
5720 }
5721
John Kessenich7c1aa102015-10-15 13:29:11 -06005722 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005723 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005724 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005725 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5726 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005727 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005728
5729 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005730 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005731 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005732
qining25262b32016-05-06 17:25:16 -04005733 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005734 decorations.addNoContraction(builder, result);
5735 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005736 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005737 }
5738
5739 if (! comparison)
5740 return 0;
5741
John Kessenich7c1aa102015-10-15 13:29:11 -06005742 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005743
John Kessenich4583b612016-08-07 19:14:22 -06005744 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005745 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5746 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005747 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005748 return result;
5749 }
John Kessenich140f3df2015-06-26 16:58:36 -06005750
5751 switch (op) {
5752 case glslang::EOpLessThan:
5753 if (isFloat)
5754 binOp = spv::OpFOrdLessThan;
5755 else if (isUnsigned)
5756 binOp = spv::OpULessThan;
5757 else
5758 binOp = spv::OpSLessThan;
5759 break;
5760 case glslang::EOpGreaterThan:
5761 if (isFloat)
5762 binOp = spv::OpFOrdGreaterThan;
5763 else if (isUnsigned)
5764 binOp = spv::OpUGreaterThan;
5765 else
5766 binOp = spv::OpSGreaterThan;
5767 break;
5768 case glslang::EOpLessThanEqual:
5769 if (isFloat)
5770 binOp = spv::OpFOrdLessThanEqual;
5771 else if (isUnsigned)
5772 binOp = spv::OpULessThanEqual;
5773 else
5774 binOp = spv::OpSLessThanEqual;
5775 break;
5776 case glslang::EOpGreaterThanEqual:
5777 if (isFloat)
5778 binOp = spv::OpFOrdGreaterThanEqual;
5779 else if (isUnsigned)
5780 binOp = spv::OpUGreaterThanEqual;
5781 else
5782 binOp = spv::OpSGreaterThanEqual;
5783 break;
5784 case glslang::EOpEqual:
5785 case glslang::EOpVectorEqual:
5786 if (isFloat)
5787 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005788 else if (isBool)
5789 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005790 else
5791 binOp = spv::OpIEqual;
5792 break;
5793 case glslang::EOpNotEqual:
5794 case glslang::EOpVectorNotEqual:
5795 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005796 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005797 else if (isBool)
5798 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005799 else
5800 binOp = spv::OpINotEqual;
5801 break;
5802 default:
5803 break;
5804 }
5805
qining25262b32016-05-06 17:25:16 -04005806 if (binOp != spv::OpNop) {
5807 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005808 decorations.addNoContraction(builder, result);
5809 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005810 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005811 }
John Kessenich140f3df2015-06-26 16:58:36 -06005812
5813 return 0;
5814}
5815
John Kessenich04bb8a02015-12-12 12:28:14 -07005816//
5817// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5818// These can be any of:
5819//
5820// matrix * scalar
5821// scalar * matrix
5822// matrix * matrix linear algebraic
5823// matrix * vector
5824// vector * matrix
5825// matrix * matrix componentwise
5826// matrix op matrix op in {+, -, /}
5827// matrix op scalar op in {+, -, /}
5828// scalar op matrix op in {+, -, /}
5829//
John Kessenichead86222018-03-28 18:01:20 -06005830spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5831 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005832{
5833 bool firstClass = true;
5834
5835 // First, handle first-class matrix operations (* and matrix/scalar)
5836 switch (op) {
5837 case spv::OpFDiv:
5838 if (builder.isMatrix(left) && builder.isScalar(right)) {
5839 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005840 spv::Id resultType = builder.getTypeId(right);
5841 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005842 op = spv::OpMatrixTimesScalar;
5843 } else
5844 firstClass = false;
5845 break;
5846 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005847 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005848 std::swap(left, right);
5849 assert(builder.isScalar(right));
5850 break;
5851 case spv::OpVectorTimesMatrix:
5852 assert(builder.isVector(left));
5853 assert(builder.isMatrix(right));
5854 break;
5855 case spv::OpMatrixTimesVector:
5856 assert(builder.isMatrix(left));
5857 assert(builder.isVector(right));
5858 break;
5859 case spv::OpMatrixTimesMatrix:
5860 assert(builder.isMatrix(left));
5861 assert(builder.isMatrix(right));
5862 break;
5863 default:
5864 firstClass = false;
5865 break;
5866 }
5867
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005868 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5869 firstClass = true;
5870
qining25262b32016-05-06 17:25:16 -04005871 if (firstClass) {
5872 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005873 decorations.addNoContraction(builder, result);
5874 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005875 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005876 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005877
LoopDawg592860c2016-06-09 08:57:35 -06005878 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005879 // The result type of all of them is the same type as the (a) matrix operand.
5880 // The algorithm is to:
5881 // - break the matrix(es) into vectors
5882 // - smear any scalar to a vector
5883 // - do vector operations
5884 // - make a matrix out the vector results
5885 switch (op) {
5886 case spv::OpFAdd:
5887 case spv::OpFSub:
5888 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005889 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005890 case spv::OpFMul:
5891 {
5892 // one time set up...
5893 bool leftMat = builder.isMatrix(left);
5894 bool rightMat = builder.isMatrix(right);
5895 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5896 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5897 spv::Id scalarType = builder.getScalarTypeId(typeId);
5898 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5899 std::vector<spv::Id> results;
5900 spv::Id smearVec = spv::NoResult;
5901 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005902 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005903 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005904 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005905
5906 // do each vector op
5907 for (unsigned int c = 0; c < numCols; ++c) {
5908 std::vector<unsigned int> indexes;
5909 indexes.push_back(c);
5910 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5911 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005912 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005913 decorations.addNoContraction(builder, result);
5914 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005915 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005916 }
5917
5918 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005919 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005920 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005921 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005922 }
5923 default:
5924 assert(0);
5925 return spv::NoResult;
5926 }
5927}
5928
John Kessenichead86222018-03-28 18:01:20 -06005929spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005930 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005931{
5932 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005933 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005934 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005935 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5936 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005937
5938 switch (op) {
5939 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005940 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005941 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005942 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005943 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005944 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005945 unaryOp = spv::OpSNegate;
5946 break;
5947
5948 case glslang::EOpLogicalNot:
5949 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005950 unaryOp = spv::OpLogicalNot;
5951 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005952 case glslang::EOpBitwiseNot:
5953 unaryOp = spv::OpNot;
5954 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005955
John Kessenich140f3df2015-06-26 16:58:36 -06005956 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005957 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005958 break;
5959 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005960 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005961 break;
5962 case glslang::EOpTranspose:
5963 unaryOp = spv::OpTranspose;
5964 break;
5965
5966 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005967 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005968 break;
5969 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005970 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005971 break;
5972 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005973 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005974 break;
5975 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005976 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005977 break;
5978 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005979 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005980 break;
5981 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005982 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005983 break;
5984 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005985 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005986 break;
5987 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005988 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005989 break;
5990
5991 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005992 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005993 break;
5994 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005995 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005996 break;
5997 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005998 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005999 break;
6000 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006001 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006002 break;
6003 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006004 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006005 break;
6006 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006007 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006008 break;
6009
6010 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06006011 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06006012 break;
6013 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06006014 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
6016
6017 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006018 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06006019 break;
6020 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06006021 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06006022 break;
6023 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006024 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06006025 break;
6026 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006027 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06006028 break;
6029 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006030 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006031 break;
6032 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006033 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006034 break;
6035
6036 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06006037 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06006038 break;
6039 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06006040 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06006041 break;
6042 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06006043 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06006044 break;
6045 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06006046 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06006047 break;
6048 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06006049 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06006050 break;
6051 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006052 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06006053 break;
6054
6055 case glslang::EOpIsNan:
6056 unaryOp = spv::OpIsNan;
6057 break;
6058 case glslang::EOpIsInf:
6059 unaryOp = spv::OpIsInf;
6060 break;
LoopDawg592860c2016-06-09 08:57:35 -06006061 case glslang::EOpIsFinite:
6062 unaryOp = spv::OpIsFinite;
6063 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006064
Rex Xucbc426e2015-12-15 16:03:10 +08006065 case glslang::EOpFloatBitsToInt:
6066 case glslang::EOpFloatBitsToUint:
6067 case glslang::EOpIntBitsToFloat:
6068 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08006069 case glslang::EOpDoubleBitsToInt64:
6070 case glslang::EOpDoubleBitsToUint64:
6071 case glslang::EOpInt64BitsToDouble:
6072 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08006073 case glslang::EOpFloat16BitsToInt16:
6074 case glslang::EOpFloat16BitsToUint16:
6075 case glslang::EOpInt16BitsToFloat16:
6076 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08006077 unaryOp = spv::OpBitcast;
6078 break;
6079
John Kessenich140f3df2015-06-26 16:58:36 -06006080 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006081 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006082 break;
6083 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006084 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006085 break;
6086 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006087 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006088 break;
6089 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006090 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006091 break;
6092 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006093 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006094 break;
6095 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006096 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006097 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006098#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06006099 case glslang::EOpPackSnorm4x8:
6100 libCall = spv::GLSLstd450PackSnorm4x8;
6101 break;
6102 case glslang::EOpUnpackSnorm4x8:
6103 libCall = spv::GLSLstd450UnpackSnorm4x8;
6104 break;
6105 case glslang::EOpPackUnorm4x8:
6106 libCall = spv::GLSLstd450PackUnorm4x8;
6107 break;
6108 case glslang::EOpUnpackUnorm4x8:
6109 libCall = spv::GLSLstd450UnpackUnorm4x8;
6110 break;
6111 case glslang::EOpPackDouble2x32:
6112 libCall = spv::GLSLstd450PackDouble2x32;
6113 break;
6114 case glslang::EOpUnpackDouble2x32:
6115 libCall = spv::GLSLstd450UnpackDouble2x32;
6116 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006117#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006118
Rex Xu8ff43de2016-04-22 16:51:45 +08006119 case glslang::EOpPackInt2x32:
6120 case glslang::EOpUnpackInt2x32:
6121 case glslang::EOpPackUint2x32:
6122 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07006123 case glslang::EOpPack16:
6124 case glslang::EOpPack32:
6125 case glslang::EOpPack64:
6126 case glslang::EOpUnpack32:
6127 case glslang::EOpUnpack16:
6128 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006129 case glslang::EOpPackInt2x16:
6130 case glslang::EOpUnpackInt2x16:
6131 case glslang::EOpPackUint2x16:
6132 case glslang::EOpUnpackUint2x16:
6133 case glslang::EOpPackInt4x16:
6134 case glslang::EOpUnpackInt4x16:
6135 case glslang::EOpPackUint4x16:
6136 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006137 case glslang::EOpPackFloat2x16:
6138 case glslang::EOpUnpackFloat2x16:
6139 unaryOp = spv::OpBitcast;
6140 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006141
John Kessenich140f3df2015-06-26 16:58:36 -06006142 case glslang::EOpDPdx:
6143 unaryOp = spv::OpDPdx;
6144 break;
6145 case glslang::EOpDPdy:
6146 unaryOp = spv::OpDPdy;
6147 break;
6148 case glslang::EOpFwidth:
6149 unaryOp = spv::OpFwidth;
6150 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006151
John Kessenich140f3df2015-06-26 16:58:36 -06006152 case glslang::EOpAny:
6153 unaryOp = spv::OpAny;
6154 break;
6155 case glslang::EOpAll:
6156 unaryOp = spv::OpAll;
6157 break;
6158
6159 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006160 if (isFloat)
6161 libCall = spv::GLSLstd450FAbs;
6162 else
6163 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006164 break;
6165 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006166 if (isFloat)
6167 libCall = spv::GLSLstd450FSign;
6168 else
6169 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006170 break;
6171
John Kessenicha28f7a72019-08-06 07:00:58 -06006172#ifndef GLSLANG_WEB
6173 case glslang::EOpDPdxFine:
6174 unaryOp = spv::OpDPdxFine;
6175 break;
6176 case glslang::EOpDPdyFine:
6177 unaryOp = spv::OpDPdyFine;
6178 break;
6179 case glslang::EOpFwidthFine:
6180 unaryOp = spv::OpFwidthFine;
6181 break;
6182 case glslang::EOpDPdxCoarse:
6183 unaryOp = spv::OpDPdxCoarse;
6184 break;
6185 case glslang::EOpDPdyCoarse:
6186 unaryOp = spv::OpDPdyCoarse;
6187 break;
6188 case glslang::EOpFwidthCoarse:
6189 unaryOp = spv::OpFwidthCoarse;
6190 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006191 case glslang::EOpRayQueryProceed:
6192 unaryOp = spv::OpRayQueryProceedKHR;
6193 break;
6194 case glslang::EOpRayQueryGetRayTMin:
6195 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6196 break;
6197 case glslang::EOpRayQueryGetRayFlags:
6198 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6199 break;
6200 case glslang::EOpRayQueryGetWorldRayOrigin:
6201 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6202 break;
6203 case glslang::EOpRayQueryGetWorldRayDirection:
6204 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6205 break;
6206 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6207 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6208 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006209 case glslang::EOpInterpolateAtCentroid:
6210 if (typeProxy == glslang::EbtFloat16)
6211 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6212 libCall = spv::GLSLstd450InterpolateAtCentroid;
6213 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006214 case glslang::EOpAtomicCounterIncrement:
6215 case glslang::EOpAtomicCounterDecrement:
6216 case glslang::EOpAtomicCounter:
6217 {
6218 // Handle all of the atomics in one place, in createAtomicOperation()
6219 std::vector<spv::Id> operands;
6220 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006221 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006222 }
6223
John Kessenichfc51d282015-08-19 13:34:18 -06006224 case glslang::EOpBitFieldReverse:
6225 unaryOp = spv::OpBitReverse;
6226 break;
6227 case glslang::EOpBitCount:
6228 unaryOp = spv::OpBitCount;
6229 break;
6230 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006231 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006232 break;
6233 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006234 if (isUnsigned)
6235 libCall = spv::GLSLstd450FindUMsb;
6236 else
6237 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006238 break;
6239
Ian Romanickb3bd4022019-01-21 08:57:25 -08006240 case glslang::EOpCountLeadingZeros:
6241 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6242 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6243 unaryOp = spv::OpUCountLeadingZerosINTEL;
6244 break;
6245
6246 case glslang::EOpCountTrailingZeros:
6247 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6248 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6249 unaryOp = spv::OpUCountTrailingZerosINTEL;
6250 break;
6251
Rex Xu574ab042016-04-14 16:53:07 +08006252 case glslang::EOpBallot:
6253 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006254 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006255 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006256 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006257 case glslang::EOpMinInvocations:
6258 case glslang::EOpMaxInvocations:
6259 case glslang::EOpAddInvocations:
6260 case glslang::EOpMinInvocationsNonUniform:
6261 case glslang::EOpMaxInvocationsNonUniform:
6262 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006263 case glslang::EOpMinInvocationsInclusiveScan:
6264 case glslang::EOpMaxInvocationsInclusiveScan:
6265 case glslang::EOpAddInvocationsInclusiveScan:
6266 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6267 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6268 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6269 case glslang::EOpMinInvocationsExclusiveScan:
6270 case glslang::EOpMaxInvocationsExclusiveScan:
6271 case glslang::EOpAddInvocationsExclusiveScan:
6272 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6273 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6274 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006275 {
6276 std::vector<spv::Id> operands;
6277 operands.push_back(operand);
6278 return createInvocationsOperation(op, typeId, operands, typeProxy);
6279 }
John Kessenich66011cb2018-03-06 16:12:04 -07006280 case glslang::EOpSubgroupAll:
6281 case glslang::EOpSubgroupAny:
6282 case glslang::EOpSubgroupAllEqual:
6283 case glslang::EOpSubgroupBroadcastFirst:
6284 case glslang::EOpSubgroupBallot:
6285 case glslang::EOpSubgroupInverseBallot:
6286 case glslang::EOpSubgroupBallotBitCount:
6287 case glslang::EOpSubgroupBallotInclusiveBitCount:
6288 case glslang::EOpSubgroupBallotExclusiveBitCount:
6289 case glslang::EOpSubgroupBallotFindLSB:
6290 case glslang::EOpSubgroupBallotFindMSB:
6291 case glslang::EOpSubgroupAdd:
6292 case glslang::EOpSubgroupMul:
6293 case glslang::EOpSubgroupMin:
6294 case glslang::EOpSubgroupMax:
6295 case glslang::EOpSubgroupAnd:
6296 case glslang::EOpSubgroupOr:
6297 case glslang::EOpSubgroupXor:
6298 case glslang::EOpSubgroupInclusiveAdd:
6299 case glslang::EOpSubgroupInclusiveMul:
6300 case glslang::EOpSubgroupInclusiveMin:
6301 case glslang::EOpSubgroupInclusiveMax:
6302 case glslang::EOpSubgroupInclusiveAnd:
6303 case glslang::EOpSubgroupInclusiveOr:
6304 case glslang::EOpSubgroupInclusiveXor:
6305 case glslang::EOpSubgroupExclusiveAdd:
6306 case glslang::EOpSubgroupExclusiveMul:
6307 case glslang::EOpSubgroupExclusiveMin:
6308 case glslang::EOpSubgroupExclusiveMax:
6309 case glslang::EOpSubgroupExclusiveAnd:
6310 case glslang::EOpSubgroupExclusiveOr:
6311 case glslang::EOpSubgroupExclusiveXor:
6312 case glslang::EOpSubgroupQuadSwapHorizontal:
6313 case glslang::EOpSubgroupQuadSwapVertical:
6314 case glslang::EOpSubgroupQuadSwapDiagonal: {
6315 std::vector<spv::Id> operands;
6316 operands.push_back(operand);
6317 return createSubgroupOperation(op, typeId, operands, typeProxy);
6318 }
Rex Xu9d93a232016-05-05 12:30:44 +08006319 case glslang::EOpMbcnt:
6320 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6321 libCall = spv::MbcntAMD;
6322 break;
6323
6324 case glslang::EOpCubeFaceIndex:
6325 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6326 libCall = spv::CubeFaceIndexAMD;
6327 break;
6328
6329 case glslang::EOpCubeFaceCoord:
6330 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6331 libCall = spv::CubeFaceCoordAMD;
6332 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006333 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006334 unaryOp = spv::OpGroupNonUniformPartitionNV;
6335 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006336 case glslang::EOpConstructReference:
6337 unaryOp = spv::OpBitcast;
6338 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05006339
6340 case glslang::EOpConvUint64ToAccStruct:
6341 case glslang::EOpConvUvec2ToAccStruct:
6342 unaryOp = spv::OpConvertUToAccelerationStructureKHR;
6343 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006344#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006345
6346 case glslang::EOpCopyObject:
6347 unaryOp = spv::OpCopyObject;
6348 break;
6349
John Kessenich140f3df2015-06-26 16:58:36 -06006350 default:
6351 return 0;
6352 }
6353
6354 spv::Id id;
6355 if (libCall >= 0) {
6356 std::vector<spv::Id> args;
6357 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006358 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006359 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006360 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006361 }
John Kessenich140f3df2015-06-26 16:58:36 -06006362
John Kessenichb9197c82019-08-11 07:41:45 -06006363 decorations.addNoContraction(builder, id);
6364 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006365 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006366}
6367
John Kessenich7a53f762016-01-20 11:19:27 -07006368// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006369spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6370 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006371{
6372 // Handle unary operations vector by vector.
6373 // The result type is the same type as the original type.
6374 // The algorithm is to:
6375 // - break the matrix into vectors
6376 // - apply the operation to each vector
6377 // - make a matrix out the vector results
6378
6379 // get the types sorted out
6380 int numCols = builder.getNumColumns(operand);
6381 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006382 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6383 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006384 std::vector<spv::Id> results;
6385
6386 // do each vector op
6387 for (int c = 0; c < numCols; ++c) {
6388 std::vector<unsigned int> indexes;
6389 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006390 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6391 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006392 decorations.addNoContraction(builder, destVec);
6393 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006394 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006395 }
6396
6397 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006398 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006399 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006400 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006401}
6402
John Kessenichad7645f2018-06-04 19:11:25 -06006403// For converting integers where both the bitwidth and the signedness could
6404// change, but only do the width change here. The caller is still responsible
6405// for the signedness conversion.
6406spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006407{
John Kessenichad7645f2018-06-04 19:11:25 -06006408 // Get the result type width, based on the type to convert to.
6409 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006410 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006411 case glslang::EOpConvInt16ToUint8:
6412 case glslang::EOpConvIntToUint8:
6413 case glslang::EOpConvInt64ToUint8:
6414 case glslang::EOpConvUint16ToInt8:
6415 case glslang::EOpConvUintToInt8:
6416 case glslang::EOpConvUint64ToInt8:
6417 width = 8;
6418 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006419 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006420 case glslang::EOpConvIntToUint16:
6421 case glslang::EOpConvInt64ToUint16:
6422 case glslang::EOpConvUint8ToInt16:
6423 case glslang::EOpConvUintToInt16:
6424 case glslang::EOpConvUint64ToInt16:
6425 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006426 break;
6427 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006428 case glslang::EOpConvInt16ToUint:
6429 case glslang::EOpConvInt64ToUint:
6430 case glslang::EOpConvUint8ToInt:
6431 case glslang::EOpConvUint16ToInt:
6432 case glslang::EOpConvUint64ToInt:
6433 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006434 break;
6435 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006436 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006437 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006438 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006439 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006440 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006441 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006442 break;
6443
6444 default:
6445 assert(false && "Default missing");
6446 break;
6447 }
6448
John Kessenichad7645f2018-06-04 19:11:25 -06006449 // Get the conversion operation and result type,
6450 // based on the target width, but the source type.
6451 spv::Id type = spv::NoType;
6452 spv::Op convOp = spv::OpNop;
6453 switch(op) {
6454 case glslang::EOpConvInt8ToUint16:
6455 case glslang::EOpConvInt8ToUint:
6456 case glslang::EOpConvInt8ToUint64:
6457 case glslang::EOpConvInt16ToUint8:
6458 case glslang::EOpConvInt16ToUint:
6459 case glslang::EOpConvInt16ToUint64:
6460 case glslang::EOpConvIntToUint8:
6461 case glslang::EOpConvIntToUint16:
6462 case glslang::EOpConvIntToUint64:
6463 case glslang::EOpConvInt64ToUint8:
6464 case glslang::EOpConvInt64ToUint16:
6465 case glslang::EOpConvInt64ToUint:
6466 convOp = spv::OpSConvert;
6467 type = builder.makeIntType(width);
6468 break;
6469 default:
6470 convOp = spv::OpUConvert;
6471 type = builder.makeUintType(width);
6472 break;
6473 }
6474
John Kessenich66011cb2018-03-06 16:12:04 -07006475 if (vectorSize > 0)
6476 type = builder.makeVectorType(type, vectorSize);
6477
John Kessenichad7645f2018-06-04 19:11:25 -06006478 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006479}
6480
John Kessenichead86222018-03-28 18:01:20 -06006481spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6482 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006483{
6484 spv::Op convOp = spv::OpNop;
6485 spv::Id zero = 0;
6486 spv::Id one = 0;
6487
6488 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6489
6490 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006491 case glslang::EOpConvIntToBool:
6492 case glslang::EOpConvUintToBool:
6493 zero = builder.makeUintConstant(0);
6494 zero = makeSmearedConstant(zero, vectorSize);
6495 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006496 case glslang::EOpConvFloatToBool:
6497 zero = builder.makeFloatConstant(0.0F);
6498 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006499 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006500 case glslang::EOpConvBoolToFloat:
6501 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006502 zero = builder.makeFloatConstant(0.0F);
6503 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006504 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006505
John Kessenich140f3df2015-06-26 16:58:36 -06006506 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006507 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006508#ifndef GLSLANG_WEB
6509 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006510 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006511 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006512 } else
6513#endif
6514 {
6515 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006516 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006517 }
Rex Xucabbb782017-03-24 13:41:14 +08006518
John Kessenich140f3df2015-06-26 16:58:36 -06006519 convOp = spv::OpSelect;
6520 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006521
John Kessenich140f3df2015-06-26 16:58:36 -06006522 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006523 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006524#ifndef GLSLANG_WEB
6525 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006526 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006527 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006528 } else
6529#endif
6530 {
6531 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006532 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006533 }
Rex Xucabbb782017-03-24 13:41:14 +08006534
John Kessenich140f3df2015-06-26 16:58:36 -06006535 convOp = spv::OpSelect;
6536 break;
6537
John Kessenich66011cb2018-03-06 16:12:04 -07006538 case glslang::EOpConvInt8ToFloat16:
6539 case glslang::EOpConvInt8ToFloat:
6540 case glslang::EOpConvInt8ToDouble:
6541 case glslang::EOpConvInt16ToFloat16:
6542 case glslang::EOpConvInt16ToFloat:
6543 case glslang::EOpConvInt16ToDouble:
6544 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006545 case glslang::EOpConvIntToFloat:
6546 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006547 case glslang::EOpConvInt64ToFloat:
6548 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006549 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006550 convOp = spv::OpConvertSToF;
6551 break;
6552
John Kessenich66011cb2018-03-06 16:12:04 -07006553 case glslang::EOpConvUint8ToFloat16:
6554 case glslang::EOpConvUint8ToFloat:
6555 case glslang::EOpConvUint8ToDouble:
6556 case glslang::EOpConvUint16ToFloat16:
6557 case glslang::EOpConvUint16ToFloat:
6558 case glslang::EOpConvUint16ToDouble:
6559 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006560 case glslang::EOpConvUintToFloat:
6561 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006562 case glslang::EOpConvUint64ToFloat:
6563 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006564 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006565 convOp = spv::OpConvertUToF;
6566 break;
6567
John Kessenich66011cb2018-03-06 16:12:04 -07006568 case glslang::EOpConvFloat16ToInt8:
6569 case glslang::EOpConvFloatToInt8:
6570 case glslang::EOpConvDoubleToInt8:
6571 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006572 case glslang::EOpConvFloatToInt16:
6573 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006574 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006575 case glslang::EOpConvFloatToInt:
6576 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006577 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006578 case glslang::EOpConvFloatToInt64:
6579 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006580 convOp = spv::OpConvertFToS;
6581 break;
6582
John Kessenich66011cb2018-03-06 16:12:04 -07006583 case glslang::EOpConvUint8ToInt8:
6584 case glslang::EOpConvInt8ToUint8:
6585 case glslang::EOpConvUint16ToInt16:
6586 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006587 case glslang::EOpConvUintToInt:
6588 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006589 case glslang::EOpConvUint64ToInt64:
6590 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006591 if (builder.isInSpecConstCodeGenMode()) {
6592 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006593#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006594 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6595 zero = builder.makeUint8Constant(0);
6596 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006597 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006598 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6599 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006600 } else
6601#endif
6602 {
Rex Xucabbb782017-03-24 13:41:14 +08006603 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006604 }
qining189b2032016-04-12 23:16:20 -04006605 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006606 // Use OpIAdd, instead of OpBitcast to do the conversion when
6607 // generating for OpSpecConstantOp instruction.
6608 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6609 }
6610 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006611 convOp = spv::OpBitcast;
6612 break;
6613
John Kessenich66011cb2018-03-06 16:12:04 -07006614 case glslang::EOpConvFloat16ToUint8:
6615 case glslang::EOpConvFloatToUint8:
6616 case glslang::EOpConvDoubleToUint8:
6617 case glslang::EOpConvFloat16ToUint16:
6618 case glslang::EOpConvFloatToUint16:
6619 case glslang::EOpConvDoubleToUint16:
6620 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006621 case glslang::EOpConvFloatToUint:
6622 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006623 case glslang::EOpConvFloatToUint64:
6624 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006625 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006626 convOp = spv::OpConvertFToU;
6627 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006628
John Kessenich39697cd2019-08-08 10:35:51 -06006629#ifndef GLSLANG_WEB
6630 case glslang::EOpConvInt8ToBool:
6631 case glslang::EOpConvUint8ToBool:
6632 zero = builder.makeUint8Constant(0);
6633 zero = makeSmearedConstant(zero, vectorSize);
6634 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6635 case glslang::EOpConvInt16ToBool:
6636 case glslang::EOpConvUint16ToBool:
6637 zero = builder.makeUint16Constant(0);
6638 zero = makeSmearedConstant(zero, vectorSize);
6639 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6640 case glslang::EOpConvInt64ToBool:
6641 case glslang::EOpConvUint64ToBool:
6642 zero = builder.makeUint64Constant(0);
6643 zero = makeSmearedConstant(zero, vectorSize);
6644 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6645 case glslang::EOpConvDoubleToBool:
6646 zero = builder.makeDoubleConstant(0.0);
6647 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006648 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006649 case glslang::EOpConvFloat16ToBool:
6650 zero = builder.makeFloat16Constant(0.0F);
6651 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006652 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006653 case glslang::EOpConvBoolToDouble:
6654 convOp = spv::OpSelect;
6655 zero = builder.makeDoubleConstant(0.0);
6656 one = builder.makeDoubleConstant(1.0);
6657 break;
6658 case glslang::EOpConvBoolToFloat16:
6659 convOp = spv::OpSelect;
6660 zero = builder.makeFloat16Constant(0.0F);
6661 one = builder.makeFloat16Constant(1.0F);
6662 break;
6663 case glslang::EOpConvBoolToInt8:
6664 zero = builder.makeInt8Constant(0);
6665 one = builder.makeInt8Constant(1);
6666 convOp = spv::OpSelect;
6667 break;
6668 case glslang::EOpConvBoolToUint8:
6669 zero = builder.makeUint8Constant(0);
6670 one = builder.makeUint8Constant(1);
6671 convOp = spv::OpSelect;
6672 break;
6673 case glslang::EOpConvBoolToInt16:
6674 zero = builder.makeInt16Constant(0);
6675 one = builder.makeInt16Constant(1);
6676 convOp = spv::OpSelect;
6677 break;
6678 case glslang::EOpConvBoolToUint16:
6679 zero = builder.makeUint16Constant(0);
6680 one = builder.makeUint16Constant(1);
6681 convOp = spv::OpSelect;
6682 break;
6683 case glslang::EOpConvDoubleToFloat:
6684 case glslang::EOpConvFloatToDouble:
6685 case glslang::EOpConvDoubleToFloat16:
6686 case glslang::EOpConvFloat16ToDouble:
6687 case glslang::EOpConvFloatToFloat16:
6688 case glslang::EOpConvFloat16ToFloat:
6689 convOp = spv::OpFConvert;
6690 if (builder.isMatrixType(destType))
6691 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6692 break;
6693
John Kessenich66011cb2018-03-06 16:12:04 -07006694 case glslang::EOpConvInt8ToInt16:
6695 case glslang::EOpConvInt8ToInt:
6696 case glslang::EOpConvInt8ToInt64:
6697 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006698 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006699 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006700 case glslang::EOpConvIntToInt8:
6701 case glslang::EOpConvIntToInt16:
6702 case glslang::EOpConvIntToInt64:
6703 case glslang::EOpConvInt64ToInt8:
6704 case glslang::EOpConvInt64ToInt16:
6705 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006706 convOp = spv::OpSConvert;
6707 break;
6708
John Kessenich66011cb2018-03-06 16:12:04 -07006709 case glslang::EOpConvUint8ToUint16:
6710 case glslang::EOpConvUint8ToUint:
6711 case glslang::EOpConvUint8ToUint64:
6712 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006713 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006714 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006715 case glslang::EOpConvUintToUint8:
6716 case glslang::EOpConvUintToUint16:
6717 case glslang::EOpConvUintToUint64:
6718 case glslang::EOpConvUint64ToUint8:
6719 case glslang::EOpConvUint64ToUint16:
6720 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006721 convOp = spv::OpUConvert;
6722 break;
6723
John Kessenich66011cb2018-03-06 16:12:04 -07006724 case glslang::EOpConvInt8ToUint16:
6725 case glslang::EOpConvInt8ToUint:
6726 case glslang::EOpConvInt8ToUint64:
6727 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006728 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006729 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006730 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006731 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006732 case glslang::EOpConvIntToUint64:
6733 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006734 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006735 case glslang::EOpConvInt64ToUint:
6736 case glslang::EOpConvUint8ToInt16:
6737 case glslang::EOpConvUint8ToInt:
6738 case glslang::EOpConvUint8ToInt64:
6739 case glslang::EOpConvUint16ToInt8:
6740 case glslang::EOpConvUint16ToInt:
6741 case glslang::EOpConvUint16ToInt64:
6742 case glslang::EOpConvUintToInt8:
6743 case glslang::EOpConvUintToInt16:
6744 case glslang::EOpConvUintToInt64:
6745 case glslang::EOpConvUint64ToInt8:
6746 case glslang::EOpConvUint64ToInt16:
6747 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006748 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006749 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006750
6751 if (builder.isInSpecConstCodeGenMode()) {
6752 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006753 switch(op) {
6754 case glslang::EOpConvInt16ToUint8:
6755 case glslang::EOpConvIntToUint8:
6756 case glslang::EOpConvInt64ToUint8:
6757 case glslang::EOpConvUint16ToInt8:
6758 case glslang::EOpConvUintToInt8:
6759 case glslang::EOpConvUint64ToInt8:
6760 zero = builder.makeUint8Constant(0);
6761 break;
6762 case glslang::EOpConvInt8ToUint16:
6763 case glslang::EOpConvIntToUint16:
6764 case glslang::EOpConvInt64ToUint16:
6765 case glslang::EOpConvUint8ToInt16:
6766 case glslang::EOpConvUintToInt16:
6767 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006768 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006769 break;
6770 case glslang::EOpConvInt8ToUint:
6771 case glslang::EOpConvInt16ToUint:
6772 case glslang::EOpConvInt64ToUint:
6773 case glslang::EOpConvUint8ToInt:
6774 case glslang::EOpConvUint16ToInt:
6775 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006776 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006777 break;
6778 case glslang::EOpConvInt8ToUint64:
6779 case glslang::EOpConvInt16ToUint64:
6780 case glslang::EOpConvIntToUint64:
6781 case glslang::EOpConvUint8ToInt64:
6782 case glslang::EOpConvUint16ToInt64:
6783 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006784 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006785 break;
6786 default:
6787 assert(false && "Default missing");
6788 break;
6789 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006790 zero = makeSmearedConstant(zero, vectorSize);
6791 // Use OpIAdd, instead of OpBitcast to do the conversion when
6792 // generating for OpSpecConstantOp instruction.
6793 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6794 }
6795 // For normal run-time conversion instruction, use OpBitcast.
6796 convOp = spv::OpBitcast;
6797 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006798 case glslang::EOpConvUint64ToPtr:
6799 convOp = spv::OpConvertUToPtr;
6800 break;
6801 case glslang::EOpConvPtrToUint64:
6802 convOp = spv::OpConvertPtrToU;
6803 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006804 case glslang::EOpConvPtrToUvec2:
6805 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006806 if (builder.isVector(operand))
6807 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6808 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006809 convOp = spv::OpBitcast;
6810 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006811#endif
6812
John Kessenich140f3df2015-06-26 16:58:36 -06006813 default:
6814 break;
6815 }
6816
6817 spv::Id result = 0;
6818 if (convOp == spv::OpNop)
6819 return result;
6820
6821 if (convOp == spv::OpSelect) {
6822 zero = makeSmearedConstant(zero, vectorSize);
6823 one = makeSmearedConstant(one, vectorSize);
6824 result = builder.createTriOp(convOp, destType, operand, one, zero);
6825 } else
6826 result = builder.createUnaryOp(convOp, destType, operand);
6827
John Kessenichead86222018-03-28 18:01:20 -06006828 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006829 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006830 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006831}
6832
6833spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6834{
6835 if (vectorSize == 0)
6836 return constant;
6837
6838 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6839 std::vector<spv::Id> components;
6840 for (int c = 0; c < vectorSize; ++c)
6841 components.push_back(constant);
6842 return builder.makeCompositeConstant(vectorTypeId, components);
6843}
6844
John Kessenich426394d2015-07-23 10:22:48 -06006845// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006846spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6847 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6848 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006849{
6850 spv::Op opCode = spv::OpNop;
6851
6852 switch (op) {
6853 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006854 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006855 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006856 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006857 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6858 opCode = spv::OpAtomicFAddEXT;
6859 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6860 if (typeProxy == glslang::EbtFloat)
6861 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6862 else
6863 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6864 }
John Kessenich426394d2015-07-23 10:22:48 -06006865 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006866 case glslang::EOpAtomicCounterSubtract:
6867 opCode = spv::OpAtomicISub;
6868 break;
John Kessenich426394d2015-07-23 10:22:48 -06006869 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006870 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006871 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006872 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6873 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006874 break;
6875 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006876 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006877 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006878 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6879 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006880 break;
6881 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006882 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006883 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006884 opCode = spv::OpAtomicAnd;
6885 break;
6886 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006887 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006888 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006889 opCode = spv::OpAtomicOr;
6890 break;
6891 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006892 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006893 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006894 opCode = spv::OpAtomicXor;
6895 break;
6896 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006897 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006898 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006899 opCode = spv::OpAtomicExchange;
6900 break;
6901 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006902 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006903 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006904 opCode = spv::OpAtomicCompareExchange;
6905 break;
6906 case glslang::EOpAtomicCounterIncrement:
6907 opCode = spv::OpAtomicIIncrement;
6908 break;
6909 case glslang::EOpAtomicCounterDecrement:
6910 opCode = spv::OpAtomicIDecrement;
6911 break;
6912 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006913 case glslang::EOpImageAtomicLoad:
6914 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006915 opCode = spv::OpAtomicLoad;
6916 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006917 case glslang::EOpAtomicStore:
6918 case glslang::EOpImageAtomicStore:
6919 opCode = spv::OpAtomicStore;
6920 break;
John Kessenich426394d2015-07-23 10:22:48 -06006921 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006922 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006923 break;
6924 }
6925
Rex Xue8fe8b02017-09-26 15:42:56 +08006926 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6927 builder.addCapability(spv::CapabilityInt64Atomics);
6928
John Kessenich426394d2015-07-23 10:22:48 -06006929 // Sort out the operands
6930 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006931 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006932 // - compare-exchange swaps the value and comparator
6933 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006934 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006935 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6936 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6937 spv::Id scopeId;
6938 if (glslangIntermediate->usingVulkanMemoryModel()) {
6939 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6940 } else {
6941 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6942 }
6943 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006944 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6945 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006946 spv::MemorySemanticsVolatileMask :
6947 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006948 spv::Id semanticsId2 = semanticsId;
6949
6950 pointerId = operands[0];
6951 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6952 // no additional operands
6953 } else if (opCode == spv::OpAtomicCompareExchange) {
6954 compareId = operands[1];
6955 valueId = operands[2];
6956 if (operands.size() > 3) {
6957 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006958 semanticsId = builder.makeUintConstant(
6959 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6960 semanticsId2 = builder.makeUintConstant(
6961 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006962 }
6963 } else if (opCode == spv::OpAtomicLoad) {
6964 if (operands.size() > 1) {
6965 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006966 semanticsId = builder.makeUintConstant(
6967 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006968 }
6969 } else {
6970 // atomic store or RMW
6971 valueId = operands[1];
6972 if (operands.size() > 2) {
6973 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006974 semanticsId = builder.makeUintConstant
6975 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006976 }
Rex Xu04db3f52015-09-16 11:44:02 +08006977 }
John Kessenich426394d2015-07-23 10:22:48 -06006978
Jeff Bolz36831c92018-09-05 10:11:41 -05006979 // Check for capabilities
6980 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006981 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6982 spv::MemorySemanticsMakeVisibleKHRMask |
6983 spv::MemorySemanticsOutputMemoryKHRMask |
6984 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006985 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6986 }
John Kessenich426394d2015-07-23 10:22:48 -06006987
Jeff Bolz36831c92018-09-05 10:11:41 -05006988 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6989 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6990 }
John Kessenich48d6e792017-10-06 21:21:48 -06006991
Jeff Bolz36831c92018-09-05 10:11:41 -05006992 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6993 spvAtomicOperands.push_back(pointerId);
6994 spvAtomicOperands.push_back(scopeId);
6995 spvAtomicOperands.push_back(semanticsId);
6996 if (opCode == spv::OpAtomicCompareExchange) {
6997 spvAtomicOperands.push_back(semanticsId2);
6998 spvAtomicOperands.push_back(valueId);
6999 spvAtomicOperands.push_back(compareId);
7000 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
7001 spvAtomicOperands.push_back(valueId);
7002 }
John Kessenich48d6e792017-10-06 21:21:48 -06007003
Jeff Bolz36831c92018-09-05 10:11:41 -05007004 if (opCode == spv::OpAtomicStore) {
7005 builder.createNoResultOp(opCode, spvAtomicOperands);
7006 return 0;
7007 } else {
7008 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
7009
7010 // GLSL and HLSL atomic-counter decrement return post-decrement value,
7011 // while SPIR-V returns pre-decrement value. Translate between these semantics.
7012 if (op == glslang::EOpAtomicCounterDecrement)
7013 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
7014
7015 return resultId;
7016 }
John Kessenich426394d2015-07-23 10:22:48 -06007017}
7018
John Kessenich91cef522016-05-05 16:45:40 -06007019// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07007020spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
7021 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06007022{
John Kessenich66011cb2018-03-06 16:12:04 -07007023 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7024 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08007025
Rex Xu51596642016-09-21 18:56:12 +08007026 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06007027 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08007028 spv::GroupOperation groupOperation = spv::GroupOperationMax;
7029
chaocf200da82016-12-20 12:44:35 -08007030 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
7031 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08007032 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
7033 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007034 } else if (op == glslang::EOpAnyInvocation ||
7035 op == glslang::EOpAllInvocations ||
7036 op == glslang::EOpAllInvocationsEqual) {
7037 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
7038 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08007039 } else {
7040 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08007041 if (op == glslang::EOpMinInvocationsNonUniform ||
7042 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08007043 op == glslang::EOpAddInvocationsNonUniform ||
7044 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7045 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7046 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
7047 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
7048 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
7049 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08007050 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08007051
Rex Xu430ef402016-10-14 17:22:23 +08007052 switch (op) {
7053 case glslang::EOpMinInvocations:
7054 case glslang::EOpMaxInvocations:
7055 case glslang::EOpAddInvocations:
7056 case glslang::EOpMinInvocationsNonUniform:
7057 case glslang::EOpMaxInvocationsNonUniform:
7058 case glslang::EOpAddInvocationsNonUniform:
7059 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08007060 break;
7061 case glslang::EOpMinInvocationsInclusiveScan:
7062 case glslang::EOpMaxInvocationsInclusiveScan:
7063 case glslang::EOpAddInvocationsInclusiveScan:
7064 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7065 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7066 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7067 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007068 break;
7069 case glslang::EOpMinInvocationsExclusiveScan:
7070 case glslang::EOpMaxInvocationsExclusiveScan:
7071 case glslang::EOpAddInvocationsExclusiveScan:
7072 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7073 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7074 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7075 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007076 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07007077 default:
7078 break;
Rex Xu430ef402016-10-14 17:22:23 +08007079 }
John Kessenich149afc32018-08-14 13:31:43 -06007080 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7081 spvGroupOperands.push_back(scope);
7082 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007083 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007084 spvGroupOperands.push_back(groupOp);
7085 }
Rex Xu51596642016-09-21 18:56:12 +08007086 }
7087
John Kessenich149afc32018-08-14 13:31:43 -06007088 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
7089 spv::IdImmediate op = { true, *opIt };
7090 spvGroupOperands.push_back(op);
7091 }
John Kessenich91cef522016-05-05 16:45:40 -06007092
7093 switch (op) {
7094 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007095 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08007096 break;
John Kessenich91cef522016-05-05 16:45:40 -06007097 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007098 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08007099 break;
John Kessenich91cef522016-05-05 16:45:40 -06007100 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007101 opCode = spv::OpSubgroupAllEqualKHR;
7102 break;
Rex Xu51596642016-09-21 18:56:12 +08007103 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08007104 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08007105 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007106 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007107 break;
7108 case glslang::EOpReadFirstInvocation:
7109 opCode = spv::OpSubgroupFirstInvocationKHR;
7110 break;
7111 case glslang::EOpBallot:
7112 {
7113 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
7114 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
7115 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
7116 //
7117 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
7118 //
7119 spv::Id uintType = builder.makeUintType(32);
7120 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
7121 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
7122
7123 std::vector<spv::Id> components;
7124 components.push_back(builder.createCompositeExtract(result, uintType, 0));
7125 components.push_back(builder.createCompositeExtract(result, uintType, 1));
7126
7127 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
7128 return builder.createUnaryOp(spv::OpBitcast, typeId,
7129 builder.createCompositeConstruct(uvec2Type, components));
7130 }
7131
Rex Xu9d93a232016-05-05 12:30:44 +08007132 case glslang::EOpMinInvocations:
7133 case glslang::EOpMaxInvocations:
7134 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007135 case glslang::EOpMinInvocationsInclusiveScan:
7136 case glslang::EOpMaxInvocationsInclusiveScan:
7137 case glslang::EOpAddInvocationsInclusiveScan:
7138 case glslang::EOpMinInvocationsExclusiveScan:
7139 case glslang::EOpMaxInvocationsExclusiveScan:
7140 case glslang::EOpAddInvocationsExclusiveScan:
7141 if (op == glslang::EOpMinInvocations ||
7142 op == glslang::EOpMinInvocationsInclusiveScan ||
7143 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007144 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007145 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007146 else {
7147 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007148 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007149 else
Rex Xu51596642016-09-21 18:56:12 +08007150 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007151 }
Rex Xu430ef402016-10-14 17:22:23 +08007152 } else if (op == glslang::EOpMaxInvocations ||
7153 op == glslang::EOpMaxInvocationsInclusiveScan ||
7154 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007155 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007156 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007157 else {
7158 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007159 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007160 else
Rex Xu51596642016-09-21 18:56:12 +08007161 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007162 }
7163 } else {
7164 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007165 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007166 else
Rex Xu51596642016-09-21 18:56:12 +08007167 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007168 }
7169
Rex Xu2bbbe062016-08-23 15:41:05 +08007170 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007171 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007172
7173 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007174 case glslang::EOpMinInvocationsNonUniform:
7175 case glslang::EOpMaxInvocationsNonUniform:
7176 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007177 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7178 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7179 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7180 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7181 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7182 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7183 if (op == glslang::EOpMinInvocationsNonUniform ||
7184 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7185 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007186 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007187 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007188 else {
7189 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007190 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007191 else
Rex Xu51596642016-09-21 18:56:12 +08007192 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007193 }
7194 }
Rex Xu430ef402016-10-14 17:22:23 +08007195 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7196 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7197 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007198 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007199 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007200 else {
7201 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007202 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007203 else
Rex Xu51596642016-09-21 18:56:12 +08007204 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007205 }
7206 }
7207 else {
7208 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007209 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007210 else
Rex Xu51596642016-09-21 18:56:12 +08007211 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007212 }
7213
Rex Xu2bbbe062016-08-23 15:41:05 +08007214 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007215 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007216
7217 break;
John Kessenich91cef522016-05-05 16:45:40 -06007218 default:
7219 logger->missingFunctionality("invocation operation");
7220 return spv::NoResult;
7221 }
Rex Xu51596642016-09-21 18:56:12 +08007222
7223 assert(opCode != spv::OpNop);
7224 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007225}
7226
Rex Xu2bbbe062016-08-23 15:41:05 +08007227// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007228spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7229 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007230{
7231 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7232 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007233 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007234 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007235 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7236 op == spv::OpGroupSMinNonUniformAMD ||
7237 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7238 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007239 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7240
7241 // Handle group invocation operations scalar by scalar.
7242 // The result type is the same type as the original type.
7243 // The algorithm is to:
7244 // - break the vector into scalars
7245 // - apply the operation to each scalar
7246 // - make a vector out the scalar results
7247
7248 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007249 int numComponents = builder.getNumComponents(operands[0]);
7250 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007251 std::vector<spv::Id> results;
7252
7253 // do each scalar op
7254 for (int comp = 0; comp < numComponents; ++comp) {
7255 std::vector<unsigned int> indexes;
7256 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007257 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7258 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007259 if (op == spv::OpSubgroupReadInvocationKHR) {
7260 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007261 spv::IdImmediate operand = { true, operands[1] };
7262 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007263 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007264 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7265 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007266 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007267 spv::IdImmediate operand = { true, operands[1] };
7268 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007269 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007270 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7271 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007272 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007273 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007274 spvGroupOperands.push_back(scalar);
7275 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007276
Rex Xub7072052016-09-26 15:53:40 +08007277 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007278 }
7279
7280 // put the pieces together
7281 return builder.createCompositeConstruct(typeId, results);
7282}
Rex Xu2bbbe062016-08-23 15:41:05 +08007283
John Kessenich66011cb2018-03-06 16:12:04 -07007284// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007285spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7286 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007287{
7288 // Add the required capabilities.
7289 switch (op) {
7290 case glslang::EOpSubgroupElect:
7291 builder.addCapability(spv::CapabilityGroupNonUniform);
7292 break;
7293 case glslang::EOpSubgroupAll:
7294 case glslang::EOpSubgroupAny:
7295 case glslang::EOpSubgroupAllEqual:
7296 builder.addCapability(spv::CapabilityGroupNonUniform);
7297 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7298 break;
7299 case glslang::EOpSubgroupBroadcast:
7300 case glslang::EOpSubgroupBroadcastFirst:
7301 case glslang::EOpSubgroupBallot:
7302 case glslang::EOpSubgroupInverseBallot:
7303 case glslang::EOpSubgroupBallotBitExtract:
7304 case glslang::EOpSubgroupBallotBitCount:
7305 case glslang::EOpSubgroupBallotInclusiveBitCount:
7306 case glslang::EOpSubgroupBallotExclusiveBitCount:
7307 case glslang::EOpSubgroupBallotFindLSB:
7308 case glslang::EOpSubgroupBallotFindMSB:
7309 builder.addCapability(spv::CapabilityGroupNonUniform);
7310 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7311 break;
7312 case glslang::EOpSubgroupShuffle:
7313 case glslang::EOpSubgroupShuffleXor:
7314 builder.addCapability(spv::CapabilityGroupNonUniform);
7315 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7316 break;
7317 case glslang::EOpSubgroupShuffleUp:
7318 case glslang::EOpSubgroupShuffleDown:
7319 builder.addCapability(spv::CapabilityGroupNonUniform);
7320 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7321 break;
7322 case glslang::EOpSubgroupAdd:
7323 case glslang::EOpSubgroupMul:
7324 case glslang::EOpSubgroupMin:
7325 case glslang::EOpSubgroupMax:
7326 case glslang::EOpSubgroupAnd:
7327 case glslang::EOpSubgroupOr:
7328 case glslang::EOpSubgroupXor:
7329 case glslang::EOpSubgroupInclusiveAdd:
7330 case glslang::EOpSubgroupInclusiveMul:
7331 case glslang::EOpSubgroupInclusiveMin:
7332 case glslang::EOpSubgroupInclusiveMax:
7333 case glslang::EOpSubgroupInclusiveAnd:
7334 case glslang::EOpSubgroupInclusiveOr:
7335 case glslang::EOpSubgroupInclusiveXor:
7336 case glslang::EOpSubgroupExclusiveAdd:
7337 case glslang::EOpSubgroupExclusiveMul:
7338 case glslang::EOpSubgroupExclusiveMin:
7339 case glslang::EOpSubgroupExclusiveMax:
7340 case glslang::EOpSubgroupExclusiveAnd:
7341 case glslang::EOpSubgroupExclusiveOr:
7342 case glslang::EOpSubgroupExclusiveXor:
7343 builder.addCapability(spv::CapabilityGroupNonUniform);
7344 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7345 break;
7346 case glslang::EOpSubgroupClusteredAdd:
7347 case glslang::EOpSubgroupClusteredMul:
7348 case glslang::EOpSubgroupClusteredMin:
7349 case glslang::EOpSubgroupClusteredMax:
7350 case glslang::EOpSubgroupClusteredAnd:
7351 case glslang::EOpSubgroupClusteredOr:
7352 case glslang::EOpSubgroupClusteredXor:
7353 builder.addCapability(spv::CapabilityGroupNonUniform);
7354 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7355 break;
7356 case glslang::EOpSubgroupQuadBroadcast:
7357 case glslang::EOpSubgroupQuadSwapHorizontal:
7358 case glslang::EOpSubgroupQuadSwapVertical:
7359 case glslang::EOpSubgroupQuadSwapDiagonal:
7360 builder.addCapability(spv::CapabilityGroupNonUniform);
7361 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7362 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007363 case glslang::EOpSubgroupPartitionedAdd:
7364 case glslang::EOpSubgroupPartitionedMul:
7365 case glslang::EOpSubgroupPartitionedMin:
7366 case glslang::EOpSubgroupPartitionedMax:
7367 case glslang::EOpSubgroupPartitionedAnd:
7368 case glslang::EOpSubgroupPartitionedOr:
7369 case glslang::EOpSubgroupPartitionedXor:
7370 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7371 case glslang::EOpSubgroupPartitionedInclusiveMul:
7372 case glslang::EOpSubgroupPartitionedInclusiveMin:
7373 case glslang::EOpSubgroupPartitionedInclusiveMax:
7374 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7375 case glslang::EOpSubgroupPartitionedInclusiveOr:
7376 case glslang::EOpSubgroupPartitionedInclusiveXor:
7377 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7378 case glslang::EOpSubgroupPartitionedExclusiveMul:
7379 case glslang::EOpSubgroupPartitionedExclusiveMin:
7380 case glslang::EOpSubgroupPartitionedExclusiveMax:
7381 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7382 case glslang::EOpSubgroupPartitionedExclusiveOr:
7383 case glslang::EOpSubgroupPartitionedExclusiveXor:
7384 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7385 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7386 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007387 default: assert(0 && "Unhandled subgroup operation!");
7388 }
7389
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007390
7391 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7392 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007393 const bool isBool = typeProxy == glslang::EbtBool;
7394
7395 spv::Op opCode = spv::OpNop;
7396
7397 // Figure out which opcode to use.
7398 switch (op) {
7399 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7400 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7401 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7402 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7403 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7404 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7405 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7406 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7407 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7408 case glslang::EOpSubgroupBallotBitCount:
7409 case glslang::EOpSubgroupBallotInclusiveBitCount:
7410 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7411 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7412 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7413 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7414 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7415 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7416 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7417 case glslang::EOpSubgroupAdd:
7418 case glslang::EOpSubgroupInclusiveAdd:
7419 case glslang::EOpSubgroupExclusiveAdd:
7420 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007421 case glslang::EOpSubgroupPartitionedAdd:
7422 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7423 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007424 if (isFloat) {
7425 opCode = spv::OpGroupNonUniformFAdd;
7426 } else {
7427 opCode = spv::OpGroupNonUniformIAdd;
7428 }
7429 break;
7430 case glslang::EOpSubgroupMul:
7431 case glslang::EOpSubgroupInclusiveMul:
7432 case glslang::EOpSubgroupExclusiveMul:
7433 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007434 case glslang::EOpSubgroupPartitionedMul:
7435 case glslang::EOpSubgroupPartitionedInclusiveMul:
7436 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007437 if (isFloat) {
7438 opCode = spv::OpGroupNonUniformFMul;
7439 } else {
7440 opCode = spv::OpGroupNonUniformIMul;
7441 }
7442 break;
7443 case glslang::EOpSubgroupMin:
7444 case glslang::EOpSubgroupInclusiveMin:
7445 case glslang::EOpSubgroupExclusiveMin:
7446 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007447 case glslang::EOpSubgroupPartitionedMin:
7448 case glslang::EOpSubgroupPartitionedInclusiveMin:
7449 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007450 if (isFloat) {
7451 opCode = spv::OpGroupNonUniformFMin;
7452 } else if (isUnsigned) {
7453 opCode = spv::OpGroupNonUniformUMin;
7454 } else {
7455 opCode = spv::OpGroupNonUniformSMin;
7456 }
7457 break;
7458 case glslang::EOpSubgroupMax:
7459 case glslang::EOpSubgroupInclusiveMax:
7460 case glslang::EOpSubgroupExclusiveMax:
7461 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007462 case glslang::EOpSubgroupPartitionedMax:
7463 case glslang::EOpSubgroupPartitionedInclusiveMax:
7464 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007465 if (isFloat) {
7466 opCode = spv::OpGroupNonUniformFMax;
7467 } else if (isUnsigned) {
7468 opCode = spv::OpGroupNonUniformUMax;
7469 } else {
7470 opCode = spv::OpGroupNonUniformSMax;
7471 }
7472 break;
7473 case glslang::EOpSubgroupAnd:
7474 case glslang::EOpSubgroupInclusiveAnd:
7475 case glslang::EOpSubgroupExclusiveAnd:
7476 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007477 case glslang::EOpSubgroupPartitionedAnd:
7478 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7479 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007480 if (isBool) {
7481 opCode = spv::OpGroupNonUniformLogicalAnd;
7482 } else {
7483 opCode = spv::OpGroupNonUniformBitwiseAnd;
7484 }
7485 break;
7486 case glslang::EOpSubgroupOr:
7487 case glslang::EOpSubgroupInclusiveOr:
7488 case glslang::EOpSubgroupExclusiveOr:
7489 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007490 case glslang::EOpSubgroupPartitionedOr:
7491 case glslang::EOpSubgroupPartitionedInclusiveOr:
7492 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007493 if (isBool) {
7494 opCode = spv::OpGroupNonUniformLogicalOr;
7495 } else {
7496 opCode = spv::OpGroupNonUniformBitwiseOr;
7497 }
7498 break;
7499 case glslang::EOpSubgroupXor:
7500 case glslang::EOpSubgroupInclusiveXor:
7501 case glslang::EOpSubgroupExclusiveXor:
7502 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007503 case glslang::EOpSubgroupPartitionedXor:
7504 case glslang::EOpSubgroupPartitionedInclusiveXor:
7505 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007506 if (isBool) {
7507 opCode = spv::OpGroupNonUniformLogicalXor;
7508 } else {
7509 opCode = spv::OpGroupNonUniformBitwiseXor;
7510 }
7511 break;
7512 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7513 case glslang::EOpSubgroupQuadSwapHorizontal:
7514 case glslang::EOpSubgroupQuadSwapVertical:
7515 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7516 default: assert(0 && "Unhandled subgroup operation!");
7517 }
7518
John Kessenich149afc32018-08-14 13:31:43 -06007519 // get the right Group Operation
7520 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007521 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007522 default:
7523 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007524 case glslang::EOpSubgroupBallotBitCount:
7525 case glslang::EOpSubgroupAdd:
7526 case glslang::EOpSubgroupMul:
7527 case glslang::EOpSubgroupMin:
7528 case glslang::EOpSubgroupMax:
7529 case glslang::EOpSubgroupAnd:
7530 case glslang::EOpSubgroupOr:
7531 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007532 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007533 break;
7534 case glslang::EOpSubgroupBallotInclusiveBitCount:
7535 case glslang::EOpSubgroupInclusiveAdd:
7536 case glslang::EOpSubgroupInclusiveMul:
7537 case glslang::EOpSubgroupInclusiveMin:
7538 case glslang::EOpSubgroupInclusiveMax:
7539 case glslang::EOpSubgroupInclusiveAnd:
7540 case glslang::EOpSubgroupInclusiveOr:
7541 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007542 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007543 break;
7544 case glslang::EOpSubgroupBallotExclusiveBitCount:
7545 case glslang::EOpSubgroupExclusiveAdd:
7546 case glslang::EOpSubgroupExclusiveMul:
7547 case glslang::EOpSubgroupExclusiveMin:
7548 case glslang::EOpSubgroupExclusiveMax:
7549 case glslang::EOpSubgroupExclusiveAnd:
7550 case glslang::EOpSubgroupExclusiveOr:
7551 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007552 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007553 break;
7554 case glslang::EOpSubgroupClusteredAdd:
7555 case glslang::EOpSubgroupClusteredMul:
7556 case glslang::EOpSubgroupClusteredMin:
7557 case glslang::EOpSubgroupClusteredMax:
7558 case glslang::EOpSubgroupClusteredAnd:
7559 case glslang::EOpSubgroupClusteredOr:
7560 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007561 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007562 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007563 case glslang::EOpSubgroupPartitionedAdd:
7564 case glslang::EOpSubgroupPartitionedMul:
7565 case glslang::EOpSubgroupPartitionedMin:
7566 case glslang::EOpSubgroupPartitionedMax:
7567 case glslang::EOpSubgroupPartitionedAnd:
7568 case glslang::EOpSubgroupPartitionedOr:
7569 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007570 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007571 break;
7572 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7573 case glslang::EOpSubgroupPartitionedInclusiveMul:
7574 case glslang::EOpSubgroupPartitionedInclusiveMin:
7575 case glslang::EOpSubgroupPartitionedInclusiveMax:
7576 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7577 case glslang::EOpSubgroupPartitionedInclusiveOr:
7578 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007579 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007580 break;
7581 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7582 case glslang::EOpSubgroupPartitionedExclusiveMul:
7583 case glslang::EOpSubgroupPartitionedExclusiveMin:
7584 case glslang::EOpSubgroupPartitionedExclusiveMax:
7585 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7586 case glslang::EOpSubgroupPartitionedExclusiveOr:
7587 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007588 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007589 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007590 }
7591
John Kessenich149afc32018-08-14 13:31:43 -06007592 // build the instruction
7593 std::vector<spv::IdImmediate> spvGroupOperands;
7594
7595 // Every operation begins with the Execution Scope operand.
7596 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7597 spvGroupOperands.push_back(executionScope);
7598
7599 // Next, for all operations that use a Group Operation, push that as an operand.
7600 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007601 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007602 spvGroupOperands.push_back(groupOperand);
7603 }
7604
John Kessenich66011cb2018-03-06 16:12:04 -07007605 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007606 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7607 spv::IdImmediate operand = { true, *opIt };
7608 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007609 }
7610
7611 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007612 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007613 switch (op) {
7614 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007615 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7616 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7617 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7618 }
7619 if (directionId != spv::NoResult) {
7620 spv::IdImmediate direction = { true, directionId };
7621 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007622 }
7623
7624 return builder.createOp(opCode, typeId, spvGroupOperands);
7625}
7626
John Kessenich8985fc92020-03-03 10:25:07 -07007627spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7628 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007629{
John Kessenich66011cb2018-03-06 16:12:04 -07007630 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7631 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007632
John Kessenich140f3df2015-06-26 16:58:36 -06007633 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007634 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007635 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007636 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007637 spv::Id typeId0 = 0;
7638 if (consumedOperands > 0)
7639 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007640 spv::Id typeId1 = 0;
7641 if (consumedOperands > 1)
7642 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007643 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007644
7645 switch (op) {
7646 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007647 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007648 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007649 else if (isUnsigned)
7650 libCall = spv::GLSLstd450UMin;
7651 else
7652 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007653 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007654 break;
7655 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007656 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007657 break;
7658 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007659 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007660 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007661 else if (isUnsigned)
7662 libCall = spv::GLSLstd450UMax;
7663 else
7664 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007665 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007666 break;
7667 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007668 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007669 break;
7670 case glslang::EOpDot:
7671 opCode = spv::OpDot;
7672 break;
7673 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007674 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007675 break;
7676
7677 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007678 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007679 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007680 else if (isUnsigned)
7681 libCall = spv::GLSLstd450UClamp;
7682 else
7683 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007684 builder.promoteScalar(precision, operands.front(), operands[1]);
7685 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007686 break;
7687 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007688 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7689 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007690 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007691 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007692 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007693 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007694 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007695 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007696 break;
7697 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007698 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007699 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007700 break;
7701 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007702 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007703 builder.promoteScalar(precision, operands[0], operands[2]);
7704 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007705 break;
7706
7707 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007708 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007709 break;
7710 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007711 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007712 break;
7713 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007714 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007715 break;
7716 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007717 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007718 break;
7719 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007720 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007721 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007722 case glslang::EOpBarrier:
7723 {
7724 // This is for the extended controlBarrier function, with four operands.
7725 // The unextended barrier() goes through createNoArgOperation.
7726 assert(operands.size() == 4);
7727 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7728 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7729 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007730 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7731 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007732 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7733 spv::MemorySemanticsMakeVisibleKHRMask |
7734 spv::MemorySemanticsOutputMemoryKHRMask |
7735 spv::MemorySemanticsVolatileMask)) {
7736 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7737 }
John Kessenich8985fc92020-03-03 10:25:07 -07007738 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7739 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007740 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7741 }
7742 return 0;
7743 }
7744 break;
7745 case glslang::EOpMemoryBarrier:
7746 {
7747 // This is for the extended memoryBarrier function, with three operands.
7748 // The unextended memoryBarrier() goes through createNoArgOperation.
7749 assert(operands.size() == 3);
7750 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7751 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7752 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7753 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7754 spv::MemorySemanticsMakeVisibleKHRMask |
7755 spv::MemorySemanticsOutputMemoryKHRMask |
7756 spv::MemorySemanticsVolatileMask)) {
7757 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7758 }
7759 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7760 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7761 }
7762 return 0;
7763 }
7764 break;
7765
John Kessenicha28f7a72019-08-06 07:00:58 -06007766#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007767 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007768 if (typeProxy == glslang::EbtFloat16)
7769 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007770 libCall = spv::GLSLstd450InterpolateAtSample;
7771 break;
7772 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007773 if (typeProxy == glslang::EbtFloat16)
7774 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007775 libCall = spv::GLSLstd450InterpolateAtOffset;
7776 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007777 case glslang::EOpAddCarry:
7778 opCode = spv::OpIAddCarry;
7779 typeId = builder.makeStructResultType(typeId0, typeId0);
7780 consumedOperands = 2;
7781 break;
7782 case glslang::EOpSubBorrow:
7783 opCode = spv::OpISubBorrow;
7784 typeId = builder.makeStructResultType(typeId0, typeId0);
7785 consumedOperands = 2;
7786 break;
7787 case glslang::EOpUMulExtended:
7788 opCode = spv::OpUMulExtended;
7789 typeId = builder.makeStructResultType(typeId0, typeId0);
7790 consumedOperands = 2;
7791 break;
7792 case glslang::EOpIMulExtended:
7793 opCode = spv::OpSMulExtended;
7794 typeId = builder.makeStructResultType(typeId0, typeId0);
7795 consumedOperands = 2;
7796 break;
7797 case glslang::EOpBitfieldExtract:
7798 if (isUnsigned)
7799 opCode = spv::OpBitFieldUExtract;
7800 else
7801 opCode = spv::OpBitFieldSExtract;
7802 break;
7803 case glslang::EOpBitfieldInsert:
7804 opCode = spv::OpBitFieldInsert;
7805 break;
7806
7807 case glslang::EOpFma:
7808 libCall = spv::GLSLstd450Fma;
7809 break;
7810 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007811 {
7812 libCall = spv::GLSLstd450FrexpStruct;
7813 assert(builder.isPointerType(typeId1));
7814 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007815 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007816 if (width == 16)
7817 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7818 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007819 if (builder.getNumComponents(operands[0]) == 1)
7820 frexpIntType = builder.makeIntegerType(width, true);
7821 else
John Kessenich8985fc92020-03-03 10:25:07 -07007822 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7823 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007824 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7825 consumedOperands = 1;
7826 }
John Kessenich55e7d112015-11-15 21:33:39 -07007827 break;
7828 case glslang::EOpLdexp:
7829 libCall = spv::GLSLstd450Ldexp;
7830 break;
7831
Rex Xu574ab042016-04-14 16:53:07 +08007832 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007833 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007834
John Kessenich66011cb2018-03-06 16:12:04 -07007835 case glslang::EOpSubgroupBroadcast:
7836 case glslang::EOpSubgroupBallotBitExtract:
7837 case glslang::EOpSubgroupShuffle:
7838 case glslang::EOpSubgroupShuffleXor:
7839 case glslang::EOpSubgroupShuffleUp:
7840 case glslang::EOpSubgroupShuffleDown:
7841 case glslang::EOpSubgroupClusteredAdd:
7842 case glslang::EOpSubgroupClusteredMul:
7843 case glslang::EOpSubgroupClusteredMin:
7844 case glslang::EOpSubgroupClusteredMax:
7845 case glslang::EOpSubgroupClusteredAnd:
7846 case glslang::EOpSubgroupClusteredOr:
7847 case glslang::EOpSubgroupClusteredXor:
7848 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007849 case glslang::EOpSubgroupPartitionedAdd:
7850 case glslang::EOpSubgroupPartitionedMul:
7851 case glslang::EOpSubgroupPartitionedMin:
7852 case glslang::EOpSubgroupPartitionedMax:
7853 case glslang::EOpSubgroupPartitionedAnd:
7854 case glslang::EOpSubgroupPartitionedOr:
7855 case glslang::EOpSubgroupPartitionedXor:
7856 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7857 case glslang::EOpSubgroupPartitionedInclusiveMul:
7858 case glslang::EOpSubgroupPartitionedInclusiveMin:
7859 case glslang::EOpSubgroupPartitionedInclusiveMax:
7860 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7861 case glslang::EOpSubgroupPartitionedInclusiveOr:
7862 case glslang::EOpSubgroupPartitionedInclusiveXor:
7863 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7864 case glslang::EOpSubgroupPartitionedExclusiveMul:
7865 case glslang::EOpSubgroupPartitionedExclusiveMin:
7866 case glslang::EOpSubgroupPartitionedExclusiveMax:
7867 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7868 case glslang::EOpSubgroupPartitionedExclusiveOr:
7869 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007870 return createSubgroupOperation(op, typeId, operands, typeProxy);
7871
Rex Xu9d93a232016-05-05 12:30:44 +08007872 case glslang::EOpSwizzleInvocations:
7873 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7874 libCall = spv::SwizzleInvocationsAMD;
7875 break;
7876 case glslang::EOpSwizzleInvocationsMasked:
7877 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7878 libCall = spv::SwizzleInvocationsMaskedAMD;
7879 break;
7880 case glslang::EOpWriteInvocation:
7881 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7882 libCall = spv::WriteInvocationAMD;
7883 break;
7884
7885 case glslang::EOpMin3:
7886 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7887 if (isFloat)
7888 libCall = spv::FMin3AMD;
7889 else {
7890 if (isUnsigned)
7891 libCall = spv::UMin3AMD;
7892 else
7893 libCall = spv::SMin3AMD;
7894 }
7895 break;
7896 case glslang::EOpMax3:
7897 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7898 if (isFloat)
7899 libCall = spv::FMax3AMD;
7900 else {
7901 if (isUnsigned)
7902 libCall = spv::UMax3AMD;
7903 else
7904 libCall = spv::SMax3AMD;
7905 }
7906 break;
7907 case glslang::EOpMid3:
7908 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7909 if (isFloat)
7910 libCall = spv::FMid3AMD;
7911 else {
7912 if (isUnsigned)
7913 libCall = spv::UMid3AMD;
7914 else
7915 libCall = spv::SMid3AMD;
7916 }
7917 break;
7918
7919 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007920 if (typeProxy == glslang::EbtFloat16)
7921 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007922 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7923 libCall = spv::InterpolateAtVertexAMD;
7924 break;
Chao Chen3c366992018-09-19 11:41:59 -07007925
Daniel Kochdb32b242020-03-17 20:42:47 -04007926 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007927 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007928 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007929 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05007930 case glslang::EOpTraceNV:
7931 builder.createNoResultOp(spv::OpTraceNV, operands);
7932 return 0;
7933 case glslang::EOpTraceKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007934 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007935 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05007936 case glslang::EOpExecuteCallableNV:
7937 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
7938 return 0;
7939 case glslang::EOpExecuteCallableKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007940 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007941 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007942
7943 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007944 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7945 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007946 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007947 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7948 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007949 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007950 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7951 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007952 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007953 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7954 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007955 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007956 typeId = builder.makeBoolType();
7957 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007958 break;
7959 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007960 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007961 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007962 break;
7963 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007964 typeId = builder.makeFloatType(32);
7965 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007966 break;
7967 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007968 typeId = builder.makeIntType(32);
7969 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007970 break;
7971 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007972 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007973 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007974 break;
7975 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007976 typeId = builder.makeIntType(32);
7977 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007978 break;
7979 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007980 typeId = builder.makeIntType(32);
7981 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007982 break;
7983 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007984 typeId = builder.makeIntType(32);
7985 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007986 break;
7987 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007988 typeId = builder.makeIntType(32);
7989 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007990 break;
7991 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007992 typeId = builder.makeIntType(32);
7993 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007994 break;
7995 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007996 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7997 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007998 break;
7999 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04008000 typeId = builder.makeBoolType();
8001 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008002 break;
8003 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04008004 typeId = builder.makeBoolType();
8005 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008006 break;
8007 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008008 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8009 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008010 break;
8011 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008012 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8013 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008014 break;
8015 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008016 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8017 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008018 break;
8019 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008020 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8021 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008022 break;
8023 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04008024 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008025 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008026 break;
8027 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04008028 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008029 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008030 break;
Chao Chen3c366992018-09-19 11:41:59 -07008031 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
8032 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
8033 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008034 case glslang::EOpCooperativeMatrixMulAdd:
8035 opCode = spv::OpCooperativeMatrixMulAddNV;
8036 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06008037#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06008038 default:
8039 return 0;
8040 }
8041
8042 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07008043 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05008044 // Use an extended instruction from the standard library.
8045 // Construct the call arguments, without modifying the original operands vector.
8046 // We might need the remaining arguments, e.g. in the EOpFrexp case.
8047 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08008048 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01008049 } else if (opCode == spv::OpDot && !isFloat) {
8050 // int dot(int, int)
8051 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
8052 const int componentCount = builder.getNumComponents(operands[0]);
8053 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
8054 builder.setPrecision(mulOp, precision);
8055 id = builder.createCompositeExtract(mulOp, typeId, 0);
8056 for (int i = 1; i < componentCount; ++i) {
8057 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07008058 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01008059 }
John Kessenich2359bd02015-12-06 19:29:11 -07008060 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07008061 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06008062 case 0:
8063 // should all be handled by visitAggregate and createNoArgOperation
8064 assert(0);
8065 return 0;
8066 case 1:
8067 // should all be handled by createUnaryOperation
8068 assert(0);
8069 return 0;
8070 case 2:
8071 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
8072 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008073 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008074 // anything 3 or over doesn't have l-value operands, so all should be consumed
8075 assert(consumedOperands == operands.size());
8076 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06008077 break;
8078 }
8079 }
8080
John Kessenichb9197c82019-08-11 07:41:45 -06008081#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07008082 // Decode the return types that were structures
8083 switch (op) {
8084 case glslang::EOpAddCarry:
8085 case glslang::EOpSubBorrow:
8086 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8087 id = builder.createCompositeExtract(id, typeId0, 0);
8088 break;
8089 case glslang::EOpUMulExtended:
8090 case glslang::EOpIMulExtended:
8091 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
8092 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8093 break;
8094 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08008095 {
8096 assert(operands.size() == 2);
8097 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
8098 // "exp" is floating-point type (from HLSL intrinsic)
8099 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
8100 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
8101 builder.createStore(member1, operands[1]);
8102 } else
8103 // "exp" is integer type (from GLSL built-in function)
8104 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
8105 id = builder.createCompositeExtract(id, typeId0, 0);
8106 }
John Kessenich55e7d112015-11-15 21:33:39 -07008107 break;
8108 default:
8109 break;
8110 }
John Kessenichb9197c82019-08-11 07:41:45 -06008111#endif
John Kessenich55e7d112015-11-15 21:33:39 -07008112
John Kessenich32cfd492016-02-02 12:37:46 -07008113 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06008114}
8115
Rex Xu9d93a232016-05-05 12:30:44 +08008116// Intrinsics with no arguments (or no return value, and no precision).
8117spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06008118{
Jeff Bolz36831c92018-09-05 10:11:41 -05008119 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07008120 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
8121 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06008122
8123 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06008124 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008125 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05008126 if (glslangIntermediate->usingVulkanMemoryModel()) {
8127 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8128 spv::MemorySemanticsOutputMemoryKHRMask |
8129 spv::MemorySemanticsAcquireReleaseMask);
8130 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
8131 } else {
8132 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
8133 }
John Kessenich82979362017-12-11 04:02:24 -07008134 } else {
8135 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8136 spv::MemorySemanticsWorkgroupMemoryMask |
8137 spv::MemorySemanticsAcquireReleaseMask);
8138 }
John Kessenich140f3df2015-06-26 16:58:36 -06008139 return 0;
8140 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008141 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8142 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008143 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008144 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008145 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8146 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008147 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008148 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008149 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8150 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008151 return 0;
8152 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008153 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8154 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008155 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008156#ifndef GLSLANG_WEB
8157 case glslang::EOpMemoryBarrierAtomicCounter:
8158 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8159 spv::MemorySemanticsAcquireReleaseMask);
8160 return 0;
8161 case glslang::EOpMemoryBarrierImage:
8162 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8163 spv::MemorySemanticsAcquireReleaseMask);
8164 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008165 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008166 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008167 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008168 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008169 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008170 case glslang::EOpDeviceMemoryBarrier:
8171 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8172 spv::MemorySemanticsImageMemoryMask |
8173 spv::MemorySemanticsAcquireReleaseMask);
8174 return 0;
8175 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8176 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8177 spv::MemorySemanticsImageMemoryMask |
8178 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008179 return 0;
8180 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008181 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8182 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008183 return 0;
8184 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008185 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8186 spv::MemorySemanticsWorkgroupMemoryMask |
8187 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008188 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008189 case glslang::EOpSubgroupBarrier:
8190 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8191 spv::MemorySemanticsAcquireReleaseMask);
8192 return spv::NoResult;
8193 case glslang::EOpSubgroupMemoryBarrier:
8194 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8195 spv::MemorySemanticsAcquireReleaseMask);
8196 return spv::NoResult;
8197 case glslang::EOpSubgroupMemoryBarrierBuffer:
8198 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8199 spv::MemorySemanticsAcquireReleaseMask);
8200 return spv::NoResult;
8201 case glslang::EOpSubgroupMemoryBarrierImage:
8202 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8203 spv::MemorySemanticsAcquireReleaseMask);
8204 return spv::NoResult;
8205 case glslang::EOpSubgroupMemoryBarrierShared:
8206 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8207 spv::MemorySemanticsAcquireReleaseMask);
8208 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008209
8210 case glslang::EOpEmitVertex:
8211 builder.createNoResultOp(spv::OpEmitVertex);
8212 return 0;
8213 case glslang::EOpEndPrimitive:
8214 builder.createNoResultOp(spv::OpEndPrimitive);
8215 return 0;
8216
John Kessenich66011cb2018-03-06 16:12:04 -07008217 case glslang::EOpSubgroupElect: {
8218 std::vector<spv::Id> operands;
8219 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8220 }
Rex Xu9d93a232016-05-05 12:30:44 +08008221 case glslang::EOpTime:
8222 {
8223 std::vector<spv::Id> args; // Dummy arguments
8224 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8225 return builder.setPrecision(id, precision);
8226 }
Daniel Kochffccefd2020-11-23 15:41:27 -05008227 case glslang::EOpIgnoreIntersectionNV:
8228 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008229 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05008230 case glslang::EOpTerminateRayNV:
8231 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008232 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008233 case glslang::EOpRayQueryInitialize:
8234 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8235 return 0;
8236 case glslang::EOpRayQueryTerminate:
8237 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8238 return 0;
8239 case glslang::EOpRayQueryGenerateIntersection:
8240 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8241 return 0;
8242 case glslang::EOpRayQueryConfirmIntersection:
8243 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8244 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008245 case glslang::EOpBeginInvocationInterlock:
8246 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8247 return 0;
8248 case glslang::EOpEndInvocationInterlock:
8249 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8250 return 0;
8251
Jeff Bolzba6170b2019-07-01 09:23:23 -05008252 case glslang::EOpIsHelperInvocation:
8253 {
8254 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008255 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8256 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8257 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008258 }
8259
amhagan91fb0092019-07-10 21:14:38 -04008260 case glslang::EOpReadClockSubgroupKHR: {
8261 std::vector<spv::Id> args;
8262 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8263 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8264 builder.addCapability(spv::CapabilityShaderClockKHR);
8265 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8266 }
8267
8268 case glslang::EOpReadClockDeviceKHR: {
8269 std::vector<spv::Id> args;
8270 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8271 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8272 builder.addCapability(spv::CapabilityShaderClockKHR);
8273 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8274 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008275#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008276 default:
John Kessenich155d3512019-08-08 23:29:20 -06008277 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008278 }
John Kessenich155d3512019-08-08 23:29:20 -06008279
8280 logger->missingFunctionality("unknown operation with no arguments");
8281
8282 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008283}
8284
8285spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8286{
John Kessenich2f273362015-07-18 22:34:27 -06008287 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008288 spv::Id id;
8289 if (symbolValues.end() != iter) {
8290 id = iter->second;
8291 return id;
8292 }
8293
8294 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008295 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008296 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008297 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008298 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008299 if (forcedType.second != spv::NoType)
8300 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008301
Rex Xuc884b4a2016-06-29 15:03:44 +08008302 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008303 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8304 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8305 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008306#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008307 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008308 if (symbol->getQualifier().hasComponent())
8309 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8310 if (symbol->getQualifier().hasIndex())
8311 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008312#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008313 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008314 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008315 // atomic counters use this:
8316 if (symbol->getQualifier().hasOffset())
8317 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008318 }
8319
scygan2c864272016-05-18 18:09:17 +02008320 if (symbol->getQualifier().hasLocation())
8321 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008322 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008323 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008324 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008325 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008326 }
John Kessenich140f3df2015-06-26 16:58:36 -06008327 if (symbol->getQualifier().hasSet())
8328 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008329 else if (IsDescriptorResource(symbol->getType())) {
8330 // default to 0
8331 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8332 }
John Kessenich140f3df2015-06-26 16:58:36 -06008333 if (symbol->getQualifier().hasBinding())
8334 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008335 else if (IsDescriptorResource(symbol->getType())) {
8336 // default to 0
8337 builder.addDecoration(id, spv::DecorationBinding, 0);
8338 }
John Kessenich6c292d32016-02-15 20:58:50 -07008339 if (symbol->getQualifier().hasAttachment())
8340 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008341 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008342 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008343 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008344 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008345 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8346 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8347 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8348 }
8349 if (symbol->getQualifier().hasXfbOffset())
8350 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008351 }
8352
John Kessenichb9197c82019-08-11 07:41:45 -06008353 // add built-in variable decoration
8354 if (builtIn != spv::BuiltInMax) {
8355 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8356 }
8357
8358#ifndef GLSLANG_WEB
Daniel Kochffccefd2020-11-23 15:41:27 -05008359 // Subgroup builtins which have input storage class are volatile for ray tracing stages.
8360 if (symbol->getType().isImage() || symbol->getQualifier().isPipeInput()) {
Rex Xu1da878f2016-02-21 20:59:01 +08008361 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008362 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8363 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008364 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008365 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008366 }
8367
chaoc0ad6a4e2016-12-19 16:29:34 -08008368 if (builtIn == spv::BuiltInSampleMask) {
8369 spv::Decoration decoration;
8370 // GL_NV_sample_mask_override_coverage extension
8371 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008372 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008373 else
8374 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008375 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008376 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008377 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008378 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8379 }
8380 }
chaoc771d89f2017-01-13 01:10:53 -08008381 else if (builtIn == spv::BuiltInLayer) {
8382 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008383 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008384 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008385 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8386 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8387 }
John Kessenichb41bff62017-08-11 13:07:17 -06008388 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008389 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8390 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008391 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8392 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8393 }
8394 }
8395
chaoc6e5acae2016-12-20 13:28:52 -08008396 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008397 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008398 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008399 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8400 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008401 if (symbol->getQualifier().pervertexNV) {
8402 builder.addDecoration(id, spv::DecorationPerVertexNV);
8403 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8404 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8405 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008406
John Kessenich5d610ee2018-03-07 18:05:55 -07008407 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8408 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8409 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8410 symbol->getType().getQualifier().semanticName);
8411 }
8412
John Kessenich7015bd62019-08-01 03:28:08 -06008413 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008414 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8415 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008416 }
John Kessenichb9197c82019-08-11 07:41:45 -06008417#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008418
John Kessenich140f3df2015-06-26 16:58:36 -06008419 return id;
8420}
8421
John Kessenicha28f7a72019-08-06 07:00:58 -06008422#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008423// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8424void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8425{
8426 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008427 if (qualifier.perPrimitiveNV) {
8428 // Need to add capability/extension for fragment shader.
8429 // Mesh shader already adds this by default.
8430 if (glslangIntermediate->getStage() == EShLangFragment) {
8431 builder.addCapability(spv::CapabilityMeshShadingNV);
8432 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8433 }
Chao Chen3c366992018-09-19 11:41:59 -07008434 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008435 }
Chao Chen3c366992018-09-19 11:41:59 -07008436 if (qualifier.perViewNV)
8437 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8438 if (qualifier.perTaskNV)
8439 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8440 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008441 if (qualifier.perPrimitiveNV) {
8442 // Need to add capability/extension for fragment shader.
8443 // Mesh shader already adds this by default.
8444 if (glslangIntermediate->getStage() == EShLangFragment) {
8445 builder.addCapability(spv::CapabilityMeshShadingNV);
8446 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8447 }
Chao Chen3c366992018-09-19 11:41:59 -07008448 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008449 }
Chao Chen3c366992018-09-19 11:41:59 -07008450 if (qualifier.perViewNV)
8451 builder.addDecoration(id, spv::DecorationPerViewNV);
8452 if (qualifier.perTaskNV)
8453 builder.addDecoration(id, spv::DecorationPerTaskNV);
8454 }
8455}
8456#endif
8457
John Kessenich55e7d112015-11-15 21:33:39 -07008458// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008459// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008460//
8461// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8462//
8463// Recursively walk the nodes. The nodes form a tree whose leaves are
8464// regular constants, which themselves are trees that createSpvConstant()
8465// recursively walks. So, this function walks the "top" of the tree:
8466// - emit specialization constant-building instructions for specConstant
8467// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008468spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008469{
John Kessenich7cc0e282016-03-20 00:46:02 -06008470 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008471
qining4f4bb812016-04-03 23:55:17 -04008472 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008473 if (! node.getQualifier().specConstant) {
8474 // hand off to the non-spec-constant path
8475 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8476 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008477 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8478 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8479 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008480 }
8481
8482 // We now know we have a specialization constant to build
8483
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008484 // Extra capabilities may be needed.
8485 if (node.getType().contains8BitInt())
8486 builder.addCapability(spv::CapabilityInt8);
8487 if (node.getType().contains16BitFloat())
8488 builder.addCapability(spv::CapabilityFloat16);
8489 if (node.getType().contains16BitInt())
8490 builder.addCapability(spv::CapabilityInt16);
8491 if (node.getType().contains64BitInt())
8492 builder.addCapability(spv::CapabilityInt64);
8493 if (node.getType().containsDouble())
8494 builder.addCapability(spv::CapabilityFloat64);
8495
John Kessenichd94c0032016-05-30 19:29:40 -06008496 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008497 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8498 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8499 std::vector<spv::Id> dimConstId;
8500 for (int dim = 0; dim < 3; ++dim) {
8501 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8502 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008503 if (specConst) {
8504 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8505 glslangIntermediate->getLocalSizeSpecId(dim));
8506 }
qining4f4bb812016-04-03 23:55:17 -04008507 }
8508 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8509 }
8510
8511 // An AST node labelled as specialization constant should be a symbol node.
8512 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8513 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008514 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008515 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008516 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8517 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8518 // will set the builder into spec constant op instruction generating mode.
8519 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008520 result = accessChainLoad(sub_tree->getType());
8521 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008522 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008523 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008524 } else {
8525 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008526 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008527 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008528 builder.addName(result, sn->getName().c_str());
8529 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008530 }
qining4f4bb812016-04-03 23:55:17 -04008531
8532 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8533 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008534 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008535 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008536}
8537
John Kessenich140f3df2015-06-26 16:58:36 -06008538// Use 'consts' as the flattened glslang source of scalar constants to recursively
8539// build the aggregate SPIR-V constant.
8540//
8541// If there are not enough elements present in 'consts', 0 will be substituted;
8542// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8543//
John Kessenich8985fc92020-03-03 10:25:07 -07008544spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8545 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008546{
8547 // vector of constants for SPIR-V
8548 std::vector<spv::Id> spvConsts;
8549
8550 // Type is used for struct and array constants
8551 spv::Id typeId = convertGlslangToSpvType(glslangType);
8552
8553 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008554 glslang::TType elementType(glslangType, 0);
8555 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008556 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008557 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008558 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008559 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008560 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008561 } else if (glslangType.isCoopMat()) {
8562 glslang::TType componentType(glslangType.getBasicType());
8563 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008564 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008565 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8566 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008567 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008568 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008569 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8570 bool zero = nextConst >= consts.size();
8571 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008572 case glslang::EbtInt:
8573 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8574 break;
8575 case glslang::EbtUint:
8576 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8577 break;
8578 case glslang::EbtFloat:
8579 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8580 break;
8581 case glslang::EbtBool:
8582 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8583 break;
8584#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008585 case glslang::EbtInt8:
8586 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8587 break;
8588 case glslang::EbtUint8:
8589 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8590 break;
8591 case glslang::EbtInt16:
8592 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8593 break;
8594 case glslang::EbtUint16:
8595 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8596 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008597 case glslang::EbtInt64:
8598 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8599 break;
8600 case glslang::EbtUint64:
8601 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8602 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008603 case glslang::EbtDouble:
8604 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8605 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008606 case glslang::EbtFloat16:
8607 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8608 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008609#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008610 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008611 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008612 break;
8613 }
8614 ++nextConst;
8615 }
8616 } else {
8617 // we have a non-aggregate (scalar) constant
8618 bool zero = nextConst >= consts.size();
8619 spv::Id scalar = 0;
8620 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008621 case glslang::EbtInt:
8622 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8623 break;
8624 case glslang::EbtUint:
8625 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8626 break;
8627 case glslang::EbtFloat:
8628 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8629 break;
8630 case glslang::EbtBool:
8631 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8632 break;
8633#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008634 case glslang::EbtInt8:
8635 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8636 break;
8637 case glslang::EbtUint8:
8638 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8639 break;
8640 case glslang::EbtInt16:
8641 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8642 break;
8643 case glslang::EbtUint16:
8644 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8645 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008646 case glslang::EbtInt64:
8647 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8648 break;
8649 case glslang::EbtUint64:
8650 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8651 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008652 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008653 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008654 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008655 case glslang::EbtFloat16:
8656 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8657 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008658 case glslang::EbtReference:
8659 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8660 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8661 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008662#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008663 case glslang::EbtString:
8664 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8665 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008666 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008667 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008668 break;
8669 }
8670 ++nextConst;
8671 return scalar;
8672 }
8673
8674 return builder.makeCompositeConstant(typeId, spvConsts);
8675}
8676
John Kessenich7c1aa102015-10-15 13:29:11 -06008677// Return true if the node is a constant or symbol whose reading has no
8678// non-trivial observable cost or effect.
8679bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8680{
8681 // don't know what this is
8682 if (node == nullptr)
8683 return false;
8684
8685 // a constant is safe
8686 if (node->getAsConstantUnion() != nullptr)
8687 return true;
8688
8689 // not a symbol means non-trivial
8690 if (node->getAsSymbolNode() == nullptr)
8691 return false;
8692
8693 // a symbol, depends on what's being read
8694 switch (node->getType().getQualifier().storage) {
8695 case glslang::EvqTemporary:
8696 case glslang::EvqGlobal:
8697 case glslang::EvqIn:
8698 case glslang::EvqInOut:
8699 case glslang::EvqConst:
8700 case glslang::EvqConstReadOnly:
8701 case glslang::EvqUniform:
8702 return true;
8703 default:
8704 return false;
8705 }
qining25262b32016-05-06 17:25:16 -04008706}
John Kessenich7c1aa102015-10-15 13:29:11 -06008707
8708// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008709// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008710// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008711// Return true if trivial.
8712bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8713{
8714 if (node == nullptr)
8715 return false;
8716
John Kessenich84cc15f2017-05-24 16:44:47 -06008717 // count non scalars as trivial, as well as anything coming from HLSL
8718 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008719 return true;
8720
John Kessenich7c1aa102015-10-15 13:29:11 -06008721 // symbols and constants are trivial
8722 if (isTrivialLeaf(node))
8723 return true;
8724
8725 // otherwise, it needs to be a simple operation or one or two leaf nodes
8726
8727 // not a simple operation
8728 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8729 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8730 if (binaryNode == nullptr && unaryNode == nullptr)
8731 return false;
8732
8733 // not on leaf nodes
8734 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8735 return false;
8736
8737 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8738 return false;
8739 }
8740
8741 switch (node->getAsOperator()->getOp()) {
8742 case glslang::EOpLogicalNot:
8743 case glslang::EOpConvIntToBool:
8744 case glslang::EOpConvUintToBool:
8745 case glslang::EOpConvFloatToBool:
8746 case glslang::EOpConvDoubleToBool:
8747 case glslang::EOpEqual:
8748 case glslang::EOpNotEqual:
8749 case glslang::EOpLessThan:
8750 case glslang::EOpGreaterThan:
8751 case glslang::EOpLessThanEqual:
8752 case glslang::EOpGreaterThanEqual:
8753 case glslang::EOpIndexDirect:
8754 case glslang::EOpIndexDirectStruct:
8755 case glslang::EOpLogicalXor:
8756 case glslang::EOpAny:
8757 case glslang::EOpAll:
8758 return true;
8759 default:
8760 return false;
8761 }
8762}
8763
8764// Emit short-circuiting code, where 'right' is never evaluated unless
8765// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008766spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8767 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008768{
8769 spv::Id boolTypeId = builder.makeBoolType();
8770
8771 // emit left operand
8772 builder.clearAccessChain();
8773 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008774 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008775
8776 // Operands to accumulate OpPhi operands
8777 std::vector<spv::Id> phiOperands;
8778 // accumulate left operand's phi information
8779 phiOperands.push_back(leftId);
8780 phiOperands.push_back(builder.getBuildPoint()->getId());
8781
8782 // Make the two kinds of operation symmetric with a "!"
8783 // || => emit "if (! left) result = right"
8784 // && => emit "if ( left) result = right"
8785 //
8786 // TODO: this runtime "not" for || could be avoided by adding functionality
8787 // to 'builder' to have an "else" without an "then"
8788 if (op == glslang::EOpLogicalOr)
8789 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8790
8791 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008792 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008793
8794 // emit right operand as the "then" part of the "if"
8795 builder.clearAccessChain();
8796 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008797 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008798
8799 // accumulate left operand's phi information
8800 phiOperands.push_back(rightId);
8801 phiOperands.push_back(builder.getBuildPoint()->getId());
8802
8803 // finish the "if"
8804 ifBuilder.makeEndIf();
8805
8806 // phi together the two results
8807 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8808}
8809
John Kessenicha28f7a72019-08-06 07:00:58 -06008810#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008811// Return type Id of the imported set of extended instructions corresponds to the name.
8812// Import this set if it has not been imported yet.
8813spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8814{
8815 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8816 return extBuiltinMap[name];
8817 else {
Rex Xu51596642016-09-21 18:56:12 +08008818 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008819 spv::Id extBuiltins = builder.import(name);
8820 extBuiltinMap[name] = extBuiltins;
8821 return extBuiltins;
8822 }
8823}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008824#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008825
John Kessenich140f3df2015-06-26 16:58:36 -06008826}; // end anonymous namespace
8827
8828namespace glslang {
8829
John Kessenich68d78fd2015-07-12 19:28:10 -06008830void GetSpirvVersion(std::string& version)
8831{
John Kessenich9e55f632015-07-15 10:03:39 -06008832 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008833 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008834 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008835 version = buf;
8836}
8837
John Kessenicha372a3e2017-11-02 22:32:14 -06008838// For low-order part of the generator's magic number. Bump up
8839// when there is a change in the style (e.g., if SSA form changes,
8840// or a different instruction sequence to do something gets used).
8841int GetSpirvGeneratorVersion()
8842{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008843 // return 1; // start
8844 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008845 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008846 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008847 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008848 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8849 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008850 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008851 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008852 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8853 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008854}
8855
John Kessenich140f3df2015-06-26 16:58:36 -06008856// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008857void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008858{
8859 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008860 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008861 if (out.fail())
8862 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008863 for (int i = 0; i < (int)spirv.size(); ++i) {
8864 unsigned int word = spirv[i];
8865 out.write((const char*)&word, 4);
8866 }
8867 out.close();
8868}
8869
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008870// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008871void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008872{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008873#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008874 std::ofstream out;
8875 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008876 if (out.fail())
8877 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008878 out << "\t// " <<
8879 GetSpirvGeneratorVersion() <<
8880 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8881 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008882 if (varName != nullptr) {
8883 out << "\t #pragma once" << std::endl;
8884 out << "const uint32_t " << varName << "[] = {" << std::endl;
8885 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008886 const int WORDS_PER_LINE = 8;
8887 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8888 out << "\t";
8889 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8890 const unsigned int word = spirv[i + j];
8891 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8892 if (i + j + 1 < (int)spirv.size()) {
8893 out << ",";
8894 }
8895 }
8896 out << std::endl;
8897 }
Flavio15017db2017-02-15 14:29:33 -08008898 if (varName != nullptr) {
8899 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008900 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008901 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008902 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008903#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008904}
8905
John Kessenich140f3df2015-06-26 16:58:36 -06008906//
8907// Set up the glslang traversal
8908//
John Kessenich4e11b612018-08-30 16:56:59 -06008909void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008910{
Lei Zhang17535f72016-05-04 15:55:59 -04008911 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008912 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008913}
8914
John Kessenich4e11b612018-08-30 16:56:59 -06008915void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008916 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008917{
John Kessenich140f3df2015-06-26 16:58:36 -06008918 TIntermNode* root = intermediate.getTreeRoot();
8919
8920 if (root == 0)
8921 return;
8922
John Kessenich4e11b612018-08-30 16:56:59 -06008923 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008924 if (options == nullptr)
8925 options = &defaultOptions;
8926
John Kessenich4e11b612018-08-30 16:56:59 -06008927 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008928
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008929 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008930 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008931 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008932 it.dumpSpv(spirv);
8933
GregFfb03a552018-03-29 11:49:14 -06008934#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008935 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8936 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008937 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008938 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8939 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008940 prelegalization = false;
8941 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008942 else if (options->stripDebugInfo) {
8943 // Strip debug info even if optimization is disabled.
8944 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8945 }
John Kessenich717c80a2018-08-23 15:17:10 -06008946
John Kessenich4e11b612018-08-30 16:56:59 -06008947 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008948 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008949
John Kessenich717c80a2018-08-23 15:17:10 -06008950 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008951 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008952
GregFcd1f1692017-09-21 18:40:22 -06008953#endif
8954
John Kessenich4e11b612018-08-30 16:56:59 -06008955 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008956}
8957
8958}; // end namespace glslang