blob: 8e063f8fa548a475bd03ca358f0fb3ef50378be3 [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:
Daniel Koche11a2c82020-11-30 11:57:34 -05001009 {
1010 // this is a GLSL alias of RayTmax
1011 // in SPV_NV_ray_tracing it has a dedicated builtin
1012 // but in SPV_KHR_ray_tracing it gets mapped to RayTmax
1013 auto& extensions = glslangIntermediate->getRequestedExtensions();
1014 if (extensions.find("GL_NV_ray_tracing") != extensions.end()) {
1015 return spv::BuiltInHitTNV;
1016 } else {
1017 return spv::BuiltInRayTmaxKHR;
1018 }
1019 }
Daniel Kochdb32b242020-03-17 20:42:47 -04001020 case glslang::EbvHitKind:
1021 return spv::BuiltInHitKindKHR;
1022 case glslang::EbvObjectToWorld:
1023 case glslang::EbvObjectToWorld3x4:
1024 return spv::BuiltInObjectToWorldKHR;
1025 case glslang::EbvWorldToObject:
1026 case glslang::EbvWorldToObject3x4:
1027 return spv::BuiltInWorldToObjectKHR;
1028 case glslang::EbvIncomingRayFlags:
1029 return spv::BuiltInIncomingRayFlagsKHR;
1030 case glslang::EbvGeometryIndex:
1031 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -04001032
1033 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -07001034 case glslang::EbvBaryCoordNV:
1035 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1036 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1037 return spv::BuiltInBaryCoordNV;
1038 case glslang::EbvBaryCoordNoPerspNV:
1039 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1040 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1041 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001042
1043 // mesh shaders
1044 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001045 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001046 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001047 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001048 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001049 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001050 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001051 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001052 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001053 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001054 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001055 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001056 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001057 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001058 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001059 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001060
1061 // sm builtins
1062 case glslang::EbvWarpsPerSM:
1063 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1064 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1065 return spv::BuiltInWarpsPerSMNV;
1066 case glslang::EbvSMCount:
1067 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1068 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1069 return spv::BuiltInSMCountNV;
1070 case glslang::EbvWarpID:
1071 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1072 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1073 return spv::BuiltInWarpIDNV;
1074 case glslang::EbvSMID:
1075 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1076 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1077 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001078#endif
1079
Rex Xu3e783f92017-02-22 16:44:48 +08001080 default:
1081 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001082 }
1083}
1084
Rex Xufc618912015-09-09 16:42:49 +08001085// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001086spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001087{
1088 assert(type.getBasicType() == glslang::EbtSampler);
1089
John Kessenichb9197c82019-08-11 07:41:45 -06001090#ifdef GLSLANG_WEB
1091 return spv::ImageFormatUnknown;
1092#endif
1093
John Kessenich5d0fa972016-02-15 11:57:00 -07001094 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001095 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001096 case glslang::ElfRg32f:
1097 case glslang::ElfRg16f:
1098 case glslang::ElfR11fG11fB10f:
1099 case glslang::ElfR16f:
1100 case glslang::ElfRgba16:
1101 case glslang::ElfRgb10A2:
1102 case glslang::ElfRg16:
1103 case glslang::ElfRg8:
1104 case glslang::ElfR16:
1105 case glslang::ElfR8:
1106 case glslang::ElfRgba16Snorm:
1107 case glslang::ElfRg16Snorm:
1108 case glslang::ElfRg8Snorm:
1109 case glslang::ElfR16Snorm:
1110 case glslang::ElfR8Snorm:
1111
1112 case glslang::ElfRg32i:
1113 case glslang::ElfRg16i:
1114 case glslang::ElfRg8i:
1115 case glslang::ElfR16i:
1116 case glslang::ElfR8i:
1117
1118 case glslang::ElfRgb10a2ui:
1119 case glslang::ElfRg32ui:
1120 case glslang::ElfRg16ui:
1121 case glslang::ElfRg8ui:
1122 case glslang::ElfR16ui:
1123 case glslang::ElfR8ui:
1124 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1125 break;
1126
Tobski8c1a3a02020-11-04 16:24:23 +00001127 case glslang::ElfR64ui:
1128 case glslang::ElfR64i:
1129 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
1130 builder.addCapability(spv::CapabilityInt64ImageEXT);
John Kessenich5d0fa972016-02-15 11:57:00 -07001131 default:
1132 break;
1133 }
1134
1135 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001136 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001137 case glslang::ElfNone: return spv::ImageFormatUnknown;
1138 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1139 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1140 case glslang::ElfR32f: return spv::ImageFormatR32f;
1141 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1142 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1143 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1144 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1145 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1146 case glslang::ElfR16f: return spv::ImageFormatR16f;
1147 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1148 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1149 case glslang::ElfRg16: return spv::ImageFormatRg16;
1150 case glslang::ElfRg8: return spv::ImageFormatRg8;
1151 case glslang::ElfR16: return spv::ImageFormatR16;
1152 case glslang::ElfR8: return spv::ImageFormatR8;
1153 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1154 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1155 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1156 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1157 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1158 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1159 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1160 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1161 case glslang::ElfR32i: return spv::ImageFormatR32i;
1162 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1163 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1164 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1165 case glslang::ElfR16i: return spv::ImageFormatR16i;
1166 case glslang::ElfR8i: return spv::ImageFormatR8i;
1167 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1168 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1169 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1170 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1171 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1172 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1173 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1174 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1175 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1176 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
Tobski8c1a3a02020-11-04 16:24:23 +00001177 case glslang::ElfR64ui: return spv::ImageFormatR64ui;
1178 case glslang::ElfR64i: return spv::ImageFormatR64i;
John Kessenich4016e382016-07-15 11:53:56 -06001179 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001180 }
1181}
1182
John Kessenich8985fc92020-03-03 10:25:07 -07001183spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1184 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001185{
John Kesseniche18fd202018-01-30 11:01:39 -07001186 if (selectionNode.getFlatten())
1187 return spv::SelectionControlFlattenMask;
1188 if (selectionNode.getDontFlatten())
1189 return spv::SelectionControlDontFlattenMask;
1190 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001191}
1192
John Kessenich8985fc92020-03-03 10:25:07 -07001193spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1194 const
steve-lunargf1709e72017-05-02 20:14:50 -06001195{
John Kesseniche18fd202018-01-30 11:01:39 -07001196 if (switchNode.getFlatten())
1197 return spv::SelectionControlFlattenMask;
1198 if (switchNode.getDontFlatten())
1199 return spv::SelectionControlDontFlattenMask;
1200 return spv::SelectionControlMaskNone;
1201}
1202
John Kessenicha2858d92018-01-31 08:11:18 -07001203// return a non-0 dependency if the dependency argument must be set
1204spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001205 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001206{
1207 spv::LoopControlMask control = spv::LoopControlMaskNone;
1208
1209 if (loopNode.getDontUnroll())
1210 control = control | spv::LoopControlDontUnrollMask;
1211 if (loopNode.getUnroll())
1212 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001213 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001214 control = control | spv::LoopControlDependencyInfiniteMask;
1215 else if (loopNode.getLoopDependency() > 0) {
1216 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001217 operands.push_back((unsigned int)loopNode.getLoopDependency());
1218 }
1219 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1220 if (loopNode.getMinIterations() > 0) {
1221 control = control | spv::LoopControlMinIterationsMask;
1222 operands.push_back(loopNode.getMinIterations());
1223 }
1224 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1225 control = control | spv::LoopControlMaxIterationsMask;
1226 operands.push_back(loopNode.getMaxIterations());
1227 }
1228 if (loopNode.getIterationMultiple() > 1) {
1229 control = control | spv::LoopControlIterationMultipleMask;
1230 operands.push_back(loopNode.getIterationMultiple());
1231 }
1232 if (loopNode.getPeelCount() > 0) {
1233 control = control | spv::LoopControlPeelCountMask;
1234 operands.push_back(loopNode.getPeelCount());
1235 }
1236 if (loopNode.getPartialCount() > 0) {
1237 control = control | spv::LoopControlPartialCountMask;
1238 operands.push_back(loopNode.getPartialCount());
1239 }
John Kessenicha2858d92018-01-31 08:11:18 -07001240 }
John Kesseniche18fd202018-01-30 11:01:39 -07001241
1242 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001243}
1244
John Kessenicha5c5fb62017-05-05 05:09:58 -06001245// Translate glslang type to SPIR-V storage class.
1246spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1247{
Torosdagli06c2eee2020-03-19 11:09:57 -04001248 if (type.getBasicType() == glslang::EbtRayQuery)
Daniel Kochffccefd2020-11-23 15:41:27 -05001249 return spv::StorageClassPrivate;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001250 if (type.getQualifier().isPipeInput())
1251 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001252 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001253 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001254
1255 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001256 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001257 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001258 return spv::StorageClassAtomicCounter;
1259 if (type.containsOpaque())
1260 return spv::StorageClassUniformConstant;
1261 }
1262
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001263 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001264 type.getQualifier().isShaderRecord()) {
1265 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001266 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001267
John Kessenichbed4e4f2017-09-08 02:38:07 -06001268 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001269 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001270 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001271 }
1272
1273 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001274 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001275 return spv::StorageClassPushConstant;
1276 if (type.getBasicType() == glslang::EbtBlock)
1277 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001278 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001279 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001280
1281 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001282 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1283 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1284 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001285 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001286#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001287 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1288 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1289 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1290 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1291 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001292#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001293 default:
1294 assert(0);
1295 break;
1296 }
1297
1298 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001299}
1300
John Kessenich5611c6d2018-04-05 11:25:02 -06001301// Add capabilities pertaining to how an array is indexed.
1302void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1303 const glslang::TType& indexType)
1304{
John Kessenichb9197c82019-08-11 07:41:45 -06001305#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001306 if (indexType.getQualifier().isNonUniform()) {
1307 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001308 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001309 if (baseType.getBasicType() == glslang::EbtSampler) {
1310 if (baseType.getQualifier().hasAttachment())
1311 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001312 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001313 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001314 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001315 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1316 else if (baseType.isImage())
1317 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1318 else if (baseType.isTexture())
1319 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1320 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1321 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1322 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1323 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1324 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1325 }
1326 } else {
1327 // assume a dynamically uniform index
1328 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001329 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001330 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001331 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001332 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001333 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001334 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001335 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001336 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001337 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001338 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001339 }
1340 }
John Kessenichb9197c82019-08-11 07:41:45 -06001341#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001342}
1343
qining25262b32016-05-06 17:25:16 -04001344// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001345// descriptor set.
1346bool IsDescriptorResource(const glslang::TType& type)
1347{
John Kessenichf7497e22016-03-08 21:36:22 -07001348 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001349 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001350 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001351 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001352 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001353
1354 // non block...
1355 // basically samplerXXX/subpass/sampler/texture are all included
1356 // if they are the global-scope-class, not the function parameter
1357 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001358 if (type.getBasicType() == glslang::EbtSampler ||
1359 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001360 return type.getQualifier().isUniformOrBuffer();
1361
1362 // None of the above.
1363 return false;
1364}
1365
John Kesseniche0b6cad2015-12-24 10:30:13 -07001366void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1367{
1368 if (child.layoutMatrix == glslang::ElmNone)
1369 child.layoutMatrix = parent.layoutMatrix;
1370
1371 if (parent.invariant)
1372 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001373 if (parent.flat)
1374 child.flat = true;
1375 if (parent.centroid)
1376 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001377#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001378 if (parent.nopersp)
1379 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001380 if (parent.explicitInterp)
1381 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001382 if (parent.perPrimitiveNV)
1383 child.perPrimitiveNV = true;
1384 if (parent.perViewNV)
1385 child.perViewNV = true;
1386 if (parent.perTaskNV)
1387 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001388 if (parent.patch)
1389 child.patch = true;
1390 if (parent.sample)
1391 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001392 if (parent.coherent)
1393 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001394 if (parent.devicecoherent)
1395 child.devicecoherent = true;
1396 if (parent.queuefamilycoherent)
1397 child.queuefamilycoherent = true;
1398 if (parent.workgroupcoherent)
1399 child.workgroupcoherent = true;
1400 if (parent.subgroupcoherent)
1401 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001402 if (parent.shadercallcoherent)
1403 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001404 if (parent.nonprivate)
1405 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001406 if (parent.volatil)
1407 child.volatil = true;
1408 if (parent.restrict)
1409 child.restrict = true;
1410 if (parent.readonly)
1411 child.readonly = true;
1412 if (parent.writeonly)
1413 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001414#endif
greg-lunarg639f5462020-11-12 11:10:07 -07001415 if (parent.nonUniform)
1416 child.nonUniform = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001417}
1418
John Kessenichf2b7f332016-09-01 17:05:23 -06001419bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001420{
John Kessenich7b9fa252016-01-21 18:56:57 -07001421 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001422 // - struct members might inherit from a struct declaration
1423 // (note that non-block structs don't explicitly inherit,
1424 // only implicitly, meaning no decoration involved)
1425 // - affect decorations on the struct members
1426 // (note smooth does not, and expecting something like volatile
1427 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001428 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001429 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001430}
1431
John Kessenich140f3df2015-06-26 16:58:36 -06001432//
1433// Implement the TGlslangToSpvTraverser class.
1434//
1435
John Kessenich8985fc92020-03-03 10:25:07 -07001436TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1437 const glslang::TIntermediate* glslangIntermediate,
1438 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1439 TIntermTraverser(true, false, true),
1440 options(options),
1441 shaderEntry(nullptr), currentFunction(nullptr),
1442 sequenceDepth(0), logger(buildLogger),
1443 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1444 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1445 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001446 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1447 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001448{
1449 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1450
1451 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001452 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1453 glslangIntermediate->getVersion());
1454
John Kessenich121853f2017-05-31 17:11:16 -06001455 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001456 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001457 builder.setSourceFile(glslangIntermediate->getSourceFile());
1458
1459 // Set the source shader's text. If for SPV version 1.0, include
1460 // a preamble in comments stating the OpModuleProcessed instructions.
1461 // Otherwise, emit those as actual instructions.
1462 std::string text;
1463 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1464 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001465 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001466 text.append("// OpModuleProcessed ");
1467 text.append(processes[p]);
1468 text.append("\n");
1469 } else
1470 builder.addModuleProcessed(processes[p]);
1471 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001472 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001473 text.append("#line 1\n");
1474 text.append(glslangIntermediate->getSourceText());
1475 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001476 // Pass name and text for all included files
1477 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1478 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1479 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001480 }
John Kessenich140f3df2015-06-26 16:58:36 -06001481 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001482
1483 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1484 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1485
1486 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1487 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001488 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001489 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001490 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001491 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001492 memoryModel = spv::MemoryModelVulkanKHR;
1493 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001494 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001495 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001496 builder.setMemoryModel(addressingModel, memoryModel);
1497
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001498 if (glslangIntermediate->usingVariablePointers()) {
1499 builder.addCapability(spv::CapabilityVariablePointers);
1500 }
1501
John Kessenicheee9d532016-09-19 18:09:30 -06001502 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1503 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001506 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1507 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001508 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001509
1510 // Add the top-level modes for this shader.
1511
John Kessenich92187592016-02-01 13:45:25 -07001512 if (glslangIntermediate->getXfbMode()) {
1513 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001514 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001515 }
John Kessenich140f3df2015-06-26 16:58:36 -06001516
alelenv59216d52020-05-21 04:38:41 -07001517 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
Daniel Kochffccefd2020-11-23 15:41:27 -05001518 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingKHR);
alelenv75de1962020-04-08 21:09:20 -07001519 }
1520
John Kessenich140f3df2015-06-26 16:58:36 -06001521 unsigned int mode;
1522 switch (glslangIntermediate->getStage()) {
1523 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001524 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001525 break;
1526
John Kessenicha28f7a72019-08-06 07:00:58 -06001527 case EShLangFragment:
1528 builder.addCapability(spv::CapabilityShader);
1529 if (glslangIntermediate->getPixelCenterInteger())
1530 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1531
1532 if (glslangIntermediate->getOriginUpperLeft())
1533 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1534 else
1535 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1536
1537 if (glslangIntermediate->getEarlyFragmentTests())
1538 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1539
1540 if (glslangIntermediate->getPostDepthCoverage()) {
1541 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1542 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1543 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1544 }
1545
John Kessenichb9197c82019-08-11 07:41:45 -06001546 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1547 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1548
1549#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001550
John Kessenicha28f7a72019-08-06 07:00:58 -06001551 switch(glslangIntermediate->getDepth()) {
1552 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1553 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1554 default: mode = spv::ExecutionModeMax; break;
1555 }
1556 if (mode != spv::ExecutionModeMax)
1557 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001558 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001559 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1560 break;
1561 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1562 break;
1563 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1564 break;
1565 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1566 break;
1567 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1568 break;
1569 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1570 break;
1571 default: mode = spv::ExecutionModeMax;
1572 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001573 }
1574 if (mode != spv::ExecutionModeMax) {
1575 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1576 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1577 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1578 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1579 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1580 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1581 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1582 } else {
1583 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1584 }
1585 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1586 }
John Kessenichb9197c82019-08-11 07:41:45 -06001587#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001588 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001589
John Kessenicha28f7a72019-08-06 07:00:58 -06001590 case EShLangCompute:
1591 builder.addCapability(spv::CapabilityShader);
1592 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1593 glslangIntermediate->getLocalSize(1),
1594 glslangIntermediate->getLocalSize(2));
1595 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1596 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1598 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1599 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1600 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1601 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1602 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1603 }
1604 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001605#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001606 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001607 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001608 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001609
steve-lunarge7412492017-03-23 11:56:07 -06001610 glslang::TLayoutGeometry primitive;
1611
1612 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001613 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1614 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001615 primitive = glslangIntermediate->getOutputPrimitive();
1616 } else {
1617 primitive = glslangIntermediate->getInputPrimitive();
1618 }
1619
1620 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001621 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1622 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1623 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001624 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001625 }
John Kessenich4016e382016-07-15 11:53:56 -06001626 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001627 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1628
John Kesseniche6903322015-10-13 16:29:02 -06001629 switch (glslangIntermediate->getVertexSpacing()) {
1630 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1631 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1632 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001633 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001634 }
John Kessenich4016e382016-07-15 11:53:56 -06001635 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001636 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1637
1638 switch (glslangIntermediate->getVertexOrder()) {
1639 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1640 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001641 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001642 }
John Kessenich4016e382016-07-15 11:53:56 -06001643 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1645
1646 if (glslangIntermediate->getPointMode())
1647 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001648 break;
1649
1650 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001651 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001652 switch (glslangIntermediate->getInputPrimitive()) {
1653 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1654 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1655 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001656 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001657 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001658 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001659 }
John Kessenich4016e382016-07-15 11:53:56 -06001660 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001661 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001662
John Kessenich140f3df2015-06-26 16:58:36 -06001663 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1664
1665 switch (glslangIntermediate->getOutputPrimitive()) {
1666 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1667 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1668 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001669 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001670 }
John Kessenich4016e382016-07-15 11:53:56 -06001671 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001672 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1673 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1674 break;
1675
Daniel Kochdb32b242020-03-17 20:42:47 -04001676 case EShLangRayGen:
1677 case EShLangIntersect:
1678 case EShLangAnyHit:
1679 case EShLangClosestHit:
1680 case EShLangMiss:
1681 case EShLangCallable:
1682 {
1683 auto& extensions = glslangIntermediate->getRequestedExtensions();
1684 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
Daniel Kochffccefd2020-11-23 15:41:27 -05001685 builder.addCapability(spv::CapabilityRayTracingKHR);
Daniel Kochdb32b242020-03-17 20:42:47 -04001686 builder.addExtension("SPV_KHR_ray_tracing");
1687 }
1688 else {
1689 builder.addCapability(spv::CapabilityRayTracingNV);
1690 builder.addExtension("SPV_NV_ray_tracing");
1691 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001692 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001693 }
Chao Chen3c366992018-09-19 11:41:59 -07001694 case EShLangTaskNV:
1695 case EShLangMeshNV:
1696 builder.addCapability(spv::CapabilityMeshShadingNV);
1697 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1698 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1699 glslangIntermediate->getLocalSize(1),
1700 glslangIntermediate->getLocalSize(2));
1701 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001702 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1703 glslangIntermediate->getVertices());
1704 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1705 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001706
1707 switch (glslangIntermediate->getOutputPrimitive()) {
1708 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1709 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1710 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1711 default: mode = spv::ExecutionModeMax; break;
1712 }
1713 if (mode != spv::ExecutionModeMax)
1714 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1715 }
1716 break;
1717#endif
1718
John Kessenich140f3df2015-06-26 16:58:36 -06001719 default:
1720 break;
1721 }
John Kessenich140f3df2015-06-26 16:58:36 -06001722}
1723
John Kessenichfca82622016-11-26 13:23:20 -07001724// Finish creating SPV, after the traversal is complete.
1725void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001726{
John Kessenichf04c51b2018-08-03 15:56:12 -06001727 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001728 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001729 builder.setBuildPoint(shaderEntry->getLastBlock());
1730 builder.leaveFunction();
1731 }
1732
John Kessenich7ba63412015-12-20 17:37:07 -07001733 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001734 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1735 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001736
David Neto8c3d5b42019-10-21 14:50:31 -04001737 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001738 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001739 // Note: WebGPU code generation must have the opportunity to aggressively
1740 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001741 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001742}
1743
John Kessenichfca82622016-11-26 13:23:20 -07001744// Write the SPV into 'out'.
1745void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001746{
John Kessenichfca82622016-11-26 13:23:20 -07001747 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001748}
1749
1750//
1751// Implement the traversal functions.
1752//
1753// Return true from interior nodes to have the external traversal
1754// continue on to children. Return false if children were
1755// already processed.
1756//
1757
1758//
qining25262b32016-05-06 17:25:16 -04001759// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001760// - uniform/input reads
1761// - output writes
1762// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1763// - something simple that degenerates into the last bullet
1764//
1765void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1766{
qining75d1d802016-04-06 14:42:01 -04001767 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001768 if (symbol->getType().isStruct())
1769 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1770
qining75d1d802016-04-06 14:42:01 -04001771 if (symbol->getType().getQualifier().isSpecConstant())
1772 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1773
Rex Xuf6e0fe82020-10-23 22:54:35 +08001774#ifdef ENABLE_HLSL
1775 // Skip symbol handling if it is string-typed
1776 if (symbol->getBasicType() == glslang::EbtString)
1777 return;
1778#endif
1779
John Kessenich140f3df2015-06-26 16:58:36 -06001780 // getSymbolId() will set up all the IO decorations on the first call.
1781 // Formal function parameters were mapped during makeFunctions().
1782 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001783
John Kessenich7ba63412015-12-20 17:37:07 -07001784 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001785 if (!symbol->getType().getQualifier().isParamInput() &&
1786 !symbol->getType().getQualifier().isParamOutput()) {
1787 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1788 // Consider adding to the OpEntryPoint interface list.
1789 // Only looking at structures if they have at least one member.
1790 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1791 spv::StorageClass sc = builder.getStorageClass(id);
1792 // Before SPIR-V 1.4, we only want to include Input and Output.
1793 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001794 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001795 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1796 iOSet.insert(id);
1797 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001798 }
John Kessenich5f77d862017-09-19 11:09:59 -06001799 }
John Kessenich9c14f772019-06-17 08:38:35 -06001800
Daniel Kochdb32b242020-03-17 20:42:47 -04001801 // If the SPIR-V type is required to be different than the AST type
1802 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001803 // translate now from the SPIR-V type to the AST type, for the consuming
1804 // operation.
1805 // Note this turns it from an l-value to an r-value.
1806 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1807 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1808 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001809 }
1810
1811 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001812 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001813 // Prepare to generate code for the access
1814
1815 // L-value chains will be computed left to right. We're on the symbol now,
1816 // which is the left-most part of the access chain, so now is "clear" time,
1817 // followed by setting the base.
1818 builder.clearAccessChain();
1819
1820 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001821 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001822 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001823 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001824 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001825 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001826 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001827 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001828 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1829 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001830 builder.setAccessChainRValue(id);
1831 else
1832 builder.setAccessChainLValue(id);
1833 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001834
John Kessenichb9197c82019-08-11 07:41:45 -06001835#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001836 // Process linkage-only nodes for any special additional interface work.
1837 if (linkageOnly) {
1838 if (glslangIntermediate->getHlslFunctionality1()) {
1839 // Map implicit counter buffers to their originating buffers, which should have been
1840 // seen by now, given earlier pruning of unused counters, and preservation of order
1841 // of declaration.
1842 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1843 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1844 // Save possible originating buffers for counter buffers, keyed by
1845 // making the potential counter-buffer name.
1846 std::string keyName = symbol->getName().c_str();
1847 keyName = glslangIntermediate->addCounterBufferName(keyName);
1848 counterOriginator[keyName] = symbol;
1849 } else {
1850 // Handle a counter buffer, by finding the saved originating buffer.
1851 std::string keyName = symbol->getName().c_str();
1852 auto it = counterOriginator.find(keyName);
1853 if (it != counterOriginator.end()) {
1854 id = getSymbolId(it->second);
1855 if (id != spv::NoResult) {
1856 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001857 if (counterId != spv::NoResult) {
1858 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001859 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001860 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001861 }
1862 }
1863 }
1864 }
1865 }
1866 }
John Kessenich155d3512019-08-08 23:29:20 -06001867#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001868}
1869
1870bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1871{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001872 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001873 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1874 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1875 }
1876 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1877 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1878 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001879
qining40887662016-04-03 22:20:42 -04001880 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1881 if (node->getType().getQualifier().isSpecConstant())
1882 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1883
John Kessenich140f3df2015-06-26 16:58:36 -06001884 // First, handle special cases
1885 switch (node->getOp()) {
1886 case glslang::EOpAssign:
1887 case glslang::EOpAddAssign:
1888 case glslang::EOpSubAssign:
1889 case glslang::EOpMulAssign:
1890 case glslang::EOpVectorTimesMatrixAssign:
1891 case glslang::EOpVectorTimesScalarAssign:
1892 case glslang::EOpMatrixTimesScalarAssign:
1893 case glslang::EOpMatrixTimesMatrixAssign:
1894 case glslang::EOpDivAssign:
1895 case glslang::EOpModAssign:
1896 case glslang::EOpAndAssign:
1897 case glslang::EOpInclusiveOrAssign:
1898 case glslang::EOpExclusiveOrAssign:
1899 case glslang::EOpLeftShiftAssign:
1900 case glslang::EOpRightShiftAssign:
1901 // A bin-op assign "a += b" means the same thing as "a = a + b"
1902 // where a is evaluated before b. For a simple assignment, GLSL
1903 // says to evaluate the left before the right. So, always, left
1904 // node then right node.
1905 {
1906 // get the left l-value, save it away
1907 builder.clearAccessChain();
1908 node->getLeft()->traverse(this);
1909 spv::Builder::AccessChain lValue = builder.getAccessChain();
1910
1911 // evaluate the right
1912 builder.clearAccessChain();
1913 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001914 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001915
1916 if (node->getOp() != glslang::EOpAssign) {
1917 // the left is also an r-value
1918 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001919 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001920
1921 // do the operation
greg-lunarg639f5462020-11-12 11:10:07 -07001922 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1923 coherentFlags |= TranslateCoherent(node->getRight()->getType());
John Kessenichead86222018-03-28 18:01:20 -06001924 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001925 TranslateNoContractionDecoration(node->getType().getQualifier()),
greg-lunarg639f5462020-11-12 11:10:07 -07001926 TranslateNonUniformDecoration(coherentFlags) };
John Kessenichead86222018-03-28 18:01:20 -06001927 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001928 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1929 node->getType().getBasicType());
1930
1931 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001932 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001933 }
1934
1935 // store the result
1936 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001937 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001938
1939 // assignments are expressions having an rValue after they are evaluated...
1940 builder.clearAccessChain();
1941 builder.setAccessChainRValue(rValue);
1942 }
1943 return false;
1944 case glslang::EOpIndexDirect:
1945 case glslang::EOpIndexDirectStruct:
1946 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001947 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001948 // Get the left part of the access chain.
1949 node->getLeft()->traverse(this);
1950
1951 // Add the next element in the chain
1952
David Netoa901ffe2016-06-08 14:11:40 +01001953 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001954 if (! node->getLeft()->getType().isArray() &&
1955 node->getLeft()->getType().isVector() &&
1956 node->getOp() == glslang::EOpIndexDirect) {
greg-lunarg639f5462020-11-12 11:10:07 -07001957 // Swizzle is uniform so propagate uniform into access chain
1958 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1959 coherentFlags.nonUniform = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06001960 // This is essentially a hard-coded vector swizzle of size 1,
1961 // so short circuit the access-chain stuff with a swizzle.
1962 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001963 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001964 int dummySize;
1965 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
greg-lunarg639f5462020-11-12 11:10:07 -07001966 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07001967 glslangIntermediate->getBaseAlignmentScalar(
1968 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001969 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001970
1971 // Load through a block reference is performed with a dot operator that
1972 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1973 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001974 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001975 !node->getLeft()->getType().isArray() &&
1976 node->getOp() == glslang::EOpIndexDirectStruct)
1977 {
1978 spv::Id left = accessChainLoad(node->getLeft()->getType());
1979 builder.clearAccessChain();
1980 builder.setAccessChainLValue(left);
1981 }
1982
David Netoa901ffe2016-06-08 14:11:40 +01001983 int spvIndex = glslangIndex;
1984 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1985 node->getOp() == glslang::EOpIndexDirectStruct)
1986 {
1987 // This may be, e.g., an anonymous block-member selection, which generally need
1988 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001989 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1990 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1991 std::vector<int>& remapper = memberRemapper[glslangId];
1992 assert(remapper.size() > 0);
1993 spvIndex = remapper[glslangIndex];
1994 }
David Netoa901ffe2016-06-08 14:11:40 +01001995 }
John Kessenichebb50532016-05-16 19:22:05 -06001996
greg-lunarg639f5462020-11-12 11:10:07 -07001997 // Struct reference propagates uniform lvalue
1998 spv::Builder::AccessChain::CoherentFlags coherentFlags =
1999 TranslateCoherent(node->getLeft()->getType());
2000 coherentFlags.nonUniform = 0;
2001
David Netoa901ffe2016-06-08 14:11:40 +01002002 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07002003 builder.accessChainPush(builder.makeIntConstant(spvIndex),
greg-lunarg639f5462020-11-12 11:10:07 -07002004 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07002005 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01002006
2007 // Add capabilities here for accessing PointSize and clip/cull distance.
2008 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06002009 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01002010 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06002011 }
2012 }
2013 return false;
2014 case glslang::EOpIndexIndirect:
2015 {
John Kessenich61a5ce12019-02-07 08:04:12 -07002016 // Array, matrix, or vector indirection with variable index.
2017 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06002018 // matrices are arrays of vectors, so will also work for a matrix.
2019 // Will use the access chain's 'component' for variable index into a vector.
2020
2021 // This adapter is building access chains left to right.
2022 // Set up the access chain to the left.
2023 node->getLeft()->traverse(this);
2024
2025 // save it so that computing the right side doesn't trash it
2026 spv::Builder::AccessChain partial = builder.getAccessChain();
2027
2028 // compute the next index in the chain
2029 builder.clearAccessChain();
2030 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002031 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002032
John Kessenich5611c6d2018-04-05 11:25:02 -06002033 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
2034
John Kessenich140f3df2015-06-26 16:58:36 -06002035 // restore the saved access chain
2036 builder.setAccessChain(partial);
2037
greg-lunarg639f5462020-11-12 11:10:07 -07002038 // Only if index is nonUniform should we propagate nonUniform into access chain
2039 spv::Builder::AccessChain::CoherentFlags index_flags = TranslateCoherent(node->getRight()->getType());
2040 spv::Builder::AccessChain::CoherentFlags coherent_flags = TranslateCoherent(node->getLeft()->getType());
2041 coherent_flags.nonUniform = index_flags.nonUniform;
2042
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002043 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
2044 int dummySize;
greg-lunarg639f5462020-11-12 11:10:07 -07002045 builder.accessChainPushComponent(
2046 index, convertGlslangToSpvType(node->getLeft()->getType()), coherent_flags,
John Kessenich8985fc92020-03-03 10:25:07 -07002047 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2048 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002049 } else
greg-lunarg639f5462020-11-12 11:10:07 -07002050 builder.accessChainPush(index, coherent_flags,
2051 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06002052 }
2053 return false;
2054 case glslang::EOpVectorSwizzle:
2055 {
2056 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002057 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06002058 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002059 int dummySize;
2060 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2061 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002062 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2063 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002064 }
2065 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002066 case glslang::EOpMatrixSwizzle:
2067 logger->missingFunctionality("matrix swizzle");
2068 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002069 case glslang::EOpLogicalOr:
2070 case glslang::EOpLogicalAnd:
2071 {
2072
2073 // These may require short circuiting, but can sometimes be done as straight
2074 // binary operations. The right operand must be short circuited if it has
2075 // side effects, and should probably be if it is complex.
2076 if (isTrivial(node->getRight()->getAsTyped()))
2077 break; // handle below as a normal binary operation
2078 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002079 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2080 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002081 builder.clearAccessChain();
2082 builder.setAccessChainRValue(result);
2083 }
2084 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002085 default:
2086 break;
2087 }
2088
2089 // Assume generic binary op...
2090
John Kessenich32cfd492016-02-02 12:37:46 -07002091 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002092 builder.clearAccessChain();
2093 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002094 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002095
John Kessenich32cfd492016-02-02 12:37:46 -07002096 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002097 builder.clearAccessChain();
2098 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002099 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002100
John Kessenich32cfd492016-02-02 12:37:46 -07002101 // get result
John Kessenichead86222018-03-28 18:01:20 -06002102 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 TranslateNoContractionDecoration(node->getType().getQualifier()),
2104 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002105 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002106 convertGlslangToSpvType(node->getType()), left, right,
2107 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002108
John Kessenich50e57562015-12-21 21:21:11 -07002109 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002110 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002111 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002112 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002113 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002114 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002115 return false;
2116 }
John Kessenich140f3df2015-06-26 16:58:36 -06002117}
2118
John Kessenich9c14f772019-06-17 08:38:35 -06002119// Figure out what, if any, type changes are needed when accessing a specific built-in.
2120// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2121// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002122std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002123 const glslang::TType& glslangType)
2124{
Daniel Kochdb32b242020-03-17 20:42:47 -04002125 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002126 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002127 case glslang::EbvSubGroupEqMask:
2128 case glslang::EbvSubGroupGeMask:
2129 case glslang::EbvSubGroupGtMask:
2130 case glslang::EbvSubGroupLeMask:
2131 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002132 // these require changing a 64-bit scaler -> a vector of 32-bit components
2133 if (glslangType.isVector())
2134 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05002135 spv::Id ivec4_type = builder.makeVectorType(builder.makeUintType(32), 4);
2136 spv::Id uint64_type = builder.makeUintType(64);
2137 std::pair<spv::Id, spv::Id> ret(ivec4_type, uint64_type);
John Kessenich9c14f772019-06-17 08:38:35 -06002138 return ret;
2139 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002140 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2141 // builtins. During visitBinary we insert a transpose
2142 case glslang::EbvWorldToObject3x4:
2143 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002144 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2145 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2146 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002147 return ret;
2148 }
John Kessenich9c14f772019-06-17 08:38:35 -06002149 default:
2150 break;
2151 }
2152
2153 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2154 return ret;
2155}
2156
2157// For an object previously identified (see getForcedType() and forceType)
2158// as needing type translations, do the translation needed for a load, turning
2159// an L-value into in R-value.
2160spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2161{
2162 const auto forceIt = forceType.find(object);
2163 if (forceIt == forceType.end())
2164 return object;
2165
2166 spv::Id desiredTypeId = forceIt->second;
2167 spv::Id objectTypeId = builder.getTypeId(object);
2168 assert(builder.isPointerType(objectTypeId));
2169 objectTypeId = builder.getContainedTypeId(objectTypeId);
2170 if (builder.isVectorType(objectTypeId) &&
2171 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2172 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2173 // handle 32-bit v.xy* -> 64-bit
2174 builder.clearAccessChain();
2175 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002176 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
John Kessenich9c14f772019-06-17 08:38:35 -06002177 std::vector<spv::Id> components;
2178 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2179 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2180
2181 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2182 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2183 builder.createCompositeConstruct(vecType, components));
2184 } else {
2185 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2186 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002187 } else if (builder.isMatrixType(objectTypeId)) {
2188 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2189 // and we insert a transpose after loading the original non-transposed builtins
2190 builder.clearAccessChain();
2191 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002192 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
Daniel Kochdb32b242020-03-17 20:42:47 -04002193 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2194
2195 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002196 logger->missingFunctionality("forcing non 32-bit vector type");
2197 }
2198
2199 return object;
2200}
2201
John Kessenich140f3df2015-06-26 16:58:36 -06002202bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2203{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002204 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002205
qining40887662016-04-03 22:20:42 -04002206 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2207 if (node->getType().getQualifier().isSpecConstant())
2208 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2209
John Kessenichfc51d282015-08-19 13:34:18 -06002210 spv::Id result = spv::NoResult;
2211
2212 // try texturing first
2213 result = createImageTextureFunctionCall(node);
2214 if (result != spv::NoResult) {
2215 builder.clearAccessChain();
2216 builder.setAccessChainRValue(result);
2217
2218 return false; // done with this node
2219 }
2220
2221 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002222
2223 if (node->getOp() == glslang::EOpArrayLength) {
2224 // Quite special; won't want to evaluate the operand.
2225
John Kessenich5611c6d2018-04-05 11:25:02 -06002226 // Currently, the front-end does not allow .length() on an array until it is sized,
2227 // except for the last block membeor of an SSBO.
2228 // TODO: If this changes, link-time sized arrays might show up here, and need their
2229 // size extracted.
2230
John Kessenichc9a80832015-09-12 12:17:44 -06002231 // Normal .length() would have been constant folded by the front-end.
2232 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002233 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002234
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002235 spv::Id length;
2236 if (node->getOperand()->getType().isCoopMat()) {
2237 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2238
2239 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2240 assert(builder.isCooperativeMatrixType(typeId));
2241
2242 length = builder.createCooperativeMatrixLength(typeId);
2243 } else {
2244 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2245 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002246 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2247 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002248 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2249 }
John Kessenichc9a80832015-09-12 12:17:44 -06002250
John Kessenich8c869672018-11-28 07:01:37 -07002251 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2252 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2253 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002254 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2255 if (builder.isInSpecConstCodeGenMode()) {
2256 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2257 } else {
2258 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2259 }
2260 }
John Kessenich8c869672018-11-28 07:01:37 -07002261
John Kessenichc9a80832015-09-12 12:17:44 -06002262 builder.clearAccessChain();
2263 builder.setAccessChainRValue(length);
2264
2265 return false;
2266 }
2267
John Kessenichfc51d282015-08-19 13:34:18 -06002268 // Start by evaluating the operand
2269
John Kessenich8c8505c2016-07-26 12:50:38 -06002270 // Does it need a swizzle inversion? If so, evaluation is inverted;
2271 // operate first on the swizzle base, then apply the swizzle.
2272 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002273 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2274 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002275 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2276 invertedType = getInvertedSwizzleType(*node->getOperand());
2277
John Kessenich140f3df2015-06-26 16:58:36 -06002278 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002279 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002280 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002281 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002282 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002283 operandNode = node->getOperand();
2284
2285 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002286
Rex Xufc618912015-09-09 16:42:49 +08002287 spv::Id operand = spv::NoResult;
2288
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002289 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2290
John Kessenichfb4f2332019-08-09 03:49:15 -06002291#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002292 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2293 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002294 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002295 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2296 node->getOp() == glslang::EOpRayQueryProceed ||
2297 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2298 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2299 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2300 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2301 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2302 node->getOp() == glslang::EOpRayQueryTerminate ||
2303 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002304 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002305 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2306 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2307 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002308#endif
2309 {
John Kessenich32cfd492016-02-02 12:37:46 -07002310 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002311 }
John Kessenich140f3df2015-06-26 16:58:36 -06002312
John Kessenichead86222018-03-28 18:01:20 -06002313 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002314 TranslateNoContractionDecoration(node->getType().getQualifier()),
2315 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002318 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002319 result = createConversion(node->getOp(), decorations, resultType(), operand,
2320 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002321
2322 // if not, then possibly an operation
2323 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002324 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2325 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002326
2327 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002328 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002329 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002330 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002331 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002332
John Kessenich140f3df2015-06-26 16:58:36 -06002333 builder.clearAccessChain();
2334 builder.setAccessChainRValue(result);
2335
2336 return false; // done with this node
2337 }
2338
2339 // it must be a special case, check...
2340 switch (node->getOp()) {
2341 case glslang::EOpPostIncrement:
2342 case glslang::EOpPostDecrement:
2343 case glslang::EOpPreIncrement:
2344 case glslang::EOpPreDecrement:
2345 {
2346 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002347 spv::Id one = 0;
2348 if (node->getBasicType() == glslang::EbtFloat)
2349 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002350#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002351 else if (node->getBasicType() == glslang::EbtDouble)
2352 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002353 else if (node->getBasicType() == glslang::EbtFloat16)
2354 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002355 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2356 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002357 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2358 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002359 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2360 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002361#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002362 else
2363 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002364 glslang::TOperator op;
2365 if (node->getOp() == glslang::EOpPreIncrement ||
2366 node->getOp() == glslang::EOpPostIncrement)
2367 op = glslang::EOpAdd;
2368 else
2369 op = glslang::EOpSub;
2370
John Kessenichead86222018-03-28 18:01:20 -06002371 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002372 convertGlslangToSpvType(node->getType()), operand, one,
2373 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002374 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002375
2376 // The result of operation is always stored, but conditionally the
2377 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002378 builder.accessChainStore(result,
greg-lunarg639f5462020-11-12 11:10:07 -07002379 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags));
John Kessenich140f3df2015-06-26 16:58:36 -06002380 builder.clearAccessChain();
2381 if (node->getOp() == glslang::EOpPreIncrement ||
2382 node->getOp() == glslang::EOpPreDecrement)
2383 builder.setAccessChainRValue(result);
2384 else
2385 builder.setAccessChainRValue(operand);
2386 }
2387
2388 return false;
2389
John Kessenich155d3512019-08-08 23:29:20 -06002390#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002391 case glslang::EOpEmitStreamVertex:
2392 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2393 return false;
2394 case glslang::EOpEndStreamPrimitive:
2395 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2396 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002397 case glslang::EOpRayQueryTerminate:
2398 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2399 return false;
2400 case glslang::EOpRayQueryConfirmIntersection:
2401 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2402 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002403#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002404
2405 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002406 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002407 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002408 }
John Kessenich140f3df2015-06-26 16:58:36 -06002409}
2410
Jeff Bolz53134492019-06-25 13:31:10 -05002411// Construct a composite object, recursively copying members if their types don't match
2412spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2413{
2414 for (int c = 0; c < (int)constituents.size(); ++c) {
2415 spv::Id& constituent = constituents[c];
2416 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2417 spv::Id rType = builder.getTypeId(constituent);
2418 if (lType != rType) {
2419 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2420 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2421 } else if (builder.isStructType(rType)) {
2422 std::vector<spv::Id> rTypeConstituents;
2423 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2424 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002425 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2426 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002427 }
2428 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2429 } else {
2430 assert(builder.isArrayType(rType));
2431 std::vector<spv::Id> rTypeConstituents;
2432 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2433
2434 spv::Id elementRType = builder.getContainedTypeId(rType);
2435 for (int i = 0; i < numrTypeConstituents; ++i) {
2436 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2437 }
2438 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2439 }
2440 }
2441 }
2442 return builder.createCompositeConstruct(resultTypeId, constituents);
2443}
2444
John Kessenich140f3df2015-06-26 16:58:36 -06002445bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2446{
qining27e04a02016-04-14 16:40:20 -04002447 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2448 if (node->getType().getQualifier().isSpecConstant())
2449 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2450
John Kessenichfc51d282015-08-19 13:34:18 -06002451 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002452 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2453 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2454 // SPIR-V, for an out parameter
2455 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002456
John Kessenich8985fc92020-03-03 10:25:07 -07002457 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2458 invertedType :
2459 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002460
2461 // try texturing
2462 result = createImageTextureFunctionCall(node);
2463 if (result != spv::NoResult) {
2464 builder.clearAccessChain();
2465 builder.setAccessChainRValue(result);
2466
2467 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002468 }
2469#ifndef GLSLANG_WEB
2470 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002471 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002472 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002473 // "imageStore" is a special case, which has no result
2474 return false;
2475 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002476#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002477
John Kessenich140f3df2015-06-26 16:58:36 -06002478 glslang::TOperator binOp = glslang::EOpNull;
2479 bool reduceComparison = true;
2480 bool isMatrix = false;
2481 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002482 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002483
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002484 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2485
John Kessenich140f3df2015-06-26 16:58:36 -06002486 assert(node->getOp());
2487
John Kessenichf6640762016-08-01 19:44:00 -06002488 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002489
2490 switch (node->getOp()) {
2491 case glslang::EOpSequence:
2492 {
2493 if (preVisit)
2494 ++sequenceDepth;
2495 else
2496 --sequenceDepth;
2497
2498 if (sequenceDepth == 1) {
2499 // If this is the parent node of all the functions, we want to see them
2500 // early, so all call points have actual SPIR-V functions to reference.
2501 // In all cases, still let the traverser visit the children for us.
2502 makeFunctions(node->getAsAggregate()->getSequence());
2503
John Kessenich6fccb3c2016-09-19 16:01:41 -06002504 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002505 // anything else gets there, so visit out of order, doing them all now.
2506 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2507
Daniel Kochffccefd2020-11-23 15:41:27 -05002508 //Pre process linker objects for ray tracing stages
2509 if (glslangIntermediate->isRayTracingStage())
2510 collectRayTracingLinkerObjects();
2511
John Kessenich6a60c2f2016-12-08 21:01:59 -07002512 // 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 -06002513 // so do them manually.
2514 visitFunctions(node->getAsAggregate()->getSequence());
2515
2516 return false;
2517 }
2518
2519 return true;
2520 }
2521 case glslang::EOpLinkerObjects:
2522 {
2523 if (visit == glslang::EvPreVisit)
2524 linkageOnly = true;
2525 else
2526 linkageOnly = false;
2527
2528 return true;
2529 }
2530 case glslang::EOpComma:
2531 {
2532 // processing from left to right naturally leaves the right-most
2533 // lying around in the access chain
2534 glslang::TIntermSequence& glslangOperands = node->getSequence();
2535 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2536 glslangOperands[i]->traverse(this);
2537
2538 return false;
2539 }
2540 case glslang::EOpFunction:
2541 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002542 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002543 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002544 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002545 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002546 } else {
2547 handleFunctionEntry(node);
2548 }
2549 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002550 if (inEntryPoint)
2551 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002552 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002553 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002554 }
2555
2556 return true;
2557 case glslang::EOpParameters:
2558 // Parameters will have been consumed by EOpFunction processing, but not
2559 // the body, so we still visited the function node's children, making this
2560 // child redundant.
2561 return false;
2562 case glslang::EOpFunctionCall:
2563 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002564 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002565 if (node->isUserDefined())
2566 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002567 if (result) {
2568 builder.clearAccessChain();
2569 builder.setAccessChainRValue(result);
2570 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002571 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002572
2573 return false;
2574 }
2575 case glslang::EOpConstructMat2x2:
2576 case glslang::EOpConstructMat2x3:
2577 case glslang::EOpConstructMat2x4:
2578 case glslang::EOpConstructMat3x2:
2579 case glslang::EOpConstructMat3x3:
2580 case glslang::EOpConstructMat3x4:
2581 case glslang::EOpConstructMat4x2:
2582 case glslang::EOpConstructMat4x3:
2583 case glslang::EOpConstructMat4x4:
2584 case glslang::EOpConstructDMat2x2:
2585 case glslang::EOpConstructDMat2x3:
2586 case glslang::EOpConstructDMat2x4:
2587 case glslang::EOpConstructDMat3x2:
2588 case glslang::EOpConstructDMat3x3:
2589 case glslang::EOpConstructDMat3x4:
2590 case glslang::EOpConstructDMat4x2:
2591 case glslang::EOpConstructDMat4x3:
2592 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002593 case glslang::EOpConstructIMat2x2:
2594 case glslang::EOpConstructIMat2x3:
2595 case glslang::EOpConstructIMat2x4:
2596 case glslang::EOpConstructIMat3x2:
2597 case glslang::EOpConstructIMat3x3:
2598 case glslang::EOpConstructIMat3x4:
2599 case glslang::EOpConstructIMat4x2:
2600 case glslang::EOpConstructIMat4x3:
2601 case glslang::EOpConstructIMat4x4:
2602 case glslang::EOpConstructUMat2x2:
2603 case glslang::EOpConstructUMat2x3:
2604 case glslang::EOpConstructUMat2x4:
2605 case glslang::EOpConstructUMat3x2:
2606 case glslang::EOpConstructUMat3x3:
2607 case glslang::EOpConstructUMat3x4:
2608 case glslang::EOpConstructUMat4x2:
2609 case glslang::EOpConstructUMat4x3:
2610 case glslang::EOpConstructUMat4x4:
2611 case glslang::EOpConstructBMat2x2:
2612 case glslang::EOpConstructBMat2x3:
2613 case glslang::EOpConstructBMat2x4:
2614 case glslang::EOpConstructBMat3x2:
2615 case glslang::EOpConstructBMat3x3:
2616 case glslang::EOpConstructBMat3x4:
2617 case glslang::EOpConstructBMat4x2:
2618 case glslang::EOpConstructBMat4x3:
2619 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002620 case glslang::EOpConstructF16Mat2x2:
2621 case glslang::EOpConstructF16Mat2x3:
2622 case glslang::EOpConstructF16Mat2x4:
2623 case glslang::EOpConstructF16Mat3x2:
2624 case glslang::EOpConstructF16Mat3x3:
2625 case glslang::EOpConstructF16Mat3x4:
2626 case glslang::EOpConstructF16Mat4x2:
2627 case glslang::EOpConstructF16Mat4x3:
2628 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002629 isMatrix = true;
2630 // fall through
2631 case glslang::EOpConstructFloat:
2632 case glslang::EOpConstructVec2:
2633 case glslang::EOpConstructVec3:
2634 case glslang::EOpConstructVec4:
2635 case glslang::EOpConstructDouble:
2636 case glslang::EOpConstructDVec2:
2637 case glslang::EOpConstructDVec3:
2638 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002639 case glslang::EOpConstructFloat16:
2640 case glslang::EOpConstructF16Vec2:
2641 case glslang::EOpConstructF16Vec3:
2642 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002643 case glslang::EOpConstructBool:
2644 case glslang::EOpConstructBVec2:
2645 case glslang::EOpConstructBVec3:
2646 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002647 case glslang::EOpConstructInt8:
2648 case glslang::EOpConstructI8Vec2:
2649 case glslang::EOpConstructI8Vec3:
2650 case glslang::EOpConstructI8Vec4:
2651 case glslang::EOpConstructUint8:
2652 case glslang::EOpConstructU8Vec2:
2653 case glslang::EOpConstructU8Vec3:
2654 case glslang::EOpConstructU8Vec4:
2655 case glslang::EOpConstructInt16:
2656 case glslang::EOpConstructI16Vec2:
2657 case glslang::EOpConstructI16Vec3:
2658 case glslang::EOpConstructI16Vec4:
2659 case glslang::EOpConstructUint16:
2660 case glslang::EOpConstructU16Vec2:
2661 case glslang::EOpConstructU16Vec3:
2662 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002663 case glslang::EOpConstructInt:
2664 case glslang::EOpConstructIVec2:
2665 case glslang::EOpConstructIVec3:
2666 case glslang::EOpConstructIVec4:
2667 case glslang::EOpConstructUint:
2668 case glslang::EOpConstructUVec2:
2669 case glslang::EOpConstructUVec3:
2670 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002671 case glslang::EOpConstructInt64:
2672 case glslang::EOpConstructI64Vec2:
2673 case glslang::EOpConstructI64Vec3:
2674 case glslang::EOpConstructI64Vec4:
2675 case glslang::EOpConstructUint64:
2676 case glslang::EOpConstructU64Vec2:
2677 case glslang::EOpConstructU64Vec3:
2678 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002679 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002680 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002681 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002682 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002683 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002684 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002685 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002686 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002687 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002688 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002689 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002690 else if (node->getOp() == glslang::EOpConstructStruct ||
2691 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2692 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002693 std::vector<spv::Id> constituents;
2694 for (int c = 0; c < (int)arguments.size(); ++c)
2695 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002696 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002697 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002698 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002699 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002700 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002701
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002702 if (node->getType().getQualifier().isNonUniform()) {
2703 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2704 }
2705
John Kessenich140f3df2015-06-26 16:58:36 -06002706 builder.clearAccessChain();
2707 builder.setAccessChainRValue(constructed);
2708
2709 return false;
2710 }
2711
2712 // These six are component-wise compares with component-wise results.
2713 // Forward on to createBinaryOperation(), requesting a vector result.
2714 case glslang::EOpLessThan:
2715 case glslang::EOpGreaterThan:
2716 case glslang::EOpLessThanEqual:
2717 case glslang::EOpGreaterThanEqual:
2718 case glslang::EOpVectorEqual:
2719 case glslang::EOpVectorNotEqual:
2720 {
2721 // Map the operation to a binary
2722 binOp = node->getOp();
2723 reduceComparison = false;
2724 switch (node->getOp()) {
2725 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2726 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2727 default: binOp = node->getOp(); break;
2728 }
2729
2730 break;
2731 }
2732 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002733 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002734 binOp = glslang::EOpMul;
2735 break;
2736 case glslang::EOpOuterProduct:
2737 // two vectors multiplied to make a matrix
2738 binOp = glslang::EOpOuterProduct;
2739 break;
2740 case glslang::EOpDot:
2741 {
qining25262b32016-05-06 17:25:16 -04002742 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002743 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002744 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002745 binOp = glslang::EOpMul;
2746 break;
2747 }
2748 case glslang::EOpMod:
2749 // when an aggregate, this is the floating-point mod built-in function,
2750 // which can be emitted by the one in createBinaryOperation()
2751 binOp = glslang::EOpMod;
2752 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002753
John Kessenich140f3df2015-06-26 16:58:36 -06002754 case glslang::EOpEmitVertex:
2755 case glslang::EOpEndPrimitive:
2756 case glslang::EOpBarrier:
2757 case glslang::EOpMemoryBarrier:
2758 case glslang::EOpMemoryBarrierAtomicCounter:
2759 case glslang::EOpMemoryBarrierBuffer:
2760 case glslang::EOpMemoryBarrierImage:
2761 case glslang::EOpMemoryBarrierShared:
2762 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002763 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002764 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002765 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002766 case glslang::EOpWorkgroupMemoryBarrier:
2767 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002768 case glslang::EOpSubgroupBarrier:
2769 case glslang::EOpSubgroupMemoryBarrier:
2770 case glslang::EOpSubgroupMemoryBarrierBuffer:
2771 case glslang::EOpSubgroupMemoryBarrierImage:
2772 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002773 noReturnValue = true;
2774 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2775 break;
2776
John Kessenich426394d2015-07-23 10:22:48 -06002777 case glslang::EOpAtomicAdd:
2778 case glslang::EOpAtomicMin:
2779 case glslang::EOpAtomicMax:
2780 case glslang::EOpAtomicAnd:
2781 case glslang::EOpAtomicOr:
2782 case glslang::EOpAtomicXor:
2783 case glslang::EOpAtomicExchange:
2784 case glslang::EOpAtomicCompSwap:
2785 atomic = true;
2786 break;
2787
John Kesseniche5eee8f2019-10-18 01:03:11 -06002788#ifndef GLSLANG_WEB
2789 case glslang::EOpAtomicStore:
2790 noReturnValue = true;
2791 // fallthrough
2792 case glslang::EOpAtomicLoad:
2793 atomic = true;
2794 break;
2795
John Kessenich0d0c6d32017-07-23 16:08:26 -06002796 case glslang::EOpAtomicCounterAdd:
2797 case glslang::EOpAtomicCounterSubtract:
2798 case glslang::EOpAtomicCounterMin:
2799 case glslang::EOpAtomicCounterMax:
2800 case glslang::EOpAtomicCounterAnd:
2801 case glslang::EOpAtomicCounterOr:
2802 case glslang::EOpAtomicCounterXor:
2803 case glslang::EOpAtomicCounterExchange:
2804 case glslang::EOpAtomicCounterCompSwap:
2805 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2806 builder.addCapability(spv::CapabilityAtomicStorageOps);
2807 atomic = true;
2808 break;
2809
Ian Romanickb3bd4022019-01-21 08:57:25 -08002810 case glslang::EOpAbsDifference:
2811 case glslang::EOpAddSaturate:
2812 case glslang::EOpSubSaturate:
2813 case glslang::EOpAverage:
2814 case glslang::EOpAverageRounded:
2815 case glslang::EOpMul32x16:
2816 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2817 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2818 binOp = node->getOp();
2819 break;
2820
Daniel Kochffccefd2020-11-23 15:41:27 -05002821 case glslang::EOpIgnoreIntersectionNV:
2822 case glslang::EOpTerminateRayNV:
2823 case glslang::EOpTraceNV:
2824 case glslang::EOpTraceKHR:
2825 case glslang::EOpExecuteCallableNV:
2826 case glslang::EOpExecuteCallableKHR:
Chao Chen3c366992018-09-19 11:41:59 -07002827 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2828 noReturnValue = true;
2829 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002830 case glslang::EOpRayQueryInitialize:
2831 case glslang::EOpRayQueryTerminate:
2832 case glslang::EOpRayQueryGenerateIntersection:
2833 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002834 builder.addExtension("SPV_KHR_ray_query");
Daniel Kochffccefd2020-11-23 15:41:27 -05002835 builder.addCapability(spv::CapabilityRayQueryKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002836 noReturnValue = true;
2837 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002838 case glslang::EOpRayQueryProceed:
2839 case glslang::EOpRayQueryGetIntersectionType:
2840 case glslang::EOpRayQueryGetRayTMin:
2841 case glslang::EOpRayQueryGetRayFlags:
2842 case glslang::EOpRayQueryGetIntersectionT:
2843 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2844 case glslang::EOpRayQueryGetIntersectionInstanceId:
2845 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2846 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2847 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2848 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2849 case glslang::EOpRayQueryGetIntersectionFrontFace:
2850 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2851 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2852 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2853 case glslang::EOpRayQueryGetWorldRayDirection:
2854 case glslang::EOpRayQueryGetWorldRayOrigin:
2855 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2856 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2857 builder.addExtension("SPV_KHR_ray_query");
Daniel Kochffccefd2020-11-23 15:41:27 -05002858 builder.addCapability(spv::CapabilityRayQueryKHR);
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002859 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002860 case glslang::EOpCooperativeMatrixLoad:
2861 case glslang::EOpCooperativeMatrixStore:
2862 noReturnValue = true;
2863 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002864 case glslang::EOpBeginInvocationInterlock:
2865 case glslang::EOpEndInvocationInterlock:
2866 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2867 noReturnValue = true;
2868 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002869#endif
Chao Chen3c366992018-09-19 11:41:59 -07002870
Jeff Bolz04d73732019-05-31 13:06:01 -05002871 case glslang::EOpDebugPrintf:
2872 noReturnValue = true;
2873 break;
2874
John Kessenich140f3df2015-06-26 16:58:36 -06002875 default:
2876 break;
2877 }
2878
2879 //
2880 // See if it maps to a regular operation.
2881 //
John Kessenich140f3df2015-06-26 16:58:36 -06002882 if (binOp != glslang::EOpNull) {
2883 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2884 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2885 assert(left && right);
2886
2887 builder.clearAccessChain();
2888 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002889 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002890
2891 builder.clearAccessChain();
2892 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002893 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002894
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002895 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002896 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002897 TranslateNoContractionDecoration(node->getType().getQualifier()),
2898 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002899 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002900 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002901 left->getType().getBasicType(), reduceComparison);
2902
2903 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002904 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002905 builder.clearAccessChain();
2906 builder.setAccessChainRValue(result);
2907
2908 return false;
2909 }
2910
John Kessenich426394d2015-07-23 10:22:48 -06002911 //
2912 // Create the list of operands.
2913 //
John Kessenich140f3df2015-06-26 16:58:36 -06002914 glslang::TIntermSequence& glslangOperands = node->getSequence();
2915 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002916 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002917 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002918 // special case l-value operands; there are just a few
2919 bool lvalue = false;
2920 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002921 case glslang::EOpModf:
2922 if (arg == 1)
2923 lvalue = true;
2924 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002925
Torosdagli06c2eee2020-03-19 11:09:57 -04002926 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002927 case glslang::EOpRayQueryTerminate:
2928 case glslang::EOpRayQueryConfirmIntersection:
2929 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002930 case glslang::EOpRayQueryGenerateIntersection:
2931 case glslang::EOpRayQueryGetIntersectionType:
2932 case glslang::EOpRayQueryGetIntersectionT:
2933 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2934 case glslang::EOpRayQueryGetIntersectionInstanceId:
2935 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2936 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2937 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2938 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2939 case glslang::EOpRayQueryGetIntersectionFrontFace:
2940 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2941 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2942 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2943 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2944 if (arg == 0)
2945 lvalue = true;
2946 break;
2947
John Kesseniche5eee8f2019-10-18 01:03:11 -06002948 case glslang::EOpAtomicAdd:
2949 case glslang::EOpAtomicMin:
2950 case glslang::EOpAtomicMax:
2951 case glslang::EOpAtomicAnd:
2952 case glslang::EOpAtomicOr:
2953 case glslang::EOpAtomicXor:
2954 case glslang::EOpAtomicExchange:
2955 case glslang::EOpAtomicCompSwap:
2956 if (arg == 0)
2957 lvalue = true;
2958 break;
2959
John Kessenicha28f7a72019-08-06 07:00:58 -06002960#ifndef GLSLANG_WEB
2961 case glslang::EOpFrexp:
2962 if (arg == 1)
2963 lvalue = true;
2964 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002965 case glslang::EOpInterpolateAtSample:
2966 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002967 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002968 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002969 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002970
2971 // Does it need a swizzle inversion? If so, evaluation is inverted;
2972 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002973 // That is, we transform
2974 //
2975 // interpolate(v.zy) -> interpolate(v).zy
2976 //
John Kessenichecba76f2017-01-06 00:34:48 -07002977 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002978 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002979 invertedType = convertGlslangToSpvType(
2980 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002981 }
Rex Xu7a26c172015-12-08 17:12:09 +08002982 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002983 case glslang::EOpAtomicLoad:
2984 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002985 case glslang::EOpAtomicCounterAdd:
2986 case glslang::EOpAtomicCounterSubtract:
2987 case glslang::EOpAtomicCounterMin:
2988 case glslang::EOpAtomicCounterMax:
2989 case glslang::EOpAtomicCounterAnd:
2990 case glslang::EOpAtomicCounterOr:
2991 case glslang::EOpAtomicCounterXor:
2992 case glslang::EOpAtomicCounterExchange:
2993 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002994 if (arg == 0)
2995 lvalue = true;
2996 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002997 case glslang::EOpAddCarry:
2998 case glslang::EOpSubBorrow:
2999 if (arg == 2)
3000 lvalue = true;
3001 break;
3002 case glslang::EOpUMulExtended:
3003 case glslang::EOpIMulExtended:
3004 if (arg >= 2)
3005 lvalue = true;
3006 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003007 case glslang::EOpCooperativeMatrixLoad:
3008 if (arg == 0 || arg == 1)
3009 lvalue = true;
3010 break;
3011 case glslang::EOpCooperativeMatrixStore:
3012 if (arg == 1)
3013 lvalue = true;
3014 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003015#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003016 default:
3017 break;
3018 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003019 builder.clearAccessChain();
3020 if (invertedType != spv::NoType && arg == 0)
3021 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
3022 else
3023 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003024
John Kessenichb9197c82019-08-11 07:41:45 -06003025#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003026 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
3027 node->getOp() == glslang::EOpCooperativeMatrixStore) {
3028
3029 if (arg == 1) {
3030 // fold "element" parameter into the access chain
3031 spv::Builder::AccessChain save = builder.getAccessChain();
3032 builder.clearAccessChain();
3033 glslangOperands[2]->traverse(this);
3034
3035 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
3036
3037 builder.setAccessChain(save);
3038
3039 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07003040 builder.accessChainPush(elementId,
3041 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
3042 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003043
3044 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3045 unsigned int alignment = builder.getAccessChain().alignment;
3046
3047 int memoryAccess = TranslateMemoryAccess(coherentFlags);
3048 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
3049 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
3050 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
3051 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07003052 if (builder.getStorageClass(builder.getAccessChain().base) ==
3053 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003054 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
3055 }
3056
3057 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
3058
3059 if (memoryAccess & spv::MemoryAccessAlignedMask) {
3060 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
3061 }
3062
John Kessenich8985fc92020-03-03 10:25:07 -07003063 if (memoryAccess &
3064 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3065 memoryAccessOperands.push_back(spv::IdImmediate(true,
3066 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003067 }
3068 } else if (arg == 2) {
3069 continue;
3070 }
3071 }
John Kessenichb9197c82019-08-11 07:41:45 -06003072#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003073
John Kessenichbbbd9a22020-03-03 07:21:37 -07003074 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003075 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003076 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3077 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3078 // reduce to a simple access chain. So, we need a temporary vector to
3079 // receive the result, and must later swizzle that into the original
3080 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003081 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06003082 temporaryLvalues.push_back(builder.createVariable(
3083 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003084 builder.accessChainGetInferredType(), "swizzleTemp"));
3085 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003086 } else {
3087 operands.push_back(builder.accessChainGetLValue());
3088 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003089 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3090 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3091 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003092 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003093 glslang::TOperator glslangOp = node->getOp();
3094 if (arg == 1 &&
3095 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3096 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3097 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3098 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3099 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3100 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3101 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3102 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3103 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3104 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3105 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3106 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3107 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3108 )) {
3109 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3110 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
Daniel Kochffccefd2020-11-23 15:41:27 -05003111 } else if ((arg == 10 && glslangOp == glslang::EOpTraceKHR) ||
3112 (arg == 1 && glslangOp == glslang::EOpExecuteCallableKHR)) {
3113 const int opdNum = glslangOp == glslang::EOpTraceKHR ? 10 : 1;
3114 const int set = glslangOp == glslang::EOpTraceKHR ? 0 : 1;
3115 const int location = glslangOperands[opdNum]->getAsConstantUnion()->getConstArray()[0].getUConst();
3116 auto itNode = locationToSymbol[set].find(location);
3117 visitSymbol(itNode->second);
3118 spv::Id symId = getSymbolId(itNode->second);
3119 operands.push_back(symId);
3120 } else {
Torosdagli06c2eee2020-03-19 11:09:57 -04003121 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
Daniel Kochffccefd2020-11-23 15:41:27 -05003122 }
John Kesseniche485c7a2017-05-31 18:50:53 -06003123 }
John Kessenich140f3df2015-06-26 16:58:36 -06003124 }
John Kessenich426394d2015-07-23 10:22:48 -06003125
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003126 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003127#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003128 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3129 std::vector<spv::IdImmediate> idImmOps;
3130
3131 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3132 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3133 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3134 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3135 // get the pointee type
3136 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3137 assert(builder.isCooperativeMatrixType(typeId));
3138 // do the op
3139 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3140 // store the result to the pointer (out param 'm')
3141 builder.createStore(result, operands[0]);
3142 result = 0;
3143 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3144 std::vector<spv::IdImmediate> idImmOps;
3145
3146 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3147 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3148 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3149 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3150 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3151
3152 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3153 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003154 } else
3155#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003156 if (atomic) {
3157 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003158 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3159 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003160 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3161 if (!nonSemanticDebugPrintf) {
3162 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3163 }
3164 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3165 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003166 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003167 // Pass through to generic operations.
3168 switch (glslangOperands.size()) {
3169 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003170 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003171 break;
3172 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003173 {
3174 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003175 TranslateNoContractionDecoration(node->getType().getQualifier()),
3176 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003177 result = createUnaryOperation(
3178 node->getOp(), decorations,
3179 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003180 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003181 }
John Kessenich426394d2015-07-23 10:22:48 -06003182 break;
3183 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003184 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003185 break;
3186 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003187
John Kessenichbbbd9a22020-03-03 07:21:37 -07003188 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003189 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003190
3191 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3192 builder.setAccessChain(complexLvalues[i]);
greg-lunarg639f5462020-11-12 11:10:07 -07003193 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision),
3194 TranslateNonUniformDecoration(complexLvalues[i].coherentFlags));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003195 }
John Kessenich140f3df2015-06-26 16:58:36 -06003196 }
3197
3198 if (noReturnValue)
3199 return false;
3200
3201 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003202 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003203 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003204 } else {
3205 builder.clearAccessChain();
3206 builder.setAccessChainRValue(result);
3207 return false;
3208 }
3209}
3210
John Kessenich433e9ff2017-01-26 20:31:11 -07003211// This path handles both if-then-else and ?:
3212// The if-then-else has a node type of void, while
3213// ?: has either a void or a non-void node type
3214//
3215// Leaving the result, when not void:
3216// GLSL only has r-values as the result of a :?, but
3217// if we have an l-value, that can be more efficient if it will
3218// become the base of a complex r-value expression, because the
3219// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003220bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3221{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003222 // see if OpSelect can handle it
3223 const auto isOpSelectable = [&]() {
3224 if (node->getBasicType() == glslang::EbtVoid)
3225 return false;
3226 // OpSelect can do all other types starting with SPV 1.4
3227 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3228 // pre-1.4, only scalars and vectors can be handled
3229 if ((!node->getType().isScalar() && !node->getType().isVector()))
3230 return false;
3231 }
3232 return true;
3233 };
3234
John Kessenich4bee5312018-02-20 21:29:05 -07003235 // See if it simple and safe, or required, to execute both sides.
3236 // Crucially, side effects must be either semantically required or avoided,
3237 // and there are performance trade-offs.
3238 // Return true if required or a good idea (and safe) to execute both sides,
3239 // false otherwise.
3240 const auto bothSidesPolicy = [&]() -> bool {
3241 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003242 if (node->getTrueBlock() == nullptr ||
3243 node->getFalseBlock() == nullptr)
3244 return false;
3245
John Kessenich4bee5312018-02-20 21:29:05 -07003246 // required? (unless we write additional code to look for side effects
3247 // and make performance trade-offs if none are present)
3248 if (!node->getShortCircuit())
3249 return true;
3250
3251 // if not required to execute both, decide based on performance/practicality...
3252
John Kessenich0c1e71a2019-01-10 18:23:06 +07003253 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003254 return false;
3255
John Kessenich433e9ff2017-01-26 20:31:11 -07003256 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3257 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3258
3259 // return true if a single operand to ? : is okay for OpSelect
3260 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003261 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003262 };
3263
3264 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3265 operandOkay(node->getFalseBlock()->getAsTyped());
3266 };
3267
John Kessenich4bee5312018-02-20 21:29:05 -07003268 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3269 // emit the condition before doing anything with selection
3270 node->getCondition()->traverse(this);
3271 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3272
3273 // Find a way of executing both sides and selecting the right result.
3274 const auto executeBothSides = [&]() -> void {
3275 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003276 node->getTrueBlock()->traverse(this);
3277 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3278 node->getFalseBlock()->traverse(this);
3279 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3280
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003281 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003282
John Kessenich4bee5312018-02-20 21:29:05 -07003283 // done if void
3284 if (node->getBasicType() == glslang::EbtVoid)
3285 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003286
John Kessenich4bee5312018-02-20 21:29:05 -07003287 // emit code to select between trueValue and falseValue
3288
3289 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003290 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003291 // Emit OpSelect for this selection.
3292
3293 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003294 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3295 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003296 condition = builder.smearScalar(spv::NoPrecision, condition,
3297 builder.makeVectorType(builder.makeBoolType(),
3298 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003299 }
John Kessenich4bee5312018-02-20 21:29:05 -07003300
3301 // OpSelect
3302 result = builder.createTriOp(spv::OpSelect,
3303 convertGlslangToSpvType(node->getType()), condition,
3304 trueValue, falseValue);
3305
3306 builder.clearAccessChain();
3307 builder.setAccessChainRValue(result);
3308 } else {
3309 // We need control flow to select the result.
3310 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003311 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3312 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003313
3314 // Selection control:
3315 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3316
3317 // make an "if" based on the value created by the condition
3318 spv::Builder::If ifBuilder(condition, control, builder);
3319
3320 // emit the "then" statement
3321 builder.createStore(trueValue, result);
3322 ifBuilder.makeBeginElse();
3323 // emit the "else" statement
3324 builder.createStore(falseValue, result);
3325
3326 // finish off the control flow
3327 ifBuilder.makeEndIf();
3328
3329 builder.clearAccessChain();
3330 builder.setAccessChainLValue(result);
3331 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003332 };
3333
John Kessenich4bee5312018-02-20 21:29:05 -07003334 // Execute the one side needed, as per the condition
3335 const auto executeOneSide = [&]() {
3336 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003337 if (node->getBasicType() != glslang::EbtVoid) {
3338 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3339 convertGlslangToSpvType(node->getType()));
3340 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003341
John Kessenich4bee5312018-02-20 21:29:05 -07003342 // Selection control:
3343 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3344
3345 // make an "if" based on the value created by the condition
3346 spv::Builder::If ifBuilder(condition, control, builder);
3347
3348 // emit the "then" statement
3349 if (node->getTrueBlock() != nullptr) {
3350 node->getTrueBlock()->traverse(this);
3351 if (result != spv::NoResult)
3352 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3353 }
3354
3355 if (node->getFalseBlock() != nullptr) {
3356 ifBuilder.makeBeginElse();
3357 // emit the "else" statement
3358 node->getFalseBlock()->traverse(this);
3359 if (result != spv::NoResult)
3360 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3361 }
3362
3363 // finish off the control flow
3364 ifBuilder.makeEndIf();
3365
3366 if (result != spv::NoResult) {
3367 builder.clearAccessChain();
3368 builder.setAccessChainLValue(result);
3369 }
3370 };
3371
3372 // Try for OpSelect (or a requirement to execute both sides)
3373 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003374 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3375 if (node->getType().getQualifier().isSpecConstant())
3376 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003377 executeBothSides();
3378 } else
3379 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003380
3381 return false;
3382}
3383
3384bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3385{
3386 // emit and get the condition before doing anything with switch
3387 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003388 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003389
Rex Xu57e65922017-07-04 23:23:40 +08003390 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003391 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003392
John Kessenich140f3df2015-06-26 16:58:36 -06003393 // browse the children to sort out code segments
3394 int defaultSegment = -1;
3395 std::vector<TIntermNode*> codeSegments;
3396 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3397 std::vector<int> caseValues;
3398 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3399 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3400 TIntermNode* child = *c;
3401 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003402 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003403 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003404 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003405 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3406 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003407 } else
3408 codeSegments.push_back(child);
3409 }
3410
qining25262b32016-05-06 17:25:16 -04003411 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003412 // statements between the last case and the end of the switch statement
3413 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3414 (int)codeSegments.size() == defaultSegment)
3415 codeSegments.push_back(nullptr);
3416
3417 // make the switch statement
3418 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003419 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3420 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003421
3422 // emit all the code in the segments
3423 breakForLoop.push(false);
3424 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3425 builder.nextSwitchSegment(segmentBlocks, s);
3426 if (codeSegments[s])
3427 codeSegments[s]->traverse(this);
3428 else
3429 builder.addSwitchBreak();
3430 }
3431 breakForLoop.pop();
3432
3433 builder.endSwitch(segmentBlocks);
3434
3435 return false;
3436}
3437
3438void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3439{
3440 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003441 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003442
3443 builder.clearAccessChain();
3444 builder.setAccessChainRValue(constant);
3445}
3446
3447bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3448{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003449 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003450 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003451
3452 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003453 std::vector<unsigned int> operands;
3454 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003455
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003456 // Spec requires back edges to target header blocks, and every header block
3457 // must dominate its merge block. Make a header block first to ensure these
3458 // conditions are met. By definition, it will contain OpLoopMerge, followed
3459 // by a block-ending branch. But we don't want to put any other body/test
3460 // instructions in it, since the body/test may have arbitrary instructions,
3461 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003462 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003463 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003464 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003465 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003466 spv::Block& test = builder.makeNewBlock();
3467 builder.createBranch(&test);
3468
3469 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003470 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003471 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003472 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3473
3474 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003475 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003476 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003477 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003478 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003479 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003480
3481 builder.setBuildPoint(&blocks.continue_target);
3482 if (node->getTerminal())
3483 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003484 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003485 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003486 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003487 builder.createBranch(&blocks.body);
3488
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003489 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003490 builder.setBuildPoint(&blocks.body);
3491 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003492 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003493 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003494 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003495
3496 builder.setBuildPoint(&blocks.continue_target);
3497 if (node->getTerminal())
3498 node->getTerminal()->traverse(this);
3499 if (node->getTest()) {
3500 node->getTest()->traverse(this);
3501 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003502 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003503 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003504 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003505 // TODO: unless there was a break/return/discard instruction
3506 // somewhere in the body, this is an infinite loop, so we should
3507 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003508 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003509 }
John Kessenich140f3df2015-06-26 16:58:36 -06003510 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003511 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003512 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003513 return false;
3514}
3515
3516bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3517{
3518 if (node->getExpression())
3519 node->getExpression()->traverse(this);
3520
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003521 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003522
John Kessenich140f3df2015-06-26 16:58:36 -06003523 switch (node->getFlowOp()) {
3524 case glslang::EOpKill:
Daniel Kochffccefd2020-11-23 15:41:27 -05003525 builder.makeStatementTerminator(spv::OpKill, "post-discard");
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
Jesse Hall74e8f052020-11-09 08:30:01 -08003527 case glslang::EOpTerminateInvocation:
3528 builder.addExtension(spv::E_SPV_KHR_terminate_invocation);
Daniel Kochffccefd2020-11-23 15:41:27 -05003529 builder.makeStatementTerminator(spv::OpTerminateInvocation, "post-terminate-invocation");
Jesse Hall74e8f052020-11-09 08:30:01 -08003530 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 case glslang::EOpBreak:
3532 if (breakForLoop.top())
3533 builder.createLoopExit();
3534 else
3535 builder.addSwitchBreak();
3536 break;
3537 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003538 builder.createLoopContinue();
3539 break;
3540 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003541 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003542 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3543 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003544 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3545 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003546 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003547 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3548 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003549 builder.setAccessChainLValue(copyId);
3550 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003551 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003552 }
3553 builder.makeReturn(false, returnId);
3554 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003555 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003556
3557 builder.clearAccessChain();
3558 break;
3559
John Kessenichb9197c82019-08-11 07:41:45 -06003560#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003561 case glslang::EOpDemote:
3562 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3563 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3564 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3565 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05003566 case glslang::EOpTerminateRayKHR:
3567 builder.makeStatementTerminator(spv::OpTerminateRayKHR, "post-terminateRayKHR");
3568 break;
3569 case glslang::EOpIgnoreIntersectionKHR:
3570 builder.makeStatementTerminator(spv::OpIgnoreIntersectionKHR, "post-ignoreIntersectionKHR");
3571 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003572#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003573
John Kessenich140f3df2015-06-26 16:58:36 -06003574 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003575 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003576 break;
3577 }
3578
3579 return false;
3580}
3581
John Kessenich9c14f772019-06-17 08:38:35 -06003582spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003583{
qining25262b32016-05-06 17:25:16 -04003584 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003585 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003586 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003587 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003588 spv::Id result = createSpvConstant(*node);
3589 if (result != spv::NoResult)
3590 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003591 }
3592
3593 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003594 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003595 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3596 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003597
John Kessenichb9197c82019-08-11 07:41:45 -06003598 const bool contains16BitType = node->getType().contains16BitFloat() ||
3599 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003600 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003601 switch (storageClass) {
3602 case spv::StorageClassInput:
3603 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003604 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003605 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003606 break;
John Kessenich18310872018-05-14 22:08:53 -06003607 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003608 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003609 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3610 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003611 else
3612 builder.addCapability(spv::CapabilityStorageUniform16);
3613 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003614#ifndef GLSLANG_WEB
3615 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003616 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003617 builder.addCapability(spv::CapabilityStoragePushConstant16);
3618 break;
John Kessenich18310872018-05-14 22:08:53 -06003619 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003620 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003621 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003622 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3623 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003624#endif
John Kessenich18310872018-05-14 22:08:53 -06003625 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003626 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003627 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003628 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003629 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003630 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003631 }
3632 }
Rex Xuf89ad982017-04-07 23:22:33 +08003633
John Kessenichb9197c82019-08-11 07:41:45 -06003634 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003635 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003636 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003637 builder.addCapability(spv::CapabilityStoragePushConstant8);
3638 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003639 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003640 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003641 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003642 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003643 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003644 } else {
3645 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003646 }
3647 }
3648
John Kessenich140f3df2015-06-26 16:58:36 -06003649 const char* name = node->getName().c_str();
3650 if (glslang::IsAnonymous(name))
3651 name = "";
3652
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003653 spv::Id initializer = spv::NoResult;
3654
John Kessenichc739e032020-06-11 08:30:03 -06003655 if (node->getType().getQualifier().storage == glslang::EvqUniform && !node->getConstArray().empty()) {
3656 int nextConst = 0;
3657 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3658 node->getConstArray(),
3659 nextConst,
3660 false /* specConst */);
3661 } else if (node->getType().getQualifier().isNullInit()) {
3662 initializer = builder.makeNullConstant(spvType);
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003663 }
3664
John Kessenich435dd802020-06-30 01:27:08 -06003665 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003666}
3667
3668// Return type Id of the sampled type.
3669spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3670{
3671 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003672 case glslang::EbtInt: return builder.makeIntType(32);
3673 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003674 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003675#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003676 case glslang::EbtFloat16:
3677 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3678 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3679 return builder.makeFloatType(16);
Tobski8c1a3a02020-11-04 16:24:23 +00003680 case glslang::EbtInt64: return builder.makeIntType(64);
3681 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3682 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3683 case glslang::EbtUint64: return builder.makeUintType(64);
3684 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3685 builder.addCapability(spv::CapabilityFloat16ImageAMD);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003686#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003687 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003688 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003689 return builder.makeFloatType(32);
3690 }
3691}
3692
John Kessenich8c8505c2016-07-26 12:50:38 -06003693// If node is a swizzle operation, return the type that should be used if
3694// the swizzle base is first consumed by another operation, before the swizzle
3695// is applied.
3696spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3697{
John Kessenichecba76f2017-01-06 00:34:48 -07003698 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003699 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3700 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3701 else
3702 return spv::NoType;
3703}
3704
3705// When inverting a swizzle with a parent op, this function
3706// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003707spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3708 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003709{
3710 std::vector<unsigned> swizzle;
3711 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3712 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3713}
3714
John Kessenich8c8505c2016-07-26 12:50:38 -06003715// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3716void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3717{
3718 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3719 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3720 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3721}
3722
John Kessenich3ac051e2015-12-20 11:29:16 -07003723// Convert from a glslang type to an SPV type, by calling into a
3724// recursive version of this function. This establishes the inherited
3725// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003726spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003727{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003728 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003729}
3730
3731// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003732// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003733// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003734spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003735 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3736 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003737{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003738 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003739
3740 switch (type.getBasicType()) {
3741 case glslang::EbtVoid:
3742 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003743 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003746 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3747 // a 32-bit int where non-0 means true.
3748 if (explicitLayout != glslang::ElpNone)
3749 spvType = builder.makeUintType(32);
3750 else
3751 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003753 case glslang::EbtInt:
3754 spvType = builder.makeIntType(32);
3755 break;
3756 case glslang::EbtUint:
3757 spvType = builder.makeUintType(32);
3758 break;
3759 case glslang::EbtFloat:
3760 spvType = builder.makeFloatType(32);
3761 break;
3762#ifndef GLSLANG_WEB
3763 case glslang::EbtDouble:
3764 spvType = builder.makeFloatType(64);
3765 break;
3766 case glslang::EbtFloat16:
3767 spvType = builder.makeFloatType(16);
3768 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003769 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003770 spvType = builder.makeIntType(8);
3771 break;
3772 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003773 spvType = builder.makeUintType(8);
3774 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003775 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003776 spvType = builder.makeIntType(16);
3777 break;
3778 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003779 spvType = builder.makeUintType(16);
3780 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003781 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003782 spvType = builder.makeIntType(64);
3783 break;
3784 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003785 spvType = builder.makeUintType(64);
3786 break;
John Kessenich426394d2015-07-23 10:22:48 -06003787 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003788 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003789 spvType = builder.makeUintType(32);
3790 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003791 case glslang::EbtAccStruct:
Daniel Koch4d41da32020-11-24 23:06:16 -05003792 switch (glslangIntermediate->getStage()) {
3793 case EShLangRayGen:
3794 case EShLangIntersect:
3795 case EShLangAnyHit:
3796 case EShLangClosestHit:
3797 case EShLangMiss:
3798 case EShLangCallable:
3799 // these all should have the RayTracingNV/KHR capability already
3800 break;
3801 default:
3802 {
3803 auto& extensions = glslangIntermediate->getRequestedExtensions();
3804 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3805 builder.addExtension(spv::E_SPV_KHR_ray_query);
3806 builder.addCapability(spv::CapabilityRayQueryKHR);
3807 }
3808 }
3809 break;
3810 }
Daniel Kochdb32b242020-03-17 20:42:47 -04003811 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003812 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003813 case glslang::EbtRayQuery:
Daniel Koch4d41da32020-11-24 23:06:16 -05003814 {
3815 auto& extensions = glslangIntermediate->getRequestedExtensions();
3816 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3817 builder.addExtension(spv::E_SPV_KHR_ray_query);
3818 builder.addCapability(spv::CapabilityRayQueryKHR);
3819 }
3820 spvType = builder.makeRayQueryType();
3821 }
Torosdagli06c2eee2020-03-19 11:09:57 -04003822 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003823 case glslang::EbtReference:
3824 {
3825 // Make the forward pointer, then recurse to convert the structure type, then
3826 // patch up the forward pointer with a real pointer type.
3827 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3828 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3829 forwardPointers[type.getReferentType()] = forwardId;
3830 }
3831 spvType = forwardPointers[type.getReferentType()];
3832 if (!forwardReferenceOnly) {
3833 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3834 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3835 forwardPointers[type.getReferentType()],
3836 referentType);
3837 }
3838 }
3839 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003840#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003841 case glslang::EbtSampler:
3842 {
3843 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003844 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003845 spvType = builder.makeSamplerType();
3846 } else {
3847 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003848 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3849 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3850 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3851 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003852 // already has both image and sampler, make the combined type
3853 spvType = builder.makeSampledImageType(spvType);
3854 }
John Kessenich55e7d112015-11-15 21:33:39 -07003855 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003856 }
John Kessenich140f3df2015-06-26 16:58:36 -06003857 break;
3858 case glslang::EbtStruct:
3859 case glslang::EbtBlock:
3860 {
3861 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003862 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003863
3864 // Try to share structs for different layouts, but not yet for other
3865 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003866 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003867 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003868 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003869 break;
3870
3871 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003872 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003873 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003874 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003875 }
3876 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003877 case glslang::EbtString:
3878 // no type used for OpString
3879 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003880 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003881 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003882 break;
3883 }
3884
3885 if (type.isMatrix())
3886 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3887 else {
3888 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3889 if (type.getVectorSize() > 1)
3890 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3891 }
3892
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003893 if (type.isCoopMat()) {
3894 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3895 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3896 if (type.getBasicType() == glslang::EbtFloat16)
3897 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003898 if (type.getBasicType() == glslang::EbtUint8 ||
3899 type.getBasicType() == glslang::EbtInt8) {
3900 builder.addCapability(spv::CapabilityInt8);
3901 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003902
3903 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3904 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3905 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3906
3907 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3908 }
3909
John Kessenich140f3df2015-06-26 16:58:36 -06003910 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003911 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3912
John Kessenichc9a80832015-09-12 12:17:44 -06003913 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003914 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003915 // We need to decorate array strides for types needing explicit layout, except blocks.
3916 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003917 // Use a dummy glslang type for querying internal strides of
3918 // arrays of arrays, but using just a one-dimensional array.
3919 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003920 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3921 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003922
3923 // Will compute the higher-order strides here, rather than making a whole
3924 // pile of types and doing repetitive recursion on their contents.
3925 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3926 }
John Kessenichf8842e52016-01-04 19:22:56 -07003927
3928 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003929 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003930 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003931 if (stride > 0)
3932 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003933 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003934 }
3935 } else {
3936 // single-dimensional array, and don't yet have stride
3937
John Kessenichf8842e52016-01-04 19:22:56 -07003938 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003939 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3940 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003941 }
John Kessenich31ed4832015-09-09 17:51:38 -06003942
John Kessenichead86222018-03-28 18:01:20 -06003943 // Do the outer dimension, which might not be known for a runtime-sized array.
3944 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3945 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003946 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003947 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003948#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003949 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003950 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003951 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3952 }
John Kessenichb9197c82019-08-11 07:41:45 -06003953#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003954 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003955 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003956 if (stride > 0)
3957 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003958 }
3959
3960 return spvType;
3961}
3962
John Kessenich0e737842017-03-24 18:38:16 -06003963// TODO: this functionality should exist at a higher level, in creating the AST
3964//
3965// Identify interface members that don't have their required extension turned on.
3966//
3967bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3968{
John Kessenicha28f7a72019-08-06 07:00:58 -06003969#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003970 auto& extensions = glslangIntermediate->getRequestedExtensions();
3971
Rex Xubcf291a2017-03-29 23:01:36 +08003972 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3973 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3974 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003975 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3976 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3977 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003978
3979 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3980 if (member.getFieldName() == "gl_ViewportMask" &&
3981 extensions.find("GL_NV_viewport_array2") == extensions.end())
3982 return true;
3983 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3984 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3985 return true;
3986 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3987 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3988 return true;
3989 }
3990#endif
John Kessenich0e737842017-03-24 18:38:16 -06003991
3992 return false;
3993};
3994
John Kessenich6090df02016-06-30 21:18:02 -06003995// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3996// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3997// Mutually recursive with convertGlslangToSpvType().
3998spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3999 const glslang::TTypeList* glslangMembers,
4000 glslang::TLayoutPacking explicitLayout,
4001 const glslang::TQualifier& qualifier)
4002{
4003 // Create a vector of struct types for SPIR-V to consume
4004 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07004005 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
4006 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004007 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06004008 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4009 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4010 if (glslangMember.hiddenMember()) {
4011 ++memberDelta;
4012 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08004013 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06004014 } else {
John Kessenich0e737842017-03-24 18:38:16 -06004015 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004016 if (filterMember(glslangMember)) {
4017 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08004018 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06004019 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004020 }
Roy05a5b532020-01-03 16:21:34 +08004021 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06004022 }
John Kessenich6090df02016-06-30 21:18:02 -06004023 // modify just this child's view of the qualifier
4024 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4025 InheritQualifiers(memberQualifier, qualifier);
4026
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004027 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06004028 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004029 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06004030
4031 // recurse
John Kessenichead86222018-03-28 18:01:20 -06004032 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
4033 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004034
4035 // Make forward pointers for any pointer members, and create a list of members to
4036 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06004037 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004038 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
4039 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
4040 }
4041 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004042 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4043 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004044 } else {
4045 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004046 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4047 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004048 }
John Kessenich6090df02016-06-30 21:18:02 -06004049 }
4050 }
4051
4052 // Make the SPIR-V type
4053 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06004054 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06004055 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
4056
4057 // Decorate it
4058 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
4059
John Kessenichd72f4882019-01-16 14:55:37 +07004060 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004061 auto it = deferredForwardPointers[i];
4062 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
4063 }
4064
John Kessenich6090df02016-06-30 21:18:02 -06004065 return spvType;
4066}
4067
4068void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
4069 const glslang::TTypeList* glslangMembers,
4070 glslang::TLayoutPacking explicitLayout,
4071 const glslang::TQualifier& qualifier,
4072 spv::Id spvType)
4073{
4074 // Name and decorate the non-hidden members
4075 int offset = -1;
4076 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08004077 bool memberLocationInvalid = type.isArrayOfArrays() ||
4078 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06004079 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4080 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4081 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06004082 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08004083 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06004084 if (filterMember(glslangMember))
4085 continue;
4086 }
John Kessenich6090df02016-06-30 21:18:02 -06004087
4088 // modify just this child's view of the qualifier
4089 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4090 InheritQualifiers(memberQualifier, qualifier);
4091
4092 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07004093 if (member < 0)
4094 continue;
4095
4096 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
4097 builder.addMemberDecoration(spvType, member,
4098 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
4099 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
4100 // Add interpolation and auxiliary storage decorations only to
4101 // top-level members of Input and Output storage classes
4102 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4103 type.getQualifier().storage == glslang::EvqVaryingOut) {
4104 if (type.getBasicType() == glslang::EbtBlock ||
4105 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4106 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4107 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004108#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004109 addMeshNVDecoration(spvType, member, memberQualifier);
4110#endif
John Kessenich6090df02016-06-30 21:18:02 -06004111 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004112 }
4113 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004114
John Kessenichb9197c82019-08-11 07:41:45 -06004115#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004116 if (type.getBasicType() == glslang::EbtBlock &&
4117 qualifier.storage == glslang::EvqBuffer) {
4118 // Add memory decorations only to top-level members of shader storage block
4119 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004120 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004121 for (unsigned int i = 0; i < memory.size(); ++i)
4122 builder.addMemberDecoration(spvType, member, memory[i]);
4123 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004124
John Kessenichb9197c82019-08-11 07:41:45 -06004125#endif
John Kessenich6090df02016-06-30 21:18:02 -06004126
John Kessenich5d610ee2018-03-07 18:05:55 -07004127 // Location assignment was already completed correctly by the front end,
4128 // just track whether a member needs to be decorated.
4129 // Ignore member locations if the container is an array, as that's
4130 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004131 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004132 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004133
John Kessenich5d610ee2018-03-07 18:05:55 -07004134 if (qualifier.hasLocation()) // track for upcoming inheritance
4135 locationOffset += glslangIntermediate->computeTypeLocationSize(
4136 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004137
John Kessenich5d610ee2018-03-07 18:05:55 -07004138 // component, XFB, others
4139 if (glslangMember.getQualifier().hasComponent())
4140 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4141 glslangMember.getQualifier().layoutComponent);
4142 if (glslangMember.getQualifier().hasXfbOffset())
4143 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4144 glslangMember.getQualifier().layoutXfbOffset);
4145 else if (explicitLayout != glslang::ElpNone) {
4146 // figure out what to do with offset, which is accumulating
4147 int nextOffset;
4148 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4149 if (offset >= 0)
4150 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4151 offset = nextOffset;
4152 }
John Kessenich6090df02016-06-30 21:18:02 -06004153
John Kessenich5d610ee2018-03-07 18:05:55 -07004154 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4155 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4156 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004157
John Kessenich5d610ee2018-03-07 18:05:55 -07004158 // built-in variable decorations
4159 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4160 if (builtIn != spv::BuiltInMax)
4161 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004162
John Kessenichb9197c82019-08-11 07:41:45 -06004163#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004164 // nonuniform
4165 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4166
John Kessenichead86222018-03-28 18:01:20 -06004167 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4168 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4169 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4170 memberQualifier.semanticName);
4171 }
4172
John Kessenich5d610ee2018-03-07 18:05:55 -07004173 if (builtIn == spv::BuiltInLayer) {
4174 // SPV_NV_viewport_array2 extension
4175 if (glslangMember.getQualifier().layoutViewportRelative){
4176 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4177 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4178 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004179 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004180 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4181 builder.addMemberDecoration(spvType, member,
4182 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4183 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4184 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4185 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004186 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004187 }
4188 if (glslangMember.getQualifier().layoutPassthrough) {
4189 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4190 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4191 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4192 }
chaoc771d89f2017-01-13 01:10:53 -08004193#endif
John Kessenich6090df02016-06-30 21:18:02 -06004194 }
4195
4196 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004197 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4198 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004199}
4200
John Kessenich6c292d32016-02-15 20:58:50 -07004201// Turn the expression forming the array size into an id.
4202// This is not quite trivial, because of specialization constants.
4203// Sometimes, a raw constant is turned into an Id, and sometimes
4204// a specialization constant expression is.
4205spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4206{
4207 // First, see if this is sized with a node, meaning a specialization constant:
4208 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4209 if (specNode != nullptr) {
4210 builder.clearAccessChain();
4211 specNode->traverse(this);
4212 return accessChainLoad(specNode->getAsTyped()->getType());
4213 }
qining25262b32016-05-06 17:25:16 -04004214
John Kessenich6c292d32016-02-15 20:58:50 -07004215 // Otherwise, need a compile-time (front end) size, get it:
4216 int size = arraySizes.getDimSize(dim);
4217 assert(size > 0);
4218 return builder.makeUintConstant(size);
4219}
4220
John Kessenich103bef92016-02-08 21:38:15 -07004221// Wrap the builder's accessChainLoad to:
4222// - localize handling of RelaxedPrecision
4223// - use the SPIR-V inferred type instead of another conversion of the glslang type
4224// (avoids unnecessary work and possible type punning for structures)
4225// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004226spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4227{
John Kessenich103bef92016-02-08 21:38:15 -07004228 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004229
4230 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4231 coherentFlags |= TranslateCoherent(type);
4232
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004233 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004234 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004235
John Kessenich5611c6d2018-04-05 11:25:02 -06004236 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
greg-lunarg639f5462020-11-12 11:10:07 -07004237 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004238 TranslateNonUniformDecoration(type.getQualifier()),
4239 nominalTypeId,
4240 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4241 TranslateMemoryScope(coherentFlags),
4242 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004243
4244 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004245 if (type.getBasicType() == glslang::EbtBool) {
4246 if (builder.isScalarType(nominalTypeId)) {
4247 // Conversion for bool
4248 spv::Id boolType = builder.makeBoolType();
4249 if (nominalTypeId != boolType)
4250 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4251 } else if (builder.isVectorType(nominalTypeId)) {
4252 // Conversion for bvec
4253 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4254 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4255 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004256 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4257 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004258 }
4259 }
John Kessenich103bef92016-02-08 21:38:15 -07004260
4261 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004262}
4263
Rex Xu27253232016-02-23 17:51:09 +08004264// Wrap the builder's accessChainStore to:
4265// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004266//
4267// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004268void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4269{
4270 // Need to convert to abstract types when necessary
4271 if (type.getBasicType() == glslang::EbtBool) {
4272 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4273
4274 if (builder.isScalarType(nominalTypeId)) {
4275 // Conversion for bool
4276 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004277 if (nominalTypeId != boolType) {
4278 // keep these outside arguments, for determinant order-of-evaluation
4279 spv::Id one = builder.makeUintConstant(1);
4280 spv::Id zero = builder.makeUintConstant(0);
4281 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4282 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004283 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004284 } else if (builder.isVectorType(nominalTypeId)) {
4285 // Conversion for bvec
4286 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4287 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004288 if (nominalTypeId != bvecType) {
4289 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004290 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4291 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4292 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004293 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004294 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4295 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004296 }
4297 }
4298
Jeff Bolz36831c92018-09-05 10:11:41 -05004299 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4300 coherentFlags |= TranslateCoherent(type);
4301
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004302 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004303 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004304
greg-lunarg639f5462020-11-12 11:10:07 -07004305 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004306 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4307 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004308 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004309}
4310
John Kessenich4bf71552016-09-02 11:20:21 -06004311// For storing when types match at the glslang level, but not might match at the
4312// SPIR-V level.
4313//
4314// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004315// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004316// as in a member-decorated way.
4317//
4318// NOTE: This function can handle any store request; if it's not special it
4319// simplifies to a simple OpStore.
4320//
4321// Implicitly uses the existing builder.accessChain as the storage target.
4322void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4323{
John Kessenichb3e24e42016-09-11 12:33:43 -06004324 // we only do the complex path here if it's an aggregate
4325 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004326 accessChainStore(type, rValue);
4327 return;
4328 }
4329
John Kessenichb3e24e42016-09-11 12:33:43 -06004330 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004331 spv::Id rType = builder.getTypeId(rValue);
4332 spv::Id lValue = builder.accessChainGetLValue();
4333 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4334 if (lType == rType) {
4335 accessChainStore(type, rValue);
4336 return;
4337 }
4338
John Kessenichb3e24e42016-09-11 12:33:43 -06004339 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004340 // where the two types were the same type in GLSL. This requires member
4341 // by member copy, recursively.
4342
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004343 // SPIR-V 1.4 added an instruction to do help do this.
4344 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4345 // However, bool in uniform space is changed to int, so
4346 // OpCopyLogical does not work for that.
4347 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4348 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4349 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4350 if (lBool == rBool) {
4351 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4352 accessChainStore(type, logicalCopy);
4353 return;
4354 }
4355 }
4356
John Kessenichb3e24e42016-09-11 12:33:43 -06004357 // If an array, copy element by element.
4358 if (type.isArray()) {
4359 glslang::TType glslangElementType(type, 0);
4360 spv::Id elementRType = builder.getContainedTypeId(rType);
4361 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4362 // get the source member
4363 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004364
John Kessenichb3e24e42016-09-11 12:33:43 -06004365 // set up the target storage
4366 builder.clearAccessChain();
4367 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004368 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4369 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004370
John Kessenichb3e24e42016-09-11 12:33:43 -06004371 // store the member
4372 multiTypeStore(glslangElementType, elementRValue);
4373 }
4374 } else {
4375 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004376
John Kessenichb3e24e42016-09-11 12:33:43 -06004377 // loop over structure members
4378 const glslang::TTypeList& members = *type.getStruct();
4379 for (int m = 0; m < (int)members.size(); ++m) {
4380 const glslang::TType& glslangMemberType = *members[m].type;
4381
4382 // get the source member
4383 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4384 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4385
4386 // set up the target storage
4387 builder.clearAccessChain();
4388 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004389 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4390 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004391
4392 // store the member
4393 multiTypeStore(glslangMemberType, memberRValue);
4394 }
John Kessenich4bf71552016-09-02 11:20:21 -06004395 }
4396}
4397
John Kessenichf85e8062015-12-19 13:57:10 -07004398// Decide whether or not this type should be
4399// decorated with offsets and strides, and if so
4400// whether std140 or std430 rules should be applied.
4401glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004402{
John Kessenichf85e8062015-12-19 13:57:10 -07004403 // has to be a block
4404 if (type.getBasicType() != glslang::EbtBlock)
4405 return glslang::ElpNone;
4406
Chao Chen3c366992018-09-19 11:41:59 -07004407 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004408 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004409 type.getQualifier().storage != glslang::EvqBuffer &&
4410 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004411 return glslang::ElpNone;
4412
4413 // return the layout to use
4414 switch (type.getQualifier().layoutPacking) {
4415 case glslang::ElpStd140:
4416 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004417 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004418 return type.getQualifier().layoutPacking;
4419 default:
4420 return glslang::ElpNone;
4421 }
John Kessenich31ed4832015-09-09 17:51:38 -06004422}
4423
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004424// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004425int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4426 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004427{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004428 int size;
John Kessenich49987892015-12-29 17:11:44 -07004429 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004430 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4431 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004432
4433 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004434}
4435
John Kessenich49987892015-12-29 17:11:44 -07004436// 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 -07004437// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004438int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4439 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004440{
John Kessenich49987892015-12-29 17:11:44 -07004441 glslang::TType elementType;
4442 elementType.shallowCopy(matrixType);
4443 elementType.clearArraySizes();
4444
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004445 int size;
John Kessenich49987892015-12-29 17:11:44 -07004446 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004447 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4448 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004449
4450 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004451}
4452
John Kessenich5e4b1242015-08-06 22:53:06 -06004453// Given a member type of a struct, realign the current offset for it, and compute
4454// the next (not yet aligned) offset for the next member, which will get aligned
4455// on the next call.
4456// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4457// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4458// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004459void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4460 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004461{
4462 // this will get a positive value when deemed necessary
4463 nextOffset = -1;
4464
John Kessenich5e4b1242015-08-06 22:53:06 -06004465 // override anything in currentOffset with user-set offset
4466 if (memberType.getQualifier().hasOffset())
4467 currentOffset = memberType.getQualifier().layoutOffset;
4468
4469 // It could be that current linker usage in glslang updated all the layoutOffset,
4470 // in which case the following code does not matter. But, that's not quite right
4471 // once cross-compilation unit GLSL validation is done, as the original user
4472 // settings are needed in layoutOffset, and then the following will come into play.
4473
John Kessenichf85e8062015-12-19 13:57:10 -07004474 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 if (! memberType.getQualifier().hasOffset())
4476 currentOffset = -1;
4477
4478 return;
4479 }
4480
John Kessenichf85e8062015-12-19 13:57:10 -07004481 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004482 if (currentOffset < 0)
4483 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004484
John Kessenich5e4b1242015-08-06 22:53:06 -06004485 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4486 // but possibly not yet correctly aligned.
4487
4488 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004489 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004490 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4491 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004492
4493 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004494 // TODO: make this consistent in early phases of code:
4495 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4496 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4497 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004498 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004499 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004500 int dummySize;
4501 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4502 if (componentAlignment <= 4)
4503 memberAlignment = componentAlignment;
4504 }
4505
4506 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004507 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004508
4509 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004510 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4511 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004512 glslang::RoundToPow2(currentOffset, 16);
4513
John Kessenich5e4b1242015-08-06 22:53:06 -06004514 nextOffset = currentOffset + memberSize;
4515}
4516
David Netoa901ffe2016-06-08 14:11:40 +01004517void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004518{
David Netoa901ffe2016-06-08 14:11:40 +01004519 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4520 switch (glslangBuiltIn)
4521 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004522 case glslang::EbvPointSize:
4523#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004524 case glslang::EbvClipDistance:
4525 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004526 case glslang::EbvViewportMaskNV:
4527 case glslang::EbvSecondaryPositionNV:
4528 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004529 case glslang::EbvPositionPerViewNV:
4530 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004531 case glslang::EbvTaskCountNV:
4532 case glslang::EbvPrimitiveCountNV:
4533 case glslang::EbvPrimitiveIndicesNV:
4534 case glslang::EbvClipDistancePerViewNV:
4535 case glslang::EbvCullDistancePerViewNV:
4536 case glslang::EbvLayerPerViewNV:
4537 case glslang::EbvMeshViewCountNV:
4538 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004539#endif
David Netoa901ffe2016-06-08 14:11:40 +01004540 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4541 // Alternately, we could just call this for any glslang built-in, since the
4542 // capability already guards against duplicates.
4543 TranslateBuiltInDecoration(glslangBuiltIn, false);
4544 break;
4545 default:
4546 // Capabilities were already generated when the struct was declared.
4547 break;
4548 }
John Kessenichebb50532016-05-16 19:22:05 -06004549}
4550
John Kessenich6fccb3c2016-09-19 16:01:41 -06004551bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004552{
John Kessenicheee9d532016-09-19 18:09:30 -06004553 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004554}
4555
John Kessenichd41993d2017-09-10 15:21:05 -06004556// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004557// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4558// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004559bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004560{
John Kessenich6a14f782017-12-04 02:48:10 -07004561 assert(qualifier == glslang::EvqIn ||
4562 qualifier == glslang::EvqOut ||
4563 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004564 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004565 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004566 return qualifier != glslang::EvqConstReadOnly &&
4567 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004568}
4569
4570// Is parameter pass-by-original?
4571bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4572 bool implicitThisParam)
4573{
4574 if (implicitThisParam) // implicit this
4575 return true;
4576 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004577 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004578 return paramType.containsOpaque() || // sampler, etc.
4579 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4580}
4581
John Kessenich140f3df2015-06-26 16:58:36 -06004582// Make all the functions, skeletally, without actually visiting their bodies.
4583void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4584{
John Kessenich8985fc92020-03-03 10:25:07 -07004585 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4586 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004587 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4588 if (paramPrecision != spv::NoPrecision)
4589 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004590 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004591 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004592 // Original and non-writable params pass the pointer directly and
4593 // use restrict/aliased, others are stored to a pointer in Function
4594 // memory and use RestrictPointer/AliasedPointer.
4595 if (originalParam(type.getQualifier().storage, type, false) ||
4596 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004597 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4598 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004599 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004600 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4601 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004602 }
4603 }
John Kessenichfad62972017-07-18 02:35:46 -06004604 };
4605
John Kessenich140f3df2015-06-26 16:58:36 -06004606 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4607 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004608 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004609 continue;
4610
4611 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004612 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004613 //
qining25262b32016-05-06 17:25:16 -04004614 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004615 // function. What it is an address of varies:
4616 //
John Kessenich4bf71552016-09-02 11:20:21 -06004617 // - "in" parameters not marked as "const" can be written to without modifying the calling
4618 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004619 //
4620 // - "const in" parameters can just be the r-value, as no writes need occur.
4621 //
John Kessenich4bf71552016-09-02 11:20:21 -06004622 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4623 // 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 -06004624
4625 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004626 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004627 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4628
John Kessenich155d3512019-08-08 23:29:20 -06004629#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004630 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4631 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004632#else
4633 bool implicitThis = false;
4634#endif
John Kessenich37789792017-03-21 23:56:40 -06004635
John Kessenichfad62972017-07-18 02:35:46 -06004636 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004637 for (int p = 0; p < (int)parameters.size(); ++p) {
4638 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4639 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004640 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004641 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004642 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004643 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4644 else
John Kessenich4bf71552016-09-02 11:20:21 -06004645 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004646 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004647 paramTypes.push_back(typeId);
4648 }
4649
4650 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004651 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4652 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004653 glslFunction->getName().c_str(), paramTypes,
4654 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004655 if (implicitThis)
4656 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004657
4658 // Track function to emit/call later
4659 functionMap[glslFunction->getName().c_str()] = function;
4660
4661 // Set the parameter id's
4662 for (int p = 0; p < (int)parameters.size(); ++p) {
4663 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4664 // give a name too
4665 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004666
4667 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004668 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004669 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004670 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004671 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004672 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004673 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004674 }
4675 }
4676}
4677
4678// Process all the initializers, while skipping the functions and link objects
4679void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4680{
4681 builder.setBuildPoint(shaderEntry->getLastBlock());
4682 for (int i = 0; i < (int)initializers.size(); ++i) {
4683 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004684 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4685 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004686
4687 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004688 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004689 initializer->traverse(this);
4690 }
4691 }
4692}
Daniel Kochffccefd2020-11-23 15:41:27 -05004693// Walk over all linker objects to create a map for payload and callable data linker objects
4694// and their location to be used during codegen for OpTraceKHR and OpExecuteCallableKHR
4695// This is done here since it is possible that these linker objects are not be referenced in the AST
4696void TGlslangToSpvTraverser::collectRayTracingLinkerObjects()
4697{
4698 glslang::TIntermAggregate* linkerObjects = glslangIntermediate->findLinkerObjects();
4699 for (auto& objSeq : linkerObjects->getSequence()) {
4700 auto objNode = objSeq->getAsSymbolNode();
4701 if (objNode != nullptr) {
4702 if (objNode->getQualifier().hasLocation()) {
4703 unsigned int location = objNode->getQualifier().layoutLocation;
4704 auto st = objNode->getQualifier().storage;
4705 int set;
4706 switch (st)
4707 {
4708 case glslang::EvqPayload:
4709 case glslang::EvqPayloadIn:
4710 set = 0;
4711 break;
4712 case glslang::EvqCallableData:
4713 case glslang::EvqCallableDataIn:
4714 set = 1;
4715 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004716
Daniel Kochffccefd2020-11-23 15:41:27 -05004717 default:
4718 set = -1;
4719 }
4720 if (set != -1)
4721 locationToSymbol[set].insert(std::make_pair(location, objNode));
4722 }
4723 }
4724 }
4725}
John Kessenich140f3df2015-06-26 16:58:36 -06004726// Process all the functions, while skipping initializers.
4727void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4728{
4729 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4730 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004731 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004732 node->traverse(this);
4733 }
4734}
4735
4736void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4737{
qining25262b32016-05-06 17:25:16 -04004738 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004739 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004740 currentFunction = functionMap[node->getName().c_str()];
4741 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004742 builder.setBuildPoint(functionBlock);
4743}
4744
John Kessenich8985fc92020-03-03 10:25:07 -07004745void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4746 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004747{
Rex Xufc618912015-09-09 16:42:49 +08004748 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004749
4750 glslang::TSampler sampler = {};
4751 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004752#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004753 bool f16ShadowCompare = false;
4754#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004755 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004756 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4757 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004758#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004759 f16ShadowCompare = sampler.shadow &&
4760 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004761#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004762 }
4763
John Kessenich140f3df2015-06-26 16:58:36 -06004764 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4765 builder.clearAccessChain();
4766 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004767
John Kessenicha28f7a72019-08-06 07:00:58 -06004768#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004769 // Special case l-value operands
4770 bool lvalue = false;
4771 switch (node.getOp()) {
4772 case glslang::EOpImageAtomicAdd:
4773 case glslang::EOpImageAtomicMin:
4774 case glslang::EOpImageAtomicMax:
4775 case glslang::EOpImageAtomicAnd:
4776 case glslang::EOpImageAtomicOr:
4777 case glslang::EOpImageAtomicXor:
4778 case glslang::EOpImageAtomicExchange:
4779 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004780 case glslang::EOpImageAtomicLoad:
4781 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004782 if (i == 0)
4783 lvalue = true;
4784 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004785 case glslang::EOpSparseImageLoad:
4786 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4787 lvalue = true;
4788 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004789 case glslang::EOpSparseTexture:
4790 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4791 lvalue = true;
4792 break;
4793 case glslang::EOpSparseTextureClamp:
4794 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4795 lvalue = true;
4796 break;
4797 case glslang::EOpSparseTextureLod:
4798 case glslang::EOpSparseTextureOffset:
4799 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4800 lvalue = true;
4801 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004802 case glslang::EOpSparseTextureFetch:
4803 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4804 lvalue = true;
4805 break;
4806 case glslang::EOpSparseTextureFetchOffset:
4807 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4808 lvalue = true;
4809 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004810 case glslang::EOpSparseTextureLodOffset:
4811 case glslang::EOpSparseTextureGrad:
4812 case glslang::EOpSparseTextureOffsetClamp:
4813 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4814 lvalue = true;
4815 break;
4816 case glslang::EOpSparseTextureGradOffset:
4817 case glslang::EOpSparseTextureGradClamp:
4818 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4819 lvalue = true;
4820 break;
4821 case glslang::EOpSparseTextureGradOffsetClamp:
4822 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4823 lvalue = true;
4824 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004825 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004826 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4827 lvalue = true;
4828 break;
4829 case glslang::EOpSparseTextureGatherOffset:
4830 case glslang::EOpSparseTextureGatherOffsets:
4831 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4832 lvalue = true;
4833 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004834 case glslang::EOpSparseTextureGatherLod:
4835 if (i == 3)
4836 lvalue = true;
4837 break;
4838 case glslang::EOpSparseTextureGatherLodOffset:
4839 case glslang::EOpSparseTextureGatherLodOffsets:
4840 if (i == 4)
4841 lvalue = true;
4842 break;
Rex Xu129799a2017-07-05 17:23:28 +08004843 case glslang::EOpSparseImageLoadLod:
4844 if (i == 3)
4845 lvalue = true;
4846 break;
Chao Chen3a137962018-09-19 11:41:27 -07004847 case glslang::EOpImageSampleFootprintNV:
4848 if (i == 4)
4849 lvalue = true;
4850 break;
4851 case glslang::EOpImageSampleFootprintClampNV:
4852 case glslang::EOpImageSampleFootprintLodNV:
4853 if (i == 5)
4854 lvalue = true;
4855 break;
4856 case glslang::EOpImageSampleFootprintGradNV:
4857 if (i == 6)
4858 lvalue = true;
4859 break;
4860 case glslang::EOpImageSampleFootprintGradClampNV:
4861 if (i == 7)
4862 lvalue = true;
4863 break;
Rex Xufc618912015-09-09 16:42:49 +08004864 default:
4865 break;
4866 }
4867
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004868 if (lvalue) {
greg-lunarg639f5462020-11-12 11:10:07 -07004869 spv::Id lvalue_id = builder.accessChainGetLValue();
4870 arguments.push_back(lvalue_id);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004871 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
greg-lunarg639f5462020-11-12 11:10:07 -07004872 builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004873 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4874 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004875#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004876 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004877 }
4878}
4879
John Kessenichfc51d282015-08-19 13:34:18 -06004880void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004881{
John Kessenichfc51d282015-08-19 13:34:18 -06004882 builder.clearAccessChain();
4883 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004884 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004885}
John Kessenich140f3df2015-06-26 16:58:36 -06004886
John Kessenichfc51d282015-08-19 13:34:18 -06004887spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4888{
John Kesseniche485c7a2017-05-31 18:50:53 -06004889 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004890 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004891
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004892 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004893
John Kessenichfc51d282015-08-19 13:34:18 -06004894 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004895
John Kessenichf43c7392019-03-31 10:51:57 -06004896 const glslang::TType &imageType = node->getAsAggregate()
4897 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4898 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004899 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004900#ifdef GLSLANG_WEB
4901 const bool f16ShadowCompare = false;
4902#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004903 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004904 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4905 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004906#endif
4907
John Kessenichf43c7392019-03-31 10:51:57 -06004908 const auto signExtensionMask = [&]() {
4909 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4910 if (sampler.type == glslang::EbtUint)
4911 return spv::ImageOperandsZeroExtendMask;
4912 else if (sampler.type == glslang::EbtInt)
4913 return spv::ImageOperandsSignExtendMask;
4914 }
4915 return spv::ImageOperandsMaskNone;
4916 };
4917
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004918 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4919
John Kessenichfc51d282015-08-19 13:34:18 -06004920 std::vector<spv::Id> arguments;
4921 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004922 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004923 else
4924 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004925 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004926
4927 spv::Builder::TextureParameters params = { };
4928 params.sampler = arguments[0];
4929
Rex Xu04db3f52015-09-16 11:44:02 +08004930 glslang::TCrackedTextureOp cracked;
4931 node->crackTexture(sampler, cracked);
4932
amhagan05506bb2017-06-13 16:53:02 -04004933 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004934
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004935 if (builder.isSampledImage(params.sampler) &&
4936 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4937 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4938 if (imageType.getQualifier().isNonUniform()) {
4939 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4940 }
4941 }
John Kessenichfc51d282015-08-19 13:34:18 -06004942 // Check for queries
4943 if (cracked.query) {
4944 switch (node->getOp()) {
4945 case glslang::EOpImageQuerySize:
4946 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004947 if (arguments.size() > 1) {
4948 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004949 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004950 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004951 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004952#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004953 case glslang::EOpImageQuerySamples:
4954 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004955 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004956 case glslang::EOpTextureQueryLod:
4957 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004958 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004959 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004960 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004961 case glslang::EOpSparseTexelsResident:
4962 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004963#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004964 default:
4965 assert(0);
4966 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004967 }
John Kessenich140f3df2015-06-26 16:58:36 -06004968 }
4969
LoopDawg4425f242018-02-18 11:40:01 -07004970 int components = node->getType().getVectorSize();
4971
4972 if (node->getOp() == glslang::EOpTextureFetch) {
4973 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4974 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4975 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4976 // here around e.g. which ones return scalars or other types.
4977 components = 4;
4978 }
4979
4980 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4981
4982 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4983
Rex Xufc618912015-09-09 16:42:49 +08004984 // Check for image functions other than queries
4985 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004986 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004987 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004988 spv::IdImmediate image = { true, *(opIt++) };
4989 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004990
4991 // Handle subpass operations
4992 // TODO: GLSL should change to have the "MS" only on the type rather than the
4993 // built-in function.
4994 if (cracked.subpass) {
4995 // add on the (0,0) coordinate
4996 spv::Id zero = builder.makeIntConstant(0);
4997 std::vector<spv::Id> comps;
4998 comps.push_back(zero);
4999 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06005000 spv::IdImmediate coord = { true,
5001 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
5002 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06005003 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
5004 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005005 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005006 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
5007 }
5008 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06005009 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005010 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005011 spv::IdImmediate imageOperand = { true, *(opIt++) };
5012 operands.push_back(imageOperand);
5013 }
John Kessenich6c292d32016-02-15 20:58:50 -07005014 }
John Kessenichfe4e5722017-10-19 02:07:30 -06005015 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
5016 builder.setPrecision(result, precision);
5017 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07005018 }
5019
John Kessenich149afc32018-08-14 13:31:43 -06005020 spv::IdImmediate coord = { true, *(opIt++) };
5021 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08005022 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005023 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005024 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005025 mask = mask | spv::ImageOperandsSampleMask;
5026 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005027 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005028 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5029 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05005030 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07005031 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005032 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5033 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005034 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005035 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005036 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5037 operands.push_back(imageOperands);
5038 }
5039 if (mask & spv::ImageOperandsSampleMask) {
5040 spv::IdImmediate imageOperand = { true, *opIt++ };
5041 operands.push_back(imageOperand);
5042 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005043 if (mask & spv::ImageOperandsLodMask) {
5044 spv::IdImmediate imageOperand = { true, *opIt++ };
5045 operands.push_back(imageOperand);
5046 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005047 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005048 spv::IdImmediate imageOperand = { true,
5049 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005050 operands.push_back(imageOperand);
5051 }
5052
John Kessenich149afc32018-08-14 13:31:43 -06005053 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005054 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06005055
John Kessenich149afc32018-08-14 13:31:43 -06005056 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07005057 builder.setPrecision(result[0], precision);
5058
5059 // If needed, add a conversion constructor to the proper size.
5060 if (components != node->getType().getVectorSize())
5061 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5062
5063 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08005064 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08005065
Jeff Bolz36831c92018-09-05 10:11:41 -05005066 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005067 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06005068 spv::IdImmediate texel = { true, *(opIt + 1) };
5069 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06005070 } else {
5071 spv::IdImmediate texel = { true, *opIt };
5072 operands.push_back(texel);
5073 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005074
5075 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005076 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005077 mask = mask | spv::ImageOperandsSampleMask;
5078 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005079 if (cracked.lod) {
5080 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5081 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5082 mask = mask | spv::ImageOperandsLodMask;
5083 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005084 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5085 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005086 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005087 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005088 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5089 operands.push_back(imageOperands);
5090 }
5091 if (mask & spv::ImageOperandsSampleMask) {
5092 spv::IdImmediate imageOperand = { true, *opIt++ };
5093 operands.push_back(imageOperand);
5094 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005095 if (mask & spv::ImageOperandsLodMask) {
5096 spv::IdImmediate imageOperand = { true, *opIt++ };
5097 operands.push_back(imageOperand);
5098 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005099 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005100 spv::IdImmediate imageOperand = { true,
5101 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005102 operands.push_back(imageOperand);
5103 }
5104
John Kessenich56bab042015-09-16 10:54:31 -06005105 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06005106 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005107 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06005108 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06005109 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
5110 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08005111 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06005112 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08005113 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
5114
Jeff Bolz36831c92018-09-05 10:11:41 -05005115 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005116 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005117 mask = mask | spv::ImageOperandsSampleMask;
5118 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005119 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005120 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5121 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5122
Jeff Bolz36831c92018-09-05 10:11:41 -05005123 mask = mask | spv::ImageOperandsLodMask;
5124 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005125 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5126 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005127 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005128 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005129 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06005130 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05005131 }
5132 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06005133 spv::IdImmediate imageOperand = { true, *opIt++ };
5134 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05005135 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005136 if (mask & spv::ImageOperandsLodMask) {
5137 spv::IdImmediate imageOperand = { true, *opIt++ };
5138 operands.push_back(imageOperand);
5139 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005140 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005141 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5142 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005143 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005144 }
5145
5146 // Create the return type that was a special structure
5147 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005148 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005149 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5150 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5151
5152 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5153
5154 // Decode the return type
5155 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5156 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005157 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005158 // Process image atomic operations
5159
5160 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5161 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005162 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005163 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005164 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005165
Jeff Bolz36831c92018-09-05 10:11:41 -05005166 spv::Id resultTypeId;
5167 // imageAtomicStore has a void return type so base the pointer type on
5168 // the type of the value operand.
5169 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005170 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005171 } else {
5172 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5173 }
John Kessenich56bab042015-09-16 10:54:31 -06005174 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005175 if (imageType.getQualifier().nonUniform) {
5176 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5177 }
Rex Xufc618912015-09-09 16:42:49 +08005178
5179 std::vector<spv::Id> operands;
5180 operands.push_back(pointer);
5181 for (; opIt != arguments.end(); ++opIt)
5182 operands.push_back(*opIt);
5183
John Kessenich8985fc92020-03-03 10:25:07 -07005184 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5185 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005186 }
5187 }
5188
John Kessenicha28f7a72019-08-06 07:00:58 -06005189#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005190 // Check for fragment mask functions other than queries
5191 if (cracked.fragMask) {
5192 assert(sampler.ms);
5193
5194 auto opIt = arguments.begin();
5195 std::vector<spv::Id> operands;
5196
amhagan05506bb2017-06-13 16:53:02 -04005197 operands.push_back(params.sampler);
5198 ++opIt;
5199
5200 if (sampler.isSubpass()) {
5201 // add on the (0,0) coordinate
5202 spv::Id zero = builder.makeIntConstant(0);
5203 std::vector<spv::Id> comps;
5204 comps.push_back(zero);
5205 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005206 operands.push_back(builder.makeCompositeConstant(
5207 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005208 }
5209
5210 for (; opIt != arguments.end(); ++opIt)
5211 operands.push_back(*opIt);
5212
5213 spv::Op fragMaskOp = spv::OpNop;
5214 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5215 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5216 else if (node->getOp() == glslang::EOpFragmentFetch)
5217 fragMaskOp = spv::OpFragmentFetchAMD;
5218
5219 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5220 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5221 return builder.createOp(fragMaskOp, resultType(), operands);
5222 }
5223#endif
5224
Rex Xufc618912015-09-09 16:42:49 +08005225 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005226 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005227 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005228 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005229
John Kessenichfc51d282015-08-19 13:34:18 -06005230 // check for bias argument
5231 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005232 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005233 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005234 if (cracked.gather)
5235 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005236
5237 if (f16ShadowCompare)
5238 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005239 if (cracked.offset)
5240 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005241 else if (cracked.offsets)
5242 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005243 if (cracked.grad)
5244 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005245 if (cracked.lodClamp)
5246 ++nonBiasArgCount;
5247 if (sparse)
5248 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005249 if (imageFootprint)
5250 //Following three extra arguments
5251 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5252 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005253 if ((int)arguments.size() > nonBiasArgCount)
5254 bias = true;
5255 }
5256
John Kessenicha28f7a72019-08-06 07:00:58 -06005257#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005258 if (cracked.gather) {
5259 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5260 if (bias || cracked.lod ||
5261 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5262 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005263 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005264 }
5265 }
5266#endif
5267
John Kessenichfc51d282015-08-19 13:34:18 -06005268 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005269
John Kessenichfc51d282015-08-19 13:34:18 -06005270 params.coords = arguments[1];
5271 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005272 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005273
5274 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005275 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005276 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005277 ++extraArgs;
5278 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005279 params.Dref = arguments[2];
5280 ++extraArgs;
5281 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005282 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005283 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005284 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005285 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005286 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005287 dRefComp = builder.getNumComponents(params.coords) - 1;
5288 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005289 params.Dref = builder.createCompositeExtract(params.coords,
5290 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005291 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005292
5293 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005294 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005295 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005296 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005297 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5298 !(glslangIntermediate->getStage() == EShLangCompute &&
5299 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005300 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5301 noImplicitLod = true;
5302 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005303
5304 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005305 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005306 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005307 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005308 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005309
5310 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005311 if (cracked.grad) {
5312 params.gradX = arguments[2 + extraArgs];
5313 params.gradY = arguments[3 + extraArgs];
5314 extraArgs += 2;
5315 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005316
5317 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005318 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005319 params.offset = arguments[2 + extraArgs];
5320 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005321 } else if (cracked.offsets) {
5322 params.offsets = arguments[2 + extraArgs];
5323 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005324 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005325
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005326#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005327 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005328 if (cracked.lodClamp) {
5329 params.lodClamp = arguments[2 + extraArgs];
5330 ++extraArgs;
5331 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005332 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005333 if (sparse) {
5334 params.texelOut = arguments[2 + extraArgs];
5335 ++extraArgs;
5336 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005337 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005338 if (cracked.gather && ! sampler.shadow) {
5339 // default component is 0, if missing, otherwise an argument
5340 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005341 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005342 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005343 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005344 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005345 }
Chao Chen3a137962018-09-19 11:41:27 -07005346 spv::Id resultStruct = spv::NoResult;
5347 if (imageFootprint) {
5348 //Following three extra arguments
5349 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5350 params.granularity = arguments[2 + extraArgs];
5351 params.coarse = arguments[3 + extraArgs];
5352 resultStruct = arguments[4 + extraArgs];
5353 extraArgs += 3;
5354 }
5355#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005356 // bias
5357 if (bias) {
5358 params.bias = arguments[2 + extraArgs];
5359 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005360 }
John Kessenichfc51d282015-08-19 13:34:18 -06005361
John Kessenicha28f7a72019-08-06 07:00:58 -06005362#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005363 if (imageFootprint) {
5364 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5365 builder.addCapability(spv::CapabilityImageFootprintNV);
5366
5367
5368 //resultStructType(OpenGL type) contains 5 elements:
5369 //struct gl_TextureFootprint2DNV {
5370 // uvec2 anchor;
5371 // uvec2 offset;
5372 // uvec2 mask;
5373 // uint lod;
5374 // uint granularity;
5375 //};
5376 //or
5377 //struct gl_TextureFootprint3DNV {
5378 // uvec3 anchor;
5379 // uvec3 offset;
5380 // uvec2 mask;
5381 // uint lod;
5382 // uint granularity;
5383 //};
5384 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5385 assert(builder.isStructType(resultStructType));
5386
5387 //resType (SPIR-V type) contains 6 elements:
5388 //Member 0 must be a Boolean type scalar(LOD),
5389 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5390 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5391 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5392 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5393 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5394 std::vector<spv::Id> members;
5395 members.push_back(resultType());
5396 for (int i = 0; i < 5; i++) {
5397 members.push_back(builder.getContainedTypeId(resultStructType, i));
5398 }
5399 spv::Id resType = builder.makeStructType(members, "ResType");
5400
5401 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005402 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5403 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005404
5405 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5406 for (int i = 0; i < 5; i++) {
5407 builder.clearAccessChain();
5408 builder.setAccessChainLValue(resultStruct);
5409
5410 //Accessing to a struct we created, no coherent flag is set
5411 spv::Builder::AccessChain::CoherentFlags flags;
5412 flags.clear();
5413
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005414 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005415 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005416 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005417 }
5418 return builder.createCompositeExtract(res, resultType(), 0);
5419 }
5420#endif
5421
John Kessenich65336482016-06-16 14:06:26 -06005422 // projective component (might not to move)
5423 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5424 // are divided by the last component of P."
5425 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5426 // unused components will appear after all used components."
5427 if (cracked.proj) {
5428 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5429 int projTargetComp;
5430 switch (sampler.dim) {
5431 case glslang::Esd1D: projTargetComp = 1; break;
5432 case glslang::Esd2D: projTargetComp = 2; break;
5433 case glslang::EsdRect: projTargetComp = 2; break;
5434 default: projTargetComp = projSourceComp; break;
5435 }
5436 // copy the projective coordinate if we have to
5437 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005438 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005439 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005440 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005441 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005442 }
5443 }
5444
John Kessenichf8d1d742019-10-21 06:55:11 -06005445#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005446 // nonprivate
5447 if (imageType.getQualifier().nonprivate) {
5448 params.nonprivate = true;
5449 }
5450
5451 // volatile
5452 if (imageType.getQualifier().volatil) {
5453 params.volatil = true;
5454 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005455#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005456
St0fFa1184dd2018-04-09 21:08:14 +02005457 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005458 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5459 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005460 );
LoopDawg4425f242018-02-18 11:40:01 -07005461
5462 if (components != node->getType().getVectorSize())
5463 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5464
5465 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005466}
5467
5468spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5469{
5470 // Grab the function's pointer from the previously created function
5471 spv::Function* function = functionMap[node->getName().c_str()];
5472 if (! function)
5473 return 0;
5474
5475 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5476 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5477
5478 // See comments in makeFunctions() for details about the semantics for parameter passing.
5479 //
5480 // These imply we need a four step process:
5481 // 1. Evaluate the arguments
5482 // 2. Allocate and make copies of in, out, and inout arguments
5483 // 3. Make the call
5484 // 4. Copy back the results
5485
John Kessenichd3ed90b2018-05-04 11:43:03 -06005486 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005487 std::vector<spv::Builder::AccessChain> lValues;
5488 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005489 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005491 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005492 // build l-value
5493 builder.clearAccessChain();
5494 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005495 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005496 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005497 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005498 // save l-value
5499 lValues.push_back(builder.getAccessChain());
5500 } else {
5501 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005502 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005503 }
5504 }
5505
5506 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5507 // copy the original into that space.
5508 //
5509 // Also, build up the list of actual arguments to pass in for the call
5510 int lValueCount = 0;
5511 int rValueCount = 0;
5512 std::vector<spv::Id> spvArgs;
5513 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5514 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005515 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005516 builder.setAccessChain(lValues[lValueCount]);
5517 arg = builder.accessChainGetLValue();
5518 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005519 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005520 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005521 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005522 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005523 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5524 // need to copy the input into output space
5525 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005526 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005527 builder.clearAccessChain();
5528 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005529 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005530 }
5531 ++lValueCount;
5532 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005533 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005534 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005535 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005536 {
John Kessenich435dd802020-06-30 01:27:08 -06005537 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005538 builder.clearAccessChain();
5539 builder.setAccessChainLValue(argCopy);
5540 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005541 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005542 } else
5543 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005544 ++rValueCount;
5545 }
5546 spvArgs.push_back(arg);
5547 }
5548
5549 // 3. Make the call.
5550 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005551 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
greg-lunarg639f5462020-11-12 11:10:07 -07005552 builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005553
5554 // 4. Copy back out an "out" arguments.
5555 lValueCount = 0;
5556 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005557 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005558 ++lValueCount;
5559 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005560 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005561 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
greg-lunarg639f5462020-11-12 11:10:07 -07005562 builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005563 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005564 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005565 }
5566 ++lValueCount;
5567 }
5568 }
5569
5570 return result;
5571}
5572
5573// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005574spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005575 spv::Id typeId, spv::Id left, spv::Id right,
5576 glslang::TBasicType typeProxy, bool reduceComparison)
5577{
John Kessenich66011cb2018-03-06 16:12:04 -07005578 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5579 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005580 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005581
5582 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005583 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005584 bool comparison = false;
5585
5586 switch (op) {
5587 case glslang::EOpAdd:
5588 case glslang::EOpAddAssign:
5589 if (isFloat)
5590 binOp = spv::OpFAdd;
5591 else
5592 binOp = spv::OpIAdd;
5593 break;
5594 case glslang::EOpSub:
5595 case glslang::EOpSubAssign:
5596 if (isFloat)
5597 binOp = spv::OpFSub;
5598 else
5599 binOp = spv::OpISub;
5600 break;
5601 case glslang::EOpMul:
5602 case glslang::EOpMulAssign:
5603 if (isFloat)
5604 binOp = spv::OpFMul;
5605 else
5606 binOp = spv::OpIMul;
5607 break;
5608 case glslang::EOpVectorTimesScalar:
5609 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005610 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005611 if (builder.isVector(right))
5612 std::swap(left, right);
5613 assert(builder.isScalar(right));
5614 needMatchingVectors = false;
5615 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005616 } else if (isFloat)
5617 binOp = spv::OpFMul;
5618 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005619 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005620 break;
5621 case glslang::EOpVectorTimesMatrix:
5622 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005623 binOp = spv::OpVectorTimesMatrix;
5624 break;
5625 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005626 binOp = spv::OpMatrixTimesVector;
5627 break;
5628 case glslang::EOpMatrixTimesScalar:
5629 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005630 binOp = spv::OpMatrixTimesScalar;
5631 break;
5632 case glslang::EOpMatrixTimesMatrix:
5633 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005634 binOp = spv::OpMatrixTimesMatrix;
5635 break;
5636 case glslang::EOpOuterProduct:
5637 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005638 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005639 break;
5640
5641 case glslang::EOpDiv:
5642 case glslang::EOpDivAssign:
5643 if (isFloat)
5644 binOp = spv::OpFDiv;
5645 else if (isUnsigned)
5646 binOp = spv::OpUDiv;
5647 else
5648 binOp = spv::OpSDiv;
5649 break;
5650 case glslang::EOpMod:
5651 case glslang::EOpModAssign:
5652 if (isFloat)
5653 binOp = spv::OpFMod;
5654 else if (isUnsigned)
5655 binOp = spv::OpUMod;
5656 else
5657 binOp = spv::OpSMod;
5658 break;
5659 case glslang::EOpRightShift:
5660 case glslang::EOpRightShiftAssign:
5661 if (isUnsigned)
5662 binOp = spv::OpShiftRightLogical;
5663 else
5664 binOp = spv::OpShiftRightArithmetic;
5665 break;
5666 case glslang::EOpLeftShift:
5667 case glslang::EOpLeftShiftAssign:
5668 binOp = spv::OpShiftLeftLogical;
5669 break;
5670 case glslang::EOpAnd:
5671 case glslang::EOpAndAssign:
5672 binOp = spv::OpBitwiseAnd;
5673 break;
5674 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005675 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005676 binOp = spv::OpLogicalAnd;
5677 break;
5678 case glslang::EOpInclusiveOr:
5679 case glslang::EOpInclusiveOrAssign:
5680 binOp = spv::OpBitwiseOr;
5681 break;
5682 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005683 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005684 binOp = spv::OpLogicalOr;
5685 break;
5686 case glslang::EOpExclusiveOr:
5687 case glslang::EOpExclusiveOrAssign:
5688 binOp = spv::OpBitwiseXor;
5689 break;
5690 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005691 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005692 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005693 break;
5694
Ian Romanickb3bd4022019-01-21 08:57:25 -08005695 case glslang::EOpAbsDifference:
5696 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5697 break;
5698
5699 case glslang::EOpAddSaturate:
5700 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5701 break;
5702
5703 case glslang::EOpSubSaturate:
5704 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5705 break;
5706
5707 case glslang::EOpAverage:
5708 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5709 break;
5710
5711 case glslang::EOpAverageRounded:
5712 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5713 break;
5714
5715 case glslang::EOpMul32x16:
5716 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5717 break;
5718
John Kessenich140f3df2015-06-26 16:58:36 -06005719 case glslang::EOpLessThan:
5720 case glslang::EOpGreaterThan:
5721 case glslang::EOpLessThanEqual:
5722 case glslang::EOpGreaterThanEqual:
5723 case glslang::EOpEqual:
5724 case glslang::EOpNotEqual:
5725 case glslang::EOpVectorEqual:
5726 case glslang::EOpVectorNotEqual:
5727 comparison = true;
5728 break;
5729 default:
5730 break;
5731 }
5732
John Kessenich7c1aa102015-10-15 13:29:11 -06005733 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005734 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005735 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005736 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5737 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005738 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005739
5740 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005741 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005742 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005743
qining25262b32016-05-06 17:25:16 -04005744 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005745 decorations.addNoContraction(builder, result);
5746 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005747 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005748 }
5749
5750 if (! comparison)
5751 return 0;
5752
John Kessenich7c1aa102015-10-15 13:29:11 -06005753 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005754
John Kessenich4583b612016-08-07 19:14:22 -06005755 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005756 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5757 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005758 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005759 return result;
5760 }
John Kessenich140f3df2015-06-26 16:58:36 -06005761
5762 switch (op) {
5763 case glslang::EOpLessThan:
5764 if (isFloat)
5765 binOp = spv::OpFOrdLessThan;
5766 else if (isUnsigned)
5767 binOp = spv::OpULessThan;
5768 else
5769 binOp = spv::OpSLessThan;
5770 break;
5771 case glslang::EOpGreaterThan:
5772 if (isFloat)
5773 binOp = spv::OpFOrdGreaterThan;
5774 else if (isUnsigned)
5775 binOp = spv::OpUGreaterThan;
5776 else
5777 binOp = spv::OpSGreaterThan;
5778 break;
5779 case glslang::EOpLessThanEqual:
5780 if (isFloat)
5781 binOp = spv::OpFOrdLessThanEqual;
5782 else if (isUnsigned)
5783 binOp = spv::OpULessThanEqual;
5784 else
5785 binOp = spv::OpSLessThanEqual;
5786 break;
5787 case glslang::EOpGreaterThanEqual:
5788 if (isFloat)
5789 binOp = spv::OpFOrdGreaterThanEqual;
5790 else if (isUnsigned)
5791 binOp = spv::OpUGreaterThanEqual;
5792 else
5793 binOp = spv::OpSGreaterThanEqual;
5794 break;
5795 case glslang::EOpEqual:
5796 case glslang::EOpVectorEqual:
5797 if (isFloat)
5798 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005799 else if (isBool)
5800 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005801 else
5802 binOp = spv::OpIEqual;
5803 break;
5804 case glslang::EOpNotEqual:
5805 case glslang::EOpVectorNotEqual:
5806 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005807 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005808 else if (isBool)
5809 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005810 else
5811 binOp = spv::OpINotEqual;
5812 break;
5813 default:
5814 break;
5815 }
5816
qining25262b32016-05-06 17:25:16 -04005817 if (binOp != spv::OpNop) {
5818 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005819 decorations.addNoContraction(builder, result);
5820 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005821 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005822 }
John Kessenich140f3df2015-06-26 16:58:36 -06005823
5824 return 0;
5825}
5826
John Kessenich04bb8a02015-12-12 12:28:14 -07005827//
5828// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5829// These can be any of:
5830//
5831// matrix * scalar
5832// scalar * matrix
5833// matrix * matrix linear algebraic
5834// matrix * vector
5835// vector * matrix
5836// matrix * matrix componentwise
5837// matrix op matrix op in {+, -, /}
5838// matrix op scalar op in {+, -, /}
5839// scalar op matrix op in {+, -, /}
5840//
John Kessenichead86222018-03-28 18:01:20 -06005841spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5842 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005843{
5844 bool firstClass = true;
5845
5846 // First, handle first-class matrix operations (* and matrix/scalar)
5847 switch (op) {
5848 case spv::OpFDiv:
5849 if (builder.isMatrix(left) && builder.isScalar(right)) {
5850 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005851 spv::Id resultType = builder.getTypeId(right);
5852 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005853 op = spv::OpMatrixTimesScalar;
5854 } else
5855 firstClass = false;
5856 break;
5857 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005858 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005859 std::swap(left, right);
5860 assert(builder.isScalar(right));
5861 break;
5862 case spv::OpVectorTimesMatrix:
5863 assert(builder.isVector(left));
5864 assert(builder.isMatrix(right));
5865 break;
5866 case spv::OpMatrixTimesVector:
5867 assert(builder.isMatrix(left));
5868 assert(builder.isVector(right));
5869 break;
5870 case spv::OpMatrixTimesMatrix:
5871 assert(builder.isMatrix(left));
5872 assert(builder.isMatrix(right));
5873 break;
5874 default:
5875 firstClass = false;
5876 break;
5877 }
5878
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005879 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5880 firstClass = true;
5881
qining25262b32016-05-06 17:25:16 -04005882 if (firstClass) {
5883 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005884 decorations.addNoContraction(builder, result);
5885 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005886 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005887 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005888
LoopDawg592860c2016-06-09 08:57:35 -06005889 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005890 // The result type of all of them is the same type as the (a) matrix operand.
5891 // The algorithm is to:
5892 // - break the matrix(es) into vectors
5893 // - smear any scalar to a vector
5894 // - do vector operations
5895 // - make a matrix out the vector results
5896 switch (op) {
5897 case spv::OpFAdd:
5898 case spv::OpFSub:
5899 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005900 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005901 case spv::OpFMul:
5902 {
5903 // one time set up...
5904 bool leftMat = builder.isMatrix(left);
5905 bool rightMat = builder.isMatrix(right);
5906 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5907 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5908 spv::Id scalarType = builder.getScalarTypeId(typeId);
5909 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5910 std::vector<spv::Id> results;
5911 spv::Id smearVec = spv::NoResult;
5912 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005913 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005914 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005915 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005916
5917 // do each vector op
5918 for (unsigned int c = 0; c < numCols; ++c) {
5919 std::vector<unsigned int> indexes;
5920 indexes.push_back(c);
5921 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5922 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005923 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005924 decorations.addNoContraction(builder, result);
5925 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005926 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005927 }
5928
5929 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005930 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005931 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005932 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005933 }
5934 default:
5935 assert(0);
5936 return spv::NoResult;
5937 }
5938}
5939
John Kessenichead86222018-03-28 18:01:20 -06005940spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005941 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005942{
5943 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005944 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005945 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005946 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5947 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005948
5949 switch (op) {
5950 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005951 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005952 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005953 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005954 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005955 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005956 unaryOp = spv::OpSNegate;
5957 break;
5958
5959 case glslang::EOpLogicalNot:
5960 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005961 unaryOp = spv::OpLogicalNot;
5962 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005963 case glslang::EOpBitwiseNot:
5964 unaryOp = spv::OpNot;
5965 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005966
John Kessenich140f3df2015-06-26 16:58:36 -06005967 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005968 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005969 break;
5970 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005971 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005972 break;
5973 case glslang::EOpTranspose:
5974 unaryOp = spv::OpTranspose;
5975 break;
5976
5977 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005978 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005979 break;
5980 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005981 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005982 break;
5983 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005984 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005985 break;
5986 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005987 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005988 break;
5989 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005990 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005991 break;
5992 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005993 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005994 break;
5995 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005996 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005997 break;
5998 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005999 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06006000 break;
6001
6002 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006003 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006004 break;
6005 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006006 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006007 break;
6008 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006009 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006010 break;
6011 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006012 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006013 break;
6014 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006015 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006016 break;
6017 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006018 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006019 break;
6020
6021 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06006022 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06006023 break;
6024 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06006025 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06006026 break;
6027
6028 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006029 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06006030 break;
6031 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06006032 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06006033 break;
6034 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006035 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06006036 break;
6037 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006038 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06006039 break;
6040 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006041 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006042 break;
6043 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006044 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006045 break;
6046
6047 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06006048 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06006049 break;
6050 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06006051 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06006052 break;
6053 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06006054 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06006055 break;
6056 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06006057 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06006058 break;
6059 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06006060 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06006061 break;
6062 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006063 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06006064 break;
6065
6066 case glslang::EOpIsNan:
6067 unaryOp = spv::OpIsNan;
6068 break;
6069 case glslang::EOpIsInf:
6070 unaryOp = spv::OpIsInf;
6071 break;
LoopDawg592860c2016-06-09 08:57:35 -06006072 case glslang::EOpIsFinite:
6073 unaryOp = spv::OpIsFinite;
6074 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006075
Rex Xucbc426e2015-12-15 16:03:10 +08006076 case glslang::EOpFloatBitsToInt:
6077 case glslang::EOpFloatBitsToUint:
6078 case glslang::EOpIntBitsToFloat:
6079 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08006080 case glslang::EOpDoubleBitsToInt64:
6081 case glslang::EOpDoubleBitsToUint64:
6082 case glslang::EOpInt64BitsToDouble:
6083 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08006084 case glslang::EOpFloat16BitsToInt16:
6085 case glslang::EOpFloat16BitsToUint16:
6086 case glslang::EOpInt16BitsToFloat16:
6087 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08006088 unaryOp = spv::OpBitcast;
6089 break;
6090
John Kessenich140f3df2015-06-26 16:58:36 -06006091 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006092 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006093 break;
6094 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006095 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006096 break;
6097 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006098 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006099 break;
6100 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006101 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006102 break;
6103 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006104 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006105 break;
6106 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006107 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006108 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006109#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06006110 case glslang::EOpPackSnorm4x8:
6111 libCall = spv::GLSLstd450PackSnorm4x8;
6112 break;
6113 case glslang::EOpUnpackSnorm4x8:
6114 libCall = spv::GLSLstd450UnpackSnorm4x8;
6115 break;
6116 case glslang::EOpPackUnorm4x8:
6117 libCall = spv::GLSLstd450PackUnorm4x8;
6118 break;
6119 case glslang::EOpUnpackUnorm4x8:
6120 libCall = spv::GLSLstd450UnpackUnorm4x8;
6121 break;
6122 case glslang::EOpPackDouble2x32:
6123 libCall = spv::GLSLstd450PackDouble2x32;
6124 break;
6125 case glslang::EOpUnpackDouble2x32:
6126 libCall = spv::GLSLstd450UnpackDouble2x32;
6127 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006128#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006129
Rex Xu8ff43de2016-04-22 16:51:45 +08006130 case glslang::EOpPackInt2x32:
6131 case glslang::EOpUnpackInt2x32:
6132 case glslang::EOpPackUint2x32:
6133 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07006134 case glslang::EOpPack16:
6135 case glslang::EOpPack32:
6136 case glslang::EOpPack64:
6137 case glslang::EOpUnpack32:
6138 case glslang::EOpUnpack16:
6139 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006140 case glslang::EOpPackInt2x16:
6141 case glslang::EOpUnpackInt2x16:
6142 case glslang::EOpPackUint2x16:
6143 case glslang::EOpUnpackUint2x16:
6144 case glslang::EOpPackInt4x16:
6145 case glslang::EOpUnpackInt4x16:
6146 case glslang::EOpPackUint4x16:
6147 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006148 case glslang::EOpPackFloat2x16:
6149 case glslang::EOpUnpackFloat2x16:
6150 unaryOp = spv::OpBitcast;
6151 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006152
John Kessenich140f3df2015-06-26 16:58:36 -06006153 case glslang::EOpDPdx:
6154 unaryOp = spv::OpDPdx;
6155 break;
6156 case glslang::EOpDPdy:
6157 unaryOp = spv::OpDPdy;
6158 break;
6159 case glslang::EOpFwidth:
6160 unaryOp = spv::OpFwidth;
6161 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006162
John Kessenich140f3df2015-06-26 16:58:36 -06006163 case glslang::EOpAny:
6164 unaryOp = spv::OpAny;
6165 break;
6166 case glslang::EOpAll:
6167 unaryOp = spv::OpAll;
6168 break;
6169
6170 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006171 if (isFloat)
6172 libCall = spv::GLSLstd450FAbs;
6173 else
6174 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006175 break;
6176 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006177 if (isFloat)
6178 libCall = spv::GLSLstd450FSign;
6179 else
6180 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006181 break;
6182
John Kessenicha28f7a72019-08-06 07:00:58 -06006183#ifndef GLSLANG_WEB
6184 case glslang::EOpDPdxFine:
6185 unaryOp = spv::OpDPdxFine;
6186 break;
6187 case glslang::EOpDPdyFine:
6188 unaryOp = spv::OpDPdyFine;
6189 break;
6190 case glslang::EOpFwidthFine:
6191 unaryOp = spv::OpFwidthFine;
6192 break;
6193 case glslang::EOpDPdxCoarse:
6194 unaryOp = spv::OpDPdxCoarse;
6195 break;
6196 case glslang::EOpDPdyCoarse:
6197 unaryOp = spv::OpDPdyCoarse;
6198 break;
6199 case glslang::EOpFwidthCoarse:
6200 unaryOp = spv::OpFwidthCoarse;
6201 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006202 case glslang::EOpRayQueryProceed:
6203 unaryOp = spv::OpRayQueryProceedKHR;
6204 break;
6205 case glslang::EOpRayQueryGetRayTMin:
6206 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6207 break;
6208 case glslang::EOpRayQueryGetRayFlags:
6209 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6210 break;
6211 case glslang::EOpRayQueryGetWorldRayOrigin:
6212 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6213 break;
6214 case glslang::EOpRayQueryGetWorldRayDirection:
6215 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6216 break;
6217 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6218 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6219 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006220 case glslang::EOpInterpolateAtCentroid:
6221 if (typeProxy == glslang::EbtFloat16)
6222 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6223 libCall = spv::GLSLstd450InterpolateAtCentroid;
6224 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006225 case glslang::EOpAtomicCounterIncrement:
6226 case glslang::EOpAtomicCounterDecrement:
6227 case glslang::EOpAtomicCounter:
6228 {
6229 // Handle all of the atomics in one place, in createAtomicOperation()
6230 std::vector<spv::Id> operands;
6231 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006232 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006233 }
6234
John Kessenichfc51d282015-08-19 13:34:18 -06006235 case glslang::EOpBitFieldReverse:
6236 unaryOp = spv::OpBitReverse;
6237 break;
6238 case glslang::EOpBitCount:
6239 unaryOp = spv::OpBitCount;
6240 break;
6241 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006242 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006243 break;
6244 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006245 if (isUnsigned)
6246 libCall = spv::GLSLstd450FindUMsb;
6247 else
6248 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006249 break;
6250
Ian Romanickb3bd4022019-01-21 08:57:25 -08006251 case glslang::EOpCountLeadingZeros:
6252 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6253 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6254 unaryOp = spv::OpUCountLeadingZerosINTEL;
6255 break;
6256
6257 case glslang::EOpCountTrailingZeros:
6258 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6259 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6260 unaryOp = spv::OpUCountTrailingZerosINTEL;
6261 break;
6262
Rex Xu574ab042016-04-14 16:53:07 +08006263 case glslang::EOpBallot:
6264 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006265 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006266 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006267 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006268 case glslang::EOpMinInvocations:
6269 case glslang::EOpMaxInvocations:
6270 case glslang::EOpAddInvocations:
6271 case glslang::EOpMinInvocationsNonUniform:
6272 case glslang::EOpMaxInvocationsNonUniform:
6273 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006274 case glslang::EOpMinInvocationsInclusiveScan:
6275 case glslang::EOpMaxInvocationsInclusiveScan:
6276 case glslang::EOpAddInvocationsInclusiveScan:
6277 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6278 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6279 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6280 case glslang::EOpMinInvocationsExclusiveScan:
6281 case glslang::EOpMaxInvocationsExclusiveScan:
6282 case glslang::EOpAddInvocationsExclusiveScan:
6283 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6284 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6285 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006286 {
6287 std::vector<spv::Id> operands;
6288 operands.push_back(operand);
6289 return createInvocationsOperation(op, typeId, operands, typeProxy);
6290 }
John Kessenich66011cb2018-03-06 16:12:04 -07006291 case glslang::EOpSubgroupAll:
6292 case glslang::EOpSubgroupAny:
6293 case glslang::EOpSubgroupAllEqual:
6294 case glslang::EOpSubgroupBroadcastFirst:
6295 case glslang::EOpSubgroupBallot:
6296 case glslang::EOpSubgroupInverseBallot:
6297 case glslang::EOpSubgroupBallotBitCount:
6298 case glslang::EOpSubgroupBallotInclusiveBitCount:
6299 case glslang::EOpSubgroupBallotExclusiveBitCount:
6300 case glslang::EOpSubgroupBallotFindLSB:
6301 case glslang::EOpSubgroupBallotFindMSB:
6302 case glslang::EOpSubgroupAdd:
6303 case glslang::EOpSubgroupMul:
6304 case glslang::EOpSubgroupMin:
6305 case glslang::EOpSubgroupMax:
6306 case glslang::EOpSubgroupAnd:
6307 case glslang::EOpSubgroupOr:
6308 case glslang::EOpSubgroupXor:
6309 case glslang::EOpSubgroupInclusiveAdd:
6310 case glslang::EOpSubgroupInclusiveMul:
6311 case glslang::EOpSubgroupInclusiveMin:
6312 case glslang::EOpSubgroupInclusiveMax:
6313 case glslang::EOpSubgroupInclusiveAnd:
6314 case glslang::EOpSubgroupInclusiveOr:
6315 case glslang::EOpSubgroupInclusiveXor:
6316 case glslang::EOpSubgroupExclusiveAdd:
6317 case glslang::EOpSubgroupExclusiveMul:
6318 case glslang::EOpSubgroupExclusiveMin:
6319 case glslang::EOpSubgroupExclusiveMax:
6320 case glslang::EOpSubgroupExclusiveAnd:
6321 case glslang::EOpSubgroupExclusiveOr:
6322 case glslang::EOpSubgroupExclusiveXor:
6323 case glslang::EOpSubgroupQuadSwapHorizontal:
6324 case glslang::EOpSubgroupQuadSwapVertical:
6325 case glslang::EOpSubgroupQuadSwapDiagonal: {
6326 std::vector<spv::Id> operands;
6327 operands.push_back(operand);
6328 return createSubgroupOperation(op, typeId, operands, typeProxy);
6329 }
Rex Xu9d93a232016-05-05 12:30:44 +08006330 case glslang::EOpMbcnt:
6331 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6332 libCall = spv::MbcntAMD;
6333 break;
6334
6335 case glslang::EOpCubeFaceIndex:
6336 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6337 libCall = spv::CubeFaceIndexAMD;
6338 break;
6339
6340 case glslang::EOpCubeFaceCoord:
6341 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6342 libCall = spv::CubeFaceCoordAMD;
6343 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006344 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006345 unaryOp = spv::OpGroupNonUniformPartitionNV;
6346 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006347 case glslang::EOpConstructReference:
6348 unaryOp = spv::OpBitcast;
6349 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05006350
6351 case glslang::EOpConvUint64ToAccStruct:
6352 case glslang::EOpConvUvec2ToAccStruct:
6353 unaryOp = spv::OpConvertUToAccelerationStructureKHR;
6354 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006355#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006356
6357 case glslang::EOpCopyObject:
6358 unaryOp = spv::OpCopyObject;
6359 break;
6360
John Kessenich140f3df2015-06-26 16:58:36 -06006361 default:
6362 return 0;
6363 }
6364
6365 spv::Id id;
6366 if (libCall >= 0) {
6367 std::vector<spv::Id> args;
6368 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006369 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006370 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006371 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006372 }
John Kessenich140f3df2015-06-26 16:58:36 -06006373
John Kessenichb9197c82019-08-11 07:41:45 -06006374 decorations.addNoContraction(builder, id);
6375 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006376 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006377}
6378
John Kessenich7a53f762016-01-20 11:19:27 -07006379// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006380spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6381 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006382{
6383 // Handle unary operations vector by vector.
6384 // The result type is the same type as the original type.
6385 // The algorithm is to:
6386 // - break the matrix into vectors
6387 // - apply the operation to each vector
6388 // - make a matrix out the vector results
6389
6390 // get the types sorted out
6391 int numCols = builder.getNumColumns(operand);
6392 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006393 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6394 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006395 std::vector<spv::Id> results;
6396
6397 // do each vector op
6398 for (int c = 0; c < numCols; ++c) {
6399 std::vector<unsigned int> indexes;
6400 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006401 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6402 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006403 decorations.addNoContraction(builder, destVec);
6404 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006405 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006406 }
6407
6408 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006409 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006410 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006411 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006412}
6413
John Kessenichad7645f2018-06-04 19:11:25 -06006414// For converting integers where both the bitwidth and the signedness could
6415// change, but only do the width change here. The caller is still responsible
6416// for the signedness conversion.
6417spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006418{
John Kessenichad7645f2018-06-04 19:11:25 -06006419 // Get the result type width, based on the type to convert to.
6420 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006421 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006422 case glslang::EOpConvInt16ToUint8:
6423 case glslang::EOpConvIntToUint8:
6424 case glslang::EOpConvInt64ToUint8:
6425 case glslang::EOpConvUint16ToInt8:
6426 case glslang::EOpConvUintToInt8:
6427 case glslang::EOpConvUint64ToInt8:
6428 width = 8;
6429 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006430 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006431 case glslang::EOpConvIntToUint16:
6432 case glslang::EOpConvInt64ToUint16:
6433 case glslang::EOpConvUint8ToInt16:
6434 case glslang::EOpConvUintToInt16:
6435 case glslang::EOpConvUint64ToInt16:
6436 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006437 break;
6438 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006439 case glslang::EOpConvInt16ToUint:
6440 case glslang::EOpConvInt64ToUint:
6441 case glslang::EOpConvUint8ToInt:
6442 case glslang::EOpConvUint16ToInt:
6443 case glslang::EOpConvUint64ToInt:
6444 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006445 break;
6446 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006447 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006448 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006449 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006450 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006451 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006452 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006453 break;
6454
6455 default:
6456 assert(false && "Default missing");
6457 break;
6458 }
6459
John Kessenichad7645f2018-06-04 19:11:25 -06006460 // Get the conversion operation and result type,
6461 // based on the target width, but the source type.
6462 spv::Id type = spv::NoType;
6463 spv::Op convOp = spv::OpNop;
6464 switch(op) {
6465 case glslang::EOpConvInt8ToUint16:
6466 case glslang::EOpConvInt8ToUint:
6467 case glslang::EOpConvInt8ToUint64:
6468 case glslang::EOpConvInt16ToUint8:
6469 case glslang::EOpConvInt16ToUint:
6470 case glslang::EOpConvInt16ToUint64:
6471 case glslang::EOpConvIntToUint8:
6472 case glslang::EOpConvIntToUint16:
6473 case glslang::EOpConvIntToUint64:
6474 case glslang::EOpConvInt64ToUint8:
6475 case glslang::EOpConvInt64ToUint16:
6476 case glslang::EOpConvInt64ToUint:
6477 convOp = spv::OpSConvert;
6478 type = builder.makeIntType(width);
6479 break;
6480 default:
6481 convOp = spv::OpUConvert;
6482 type = builder.makeUintType(width);
6483 break;
6484 }
6485
John Kessenich66011cb2018-03-06 16:12:04 -07006486 if (vectorSize > 0)
6487 type = builder.makeVectorType(type, vectorSize);
6488
John Kessenichad7645f2018-06-04 19:11:25 -06006489 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006490}
6491
John Kessenichead86222018-03-28 18:01:20 -06006492spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6493 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006494{
6495 spv::Op convOp = spv::OpNop;
6496 spv::Id zero = 0;
6497 spv::Id one = 0;
6498
6499 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6500
6501 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006502 case glslang::EOpConvIntToBool:
6503 case glslang::EOpConvUintToBool:
6504 zero = builder.makeUintConstant(0);
6505 zero = makeSmearedConstant(zero, vectorSize);
6506 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006507 case glslang::EOpConvFloatToBool:
6508 zero = builder.makeFloatConstant(0.0F);
6509 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006510 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006511 case glslang::EOpConvBoolToFloat:
6512 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006513 zero = builder.makeFloatConstant(0.0F);
6514 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006515 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006516
John Kessenich140f3df2015-06-26 16:58:36 -06006517 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006518 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006519#ifndef GLSLANG_WEB
6520 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006521 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006522 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006523 } else
6524#endif
6525 {
6526 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006527 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006528 }
Rex Xucabbb782017-03-24 13:41:14 +08006529
John Kessenich140f3df2015-06-26 16:58:36 -06006530 convOp = spv::OpSelect;
6531 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006532
John Kessenich140f3df2015-06-26 16:58:36 -06006533 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006534 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006535#ifndef GLSLANG_WEB
6536 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006537 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006538 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006539 } else
6540#endif
6541 {
6542 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006543 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006544 }
Rex Xucabbb782017-03-24 13:41:14 +08006545
John Kessenich140f3df2015-06-26 16:58:36 -06006546 convOp = spv::OpSelect;
6547 break;
6548
John Kessenich66011cb2018-03-06 16:12:04 -07006549 case glslang::EOpConvInt8ToFloat16:
6550 case glslang::EOpConvInt8ToFloat:
6551 case glslang::EOpConvInt8ToDouble:
6552 case glslang::EOpConvInt16ToFloat16:
6553 case glslang::EOpConvInt16ToFloat:
6554 case glslang::EOpConvInt16ToDouble:
6555 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006556 case glslang::EOpConvIntToFloat:
6557 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006558 case glslang::EOpConvInt64ToFloat:
6559 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006560 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006561 convOp = spv::OpConvertSToF;
6562 break;
6563
John Kessenich66011cb2018-03-06 16:12:04 -07006564 case glslang::EOpConvUint8ToFloat16:
6565 case glslang::EOpConvUint8ToFloat:
6566 case glslang::EOpConvUint8ToDouble:
6567 case glslang::EOpConvUint16ToFloat16:
6568 case glslang::EOpConvUint16ToFloat:
6569 case glslang::EOpConvUint16ToDouble:
6570 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006571 case glslang::EOpConvUintToFloat:
6572 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006573 case glslang::EOpConvUint64ToFloat:
6574 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006575 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006576 convOp = spv::OpConvertUToF;
6577 break;
6578
John Kessenich66011cb2018-03-06 16:12:04 -07006579 case glslang::EOpConvFloat16ToInt8:
6580 case glslang::EOpConvFloatToInt8:
6581 case glslang::EOpConvDoubleToInt8:
6582 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006583 case glslang::EOpConvFloatToInt16:
6584 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006585 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006586 case glslang::EOpConvFloatToInt:
6587 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006588 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006589 case glslang::EOpConvFloatToInt64:
6590 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006591 convOp = spv::OpConvertFToS;
6592 break;
6593
John Kessenich66011cb2018-03-06 16:12:04 -07006594 case glslang::EOpConvUint8ToInt8:
6595 case glslang::EOpConvInt8ToUint8:
6596 case glslang::EOpConvUint16ToInt16:
6597 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006598 case glslang::EOpConvUintToInt:
6599 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006600 case glslang::EOpConvUint64ToInt64:
6601 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006602 if (builder.isInSpecConstCodeGenMode()) {
6603 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006604#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006605 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6606 zero = builder.makeUint8Constant(0);
6607 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006608 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006609 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6610 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006611 } else
6612#endif
6613 {
Rex Xucabbb782017-03-24 13:41:14 +08006614 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006615 }
qining189b2032016-04-12 23:16:20 -04006616 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006617 // Use OpIAdd, instead of OpBitcast to do the conversion when
6618 // generating for OpSpecConstantOp instruction.
6619 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6620 }
6621 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006622 convOp = spv::OpBitcast;
6623 break;
6624
John Kessenich66011cb2018-03-06 16:12:04 -07006625 case glslang::EOpConvFloat16ToUint8:
6626 case glslang::EOpConvFloatToUint8:
6627 case glslang::EOpConvDoubleToUint8:
6628 case glslang::EOpConvFloat16ToUint16:
6629 case glslang::EOpConvFloatToUint16:
6630 case glslang::EOpConvDoubleToUint16:
6631 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006632 case glslang::EOpConvFloatToUint:
6633 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006634 case glslang::EOpConvFloatToUint64:
6635 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006636 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006637 convOp = spv::OpConvertFToU;
6638 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006639
John Kessenich39697cd2019-08-08 10:35:51 -06006640#ifndef GLSLANG_WEB
6641 case glslang::EOpConvInt8ToBool:
6642 case glslang::EOpConvUint8ToBool:
6643 zero = builder.makeUint8Constant(0);
6644 zero = makeSmearedConstant(zero, vectorSize);
6645 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6646 case glslang::EOpConvInt16ToBool:
6647 case glslang::EOpConvUint16ToBool:
6648 zero = builder.makeUint16Constant(0);
6649 zero = makeSmearedConstant(zero, vectorSize);
6650 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6651 case glslang::EOpConvInt64ToBool:
6652 case glslang::EOpConvUint64ToBool:
6653 zero = builder.makeUint64Constant(0);
6654 zero = makeSmearedConstant(zero, vectorSize);
6655 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6656 case glslang::EOpConvDoubleToBool:
6657 zero = builder.makeDoubleConstant(0.0);
6658 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006659 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006660 case glslang::EOpConvFloat16ToBool:
6661 zero = builder.makeFloat16Constant(0.0F);
6662 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006663 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006664 case glslang::EOpConvBoolToDouble:
6665 convOp = spv::OpSelect;
6666 zero = builder.makeDoubleConstant(0.0);
6667 one = builder.makeDoubleConstant(1.0);
6668 break;
6669 case glslang::EOpConvBoolToFloat16:
6670 convOp = spv::OpSelect;
6671 zero = builder.makeFloat16Constant(0.0F);
6672 one = builder.makeFloat16Constant(1.0F);
6673 break;
6674 case glslang::EOpConvBoolToInt8:
6675 zero = builder.makeInt8Constant(0);
6676 one = builder.makeInt8Constant(1);
6677 convOp = spv::OpSelect;
6678 break;
6679 case glslang::EOpConvBoolToUint8:
6680 zero = builder.makeUint8Constant(0);
6681 one = builder.makeUint8Constant(1);
6682 convOp = spv::OpSelect;
6683 break;
6684 case glslang::EOpConvBoolToInt16:
6685 zero = builder.makeInt16Constant(0);
6686 one = builder.makeInt16Constant(1);
6687 convOp = spv::OpSelect;
6688 break;
6689 case glslang::EOpConvBoolToUint16:
6690 zero = builder.makeUint16Constant(0);
6691 one = builder.makeUint16Constant(1);
6692 convOp = spv::OpSelect;
6693 break;
6694 case glslang::EOpConvDoubleToFloat:
6695 case glslang::EOpConvFloatToDouble:
6696 case glslang::EOpConvDoubleToFloat16:
6697 case glslang::EOpConvFloat16ToDouble:
6698 case glslang::EOpConvFloatToFloat16:
6699 case glslang::EOpConvFloat16ToFloat:
6700 convOp = spv::OpFConvert;
6701 if (builder.isMatrixType(destType))
6702 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6703 break;
6704
John Kessenich66011cb2018-03-06 16:12:04 -07006705 case glslang::EOpConvInt8ToInt16:
6706 case glslang::EOpConvInt8ToInt:
6707 case glslang::EOpConvInt8ToInt64:
6708 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006709 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006710 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006711 case glslang::EOpConvIntToInt8:
6712 case glslang::EOpConvIntToInt16:
6713 case glslang::EOpConvIntToInt64:
6714 case glslang::EOpConvInt64ToInt8:
6715 case glslang::EOpConvInt64ToInt16:
6716 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006717 convOp = spv::OpSConvert;
6718 break;
6719
John Kessenich66011cb2018-03-06 16:12:04 -07006720 case glslang::EOpConvUint8ToUint16:
6721 case glslang::EOpConvUint8ToUint:
6722 case glslang::EOpConvUint8ToUint64:
6723 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006724 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006725 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006726 case glslang::EOpConvUintToUint8:
6727 case glslang::EOpConvUintToUint16:
6728 case glslang::EOpConvUintToUint64:
6729 case glslang::EOpConvUint64ToUint8:
6730 case glslang::EOpConvUint64ToUint16:
6731 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006732 convOp = spv::OpUConvert;
6733 break;
6734
John Kessenich66011cb2018-03-06 16:12:04 -07006735 case glslang::EOpConvInt8ToUint16:
6736 case glslang::EOpConvInt8ToUint:
6737 case glslang::EOpConvInt8ToUint64:
6738 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006739 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006740 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006741 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006742 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006743 case glslang::EOpConvIntToUint64:
6744 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006745 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006746 case glslang::EOpConvInt64ToUint:
6747 case glslang::EOpConvUint8ToInt16:
6748 case glslang::EOpConvUint8ToInt:
6749 case glslang::EOpConvUint8ToInt64:
6750 case glslang::EOpConvUint16ToInt8:
6751 case glslang::EOpConvUint16ToInt:
6752 case glslang::EOpConvUint16ToInt64:
6753 case glslang::EOpConvUintToInt8:
6754 case glslang::EOpConvUintToInt16:
6755 case glslang::EOpConvUintToInt64:
6756 case glslang::EOpConvUint64ToInt8:
6757 case glslang::EOpConvUint64ToInt16:
6758 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006759 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006760 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006761
6762 if (builder.isInSpecConstCodeGenMode()) {
6763 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006764 switch(op) {
6765 case glslang::EOpConvInt16ToUint8:
6766 case glslang::EOpConvIntToUint8:
6767 case glslang::EOpConvInt64ToUint8:
6768 case glslang::EOpConvUint16ToInt8:
6769 case glslang::EOpConvUintToInt8:
6770 case glslang::EOpConvUint64ToInt8:
6771 zero = builder.makeUint8Constant(0);
6772 break;
6773 case glslang::EOpConvInt8ToUint16:
6774 case glslang::EOpConvIntToUint16:
6775 case glslang::EOpConvInt64ToUint16:
6776 case glslang::EOpConvUint8ToInt16:
6777 case glslang::EOpConvUintToInt16:
6778 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006779 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006780 break;
6781 case glslang::EOpConvInt8ToUint:
6782 case glslang::EOpConvInt16ToUint:
6783 case glslang::EOpConvInt64ToUint:
6784 case glslang::EOpConvUint8ToInt:
6785 case glslang::EOpConvUint16ToInt:
6786 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006787 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006788 break;
6789 case glslang::EOpConvInt8ToUint64:
6790 case glslang::EOpConvInt16ToUint64:
6791 case glslang::EOpConvIntToUint64:
6792 case glslang::EOpConvUint8ToInt64:
6793 case glslang::EOpConvUint16ToInt64:
6794 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006795 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006796 break;
6797 default:
6798 assert(false && "Default missing");
6799 break;
6800 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006801 zero = makeSmearedConstant(zero, vectorSize);
6802 // Use OpIAdd, instead of OpBitcast to do the conversion when
6803 // generating for OpSpecConstantOp instruction.
6804 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6805 }
6806 // For normal run-time conversion instruction, use OpBitcast.
6807 convOp = spv::OpBitcast;
6808 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006809 case glslang::EOpConvUint64ToPtr:
6810 convOp = spv::OpConvertUToPtr;
6811 break;
6812 case glslang::EOpConvPtrToUint64:
6813 convOp = spv::OpConvertPtrToU;
6814 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006815 case glslang::EOpConvPtrToUvec2:
6816 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006817 if (builder.isVector(operand))
6818 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6819 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006820 convOp = spv::OpBitcast;
6821 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006822#endif
6823
John Kessenich140f3df2015-06-26 16:58:36 -06006824 default:
6825 break;
6826 }
6827
6828 spv::Id result = 0;
6829 if (convOp == spv::OpNop)
6830 return result;
6831
6832 if (convOp == spv::OpSelect) {
6833 zero = makeSmearedConstant(zero, vectorSize);
6834 one = makeSmearedConstant(one, vectorSize);
6835 result = builder.createTriOp(convOp, destType, operand, one, zero);
6836 } else
6837 result = builder.createUnaryOp(convOp, destType, operand);
6838
John Kessenichead86222018-03-28 18:01:20 -06006839 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006840 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006841 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006842}
6843
6844spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6845{
6846 if (vectorSize == 0)
6847 return constant;
6848
6849 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6850 std::vector<spv::Id> components;
6851 for (int c = 0; c < vectorSize; ++c)
6852 components.push_back(constant);
6853 return builder.makeCompositeConstant(vectorTypeId, components);
6854}
6855
John Kessenich426394d2015-07-23 10:22:48 -06006856// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006857spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6858 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6859 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006860{
6861 spv::Op opCode = spv::OpNop;
6862
6863 switch (op) {
6864 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006865 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006866 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006867 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006868 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6869 opCode = spv::OpAtomicFAddEXT;
6870 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6871 if (typeProxy == glslang::EbtFloat)
6872 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6873 else
6874 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6875 }
John Kessenich426394d2015-07-23 10:22:48 -06006876 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006877 case glslang::EOpAtomicCounterSubtract:
6878 opCode = spv::OpAtomicISub;
6879 break;
John Kessenich426394d2015-07-23 10:22:48 -06006880 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006881 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006882 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006883 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6884 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006885 break;
6886 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006887 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006888 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006889 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6890 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006891 break;
6892 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006893 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006894 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006895 opCode = spv::OpAtomicAnd;
6896 break;
6897 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006898 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006899 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006900 opCode = spv::OpAtomicOr;
6901 break;
6902 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006903 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006904 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006905 opCode = spv::OpAtomicXor;
6906 break;
6907 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006908 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006909 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006910 opCode = spv::OpAtomicExchange;
6911 break;
6912 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006913 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006914 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006915 opCode = spv::OpAtomicCompareExchange;
6916 break;
6917 case glslang::EOpAtomicCounterIncrement:
6918 opCode = spv::OpAtomicIIncrement;
6919 break;
6920 case glslang::EOpAtomicCounterDecrement:
6921 opCode = spv::OpAtomicIDecrement;
6922 break;
6923 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006924 case glslang::EOpImageAtomicLoad:
6925 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006926 opCode = spv::OpAtomicLoad;
6927 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006928 case glslang::EOpAtomicStore:
6929 case glslang::EOpImageAtomicStore:
6930 opCode = spv::OpAtomicStore;
6931 break;
John Kessenich426394d2015-07-23 10:22:48 -06006932 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006933 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006934 break;
6935 }
6936
Rex Xue8fe8b02017-09-26 15:42:56 +08006937 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6938 builder.addCapability(spv::CapabilityInt64Atomics);
6939
John Kessenich426394d2015-07-23 10:22:48 -06006940 // Sort out the operands
6941 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006942 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006943 // - compare-exchange swaps the value and comparator
6944 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006945 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006946 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6947 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6948 spv::Id scopeId;
6949 if (glslangIntermediate->usingVulkanMemoryModel()) {
6950 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6951 } else {
6952 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6953 }
6954 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006955 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6956 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006957 spv::MemorySemanticsVolatileMask :
6958 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006959 spv::Id semanticsId2 = semanticsId;
6960
6961 pointerId = operands[0];
6962 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6963 // no additional operands
6964 } else if (opCode == spv::OpAtomicCompareExchange) {
6965 compareId = operands[1];
6966 valueId = operands[2];
6967 if (operands.size() > 3) {
6968 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006969 semanticsId = builder.makeUintConstant(
6970 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6971 semanticsId2 = builder.makeUintConstant(
6972 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006973 }
6974 } else if (opCode == spv::OpAtomicLoad) {
6975 if (operands.size() > 1) {
6976 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006977 semanticsId = builder.makeUintConstant(
6978 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006979 }
6980 } else {
6981 // atomic store or RMW
6982 valueId = operands[1];
6983 if (operands.size() > 2) {
6984 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006985 semanticsId = builder.makeUintConstant
6986 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006987 }
Rex Xu04db3f52015-09-16 11:44:02 +08006988 }
John Kessenich426394d2015-07-23 10:22:48 -06006989
Jeff Bolz36831c92018-09-05 10:11:41 -05006990 // Check for capabilities
6991 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006992 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6993 spv::MemorySemanticsMakeVisibleKHRMask |
6994 spv::MemorySemanticsOutputMemoryKHRMask |
6995 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006996 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6997 }
John Kessenich426394d2015-07-23 10:22:48 -06006998
Jeff Bolz36831c92018-09-05 10:11:41 -05006999 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
7000 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7001 }
John Kessenich48d6e792017-10-06 21:21:48 -06007002
Jeff Bolz36831c92018-09-05 10:11:41 -05007003 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
7004 spvAtomicOperands.push_back(pointerId);
7005 spvAtomicOperands.push_back(scopeId);
7006 spvAtomicOperands.push_back(semanticsId);
7007 if (opCode == spv::OpAtomicCompareExchange) {
7008 spvAtomicOperands.push_back(semanticsId2);
7009 spvAtomicOperands.push_back(valueId);
7010 spvAtomicOperands.push_back(compareId);
7011 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
7012 spvAtomicOperands.push_back(valueId);
7013 }
John Kessenich48d6e792017-10-06 21:21:48 -06007014
Jeff Bolz36831c92018-09-05 10:11:41 -05007015 if (opCode == spv::OpAtomicStore) {
7016 builder.createNoResultOp(opCode, spvAtomicOperands);
7017 return 0;
7018 } else {
7019 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
7020
7021 // GLSL and HLSL atomic-counter decrement return post-decrement value,
7022 // while SPIR-V returns pre-decrement value. Translate between these semantics.
7023 if (op == glslang::EOpAtomicCounterDecrement)
7024 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
7025
7026 return resultId;
7027 }
John Kessenich426394d2015-07-23 10:22:48 -06007028}
7029
John Kessenich91cef522016-05-05 16:45:40 -06007030// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07007031spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
7032 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06007033{
John Kessenich66011cb2018-03-06 16:12:04 -07007034 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7035 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08007036
Rex Xu51596642016-09-21 18:56:12 +08007037 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06007038 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08007039 spv::GroupOperation groupOperation = spv::GroupOperationMax;
7040
chaocf200da82016-12-20 12:44:35 -08007041 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
7042 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08007043 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
7044 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007045 } else if (op == glslang::EOpAnyInvocation ||
7046 op == glslang::EOpAllInvocations ||
7047 op == glslang::EOpAllInvocationsEqual) {
7048 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
7049 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08007050 } else {
7051 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08007052 if (op == glslang::EOpMinInvocationsNonUniform ||
7053 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08007054 op == glslang::EOpAddInvocationsNonUniform ||
7055 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7056 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7057 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
7058 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
7059 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
7060 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08007061 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08007062
Rex Xu430ef402016-10-14 17:22:23 +08007063 switch (op) {
7064 case glslang::EOpMinInvocations:
7065 case glslang::EOpMaxInvocations:
7066 case glslang::EOpAddInvocations:
7067 case glslang::EOpMinInvocationsNonUniform:
7068 case glslang::EOpMaxInvocationsNonUniform:
7069 case glslang::EOpAddInvocationsNonUniform:
7070 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08007071 break;
7072 case glslang::EOpMinInvocationsInclusiveScan:
7073 case glslang::EOpMaxInvocationsInclusiveScan:
7074 case glslang::EOpAddInvocationsInclusiveScan:
7075 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7076 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7077 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7078 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007079 break;
7080 case glslang::EOpMinInvocationsExclusiveScan:
7081 case glslang::EOpMaxInvocationsExclusiveScan:
7082 case glslang::EOpAddInvocationsExclusiveScan:
7083 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7084 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7085 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7086 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007087 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07007088 default:
7089 break;
Rex Xu430ef402016-10-14 17:22:23 +08007090 }
John Kessenich149afc32018-08-14 13:31:43 -06007091 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7092 spvGroupOperands.push_back(scope);
7093 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007094 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007095 spvGroupOperands.push_back(groupOp);
7096 }
Rex Xu51596642016-09-21 18:56:12 +08007097 }
7098
John Kessenich149afc32018-08-14 13:31:43 -06007099 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
7100 spv::IdImmediate op = { true, *opIt };
7101 spvGroupOperands.push_back(op);
7102 }
John Kessenich91cef522016-05-05 16:45:40 -06007103
7104 switch (op) {
7105 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007106 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08007107 break;
John Kessenich91cef522016-05-05 16:45:40 -06007108 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007109 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08007110 break;
John Kessenich91cef522016-05-05 16:45:40 -06007111 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007112 opCode = spv::OpSubgroupAllEqualKHR;
7113 break;
Rex Xu51596642016-09-21 18:56:12 +08007114 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08007115 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08007116 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007117 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007118 break;
7119 case glslang::EOpReadFirstInvocation:
7120 opCode = spv::OpSubgroupFirstInvocationKHR;
7121 break;
7122 case glslang::EOpBallot:
7123 {
7124 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
7125 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
7126 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
7127 //
7128 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
7129 //
7130 spv::Id uintType = builder.makeUintType(32);
7131 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
7132 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
7133
7134 std::vector<spv::Id> components;
7135 components.push_back(builder.createCompositeExtract(result, uintType, 0));
7136 components.push_back(builder.createCompositeExtract(result, uintType, 1));
7137
7138 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
7139 return builder.createUnaryOp(spv::OpBitcast, typeId,
7140 builder.createCompositeConstruct(uvec2Type, components));
7141 }
7142
Rex Xu9d93a232016-05-05 12:30:44 +08007143 case glslang::EOpMinInvocations:
7144 case glslang::EOpMaxInvocations:
7145 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007146 case glslang::EOpMinInvocationsInclusiveScan:
7147 case glslang::EOpMaxInvocationsInclusiveScan:
7148 case glslang::EOpAddInvocationsInclusiveScan:
7149 case glslang::EOpMinInvocationsExclusiveScan:
7150 case glslang::EOpMaxInvocationsExclusiveScan:
7151 case glslang::EOpAddInvocationsExclusiveScan:
7152 if (op == glslang::EOpMinInvocations ||
7153 op == glslang::EOpMinInvocationsInclusiveScan ||
7154 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007155 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007156 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007157 else {
7158 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007159 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007160 else
Rex Xu51596642016-09-21 18:56:12 +08007161 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007162 }
Rex Xu430ef402016-10-14 17:22:23 +08007163 } else if (op == glslang::EOpMaxInvocations ||
7164 op == glslang::EOpMaxInvocationsInclusiveScan ||
7165 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007166 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007167 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007168 else {
7169 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007170 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007171 else
Rex Xu51596642016-09-21 18:56:12 +08007172 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007173 }
7174 } else {
7175 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007176 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007177 else
Rex Xu51596642016-09-21 18:56:12 +08007178 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007179 }
7180
Rex Xu2bbbe062016-08-23 15:41:05 +08007181 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007182 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007183
7184 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007185 case glslang::EOpMinInvocationsNonUniform:
7186 case glslang::EOpMaxInvocationsNonUniform:
7187 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007188 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7189 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7190 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7191 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7192 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7193 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7194 if (op == glslang::EOpMinInvocationsNonUniform ||
7195 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7196 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007197 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007198 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007199 else {
7200 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007201 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007202 else
Rex Xu51596642016-09-21 18:56:12 +08007203 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007204 }
7205 }
Rex Xu430ef402016-10-14 17:22:23 +08007206 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7207 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7208 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007209 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007210 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007211 else {
7212 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007213 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007214 else
Rex Xu51596642016-09-21 18:56:12 +08007215 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007216 }
7217 }
7218 else {
7219 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007220 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007221 else
Rex Xu51596642016-09-21 18:56:12 +08007222 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007223 }
7224
Rex Xu2bbbe062016-08-23 15:41:05 +08007225 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007226 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007227
7228 break;
John Kessenich91cef522016-05-05 16:45:40 -06007229 default:
7230 logger->missingFunctionality("invocation operation");
7231 return spv::NoResult;
7232 }
Rex Xu51596642016-09-21 18:56:12 +08007233
7234 assert(opCode != spv::OpNop);
7235 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007236}
7237
Rex Xu2bbbe062016-08-23 15:41:05 +08007238// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007239spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7240 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007241{
7242 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7243 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007244 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007245 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007246 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7247 op == spv::OpGroupSMinNonUniformAMD ||
7248 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7249 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007250 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7251
7252 // Handle group invocation operations scalar by scalar.
7253 // The result type is the same type as the original type.
7254 // The algorithm is to:
7255 // - break the vector into scalars
7256 // - apply the operation to each scalar
7257 // - make a vector out the scalar results
7258
7259 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007260 int numComponents = builder.getNumComponents(operands[0]);
7261 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007262 std::vector<spv::Id> results;
7263
7264 // do each scalar op
7265 for (int comp = 0; comp < numComponents; ++comp) {
7266 std::vector<unsigned int> indexes;
7267 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007268 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7269 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007270 if (op == spv::OpSubgroupReadInvocationKHR) {
7271 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007272 spv::IdImmediate operand = { true, operands[1] };
7273 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007274 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007275 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7276 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007277 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007278 spv::IdImmediate operand = { true, operands[1] };
7279 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007280 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007281 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7282 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007283 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007284 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007285 spvGroupOperands.push_back(scalar);
7286 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007287
Rex Xub7072052016-09-26 15:53:40 +08007288 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007289 }
7290
7291 // put the pieces together
7292 return builder.createCompositeConstruct(typeId, results);
7293}
Rex Xu2bbbe062016-08-23 15:41:05 +08007294
John Kessenich66011cb2018-03-06 16:12:04 -07007295// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007296spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7297 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007298{
7299 // Add the required capabilities.
7300 switch (op) {
7301 case glslang::EOpSubgroupElect:
7302 builder.addCapability(spv::CapabilityGroupNonUniform);
7303 break;
7304 case glslang::EOpSubgroupAll:
7305 case glslang::EOpSubgroupAny:
7306 case glslang::EOpSubgroupAllEqual:
7307 builder.addCapability(spv::CapabilityGroupNonUniform);
7308 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7309 break;
7310 case glslang::EOpSubgroupBroadcast:
7311 case glslang::EOpSubgroupBroadcastFirst:
7312 case glslang::EOpSubgroupBallot:
7313 case glslang::EOpSubgroupInverseBallot:
7314 case glslang::EOpSubgroupBallotBitExtract:
7315 case glslang::EOpSubgroupBallotBitCount:
7316 case glslang::EOpSubgroupBallotInclusiveBitCount:
7317 case glslang::EOpSubgroupBallotExclusiveBitCount:
7318 case glslang::EOpSubgroupBallotFindLSB:
7319 case glslang::EOpSubgroupBallotFindMSB:
7320 builder.addCapability(spv::CapabilityGroupNonUniform);
7321 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7322 break;
7323 case glslang::EOpSubgroupShuffle:
7324 case glslang::EOpSubgroupShuffleXor:
7325 builder.addCapability(spv::CapabilityGroupNonUniform);
7326 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7327 break;
7328 case glslang::EOpSubgroupShuffleUp:
7329 case glslang::EOpSubgroupShuffleDown:
7330 builder.addCapability(spv::CapabilityGroupNonUniform);
7331 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7332 break;
7333 case glslang::EOpSubgroupAdd:
7334 case glslang::EOpSubgroupMul:
7335 case glslang::EOpSubgroupMin:
7336 case glslang::EOpSubgroupMax:
7337 case glslang::EOpSubgroupAnd:
7338 case glslang::EOpSubgroupOr:
7339 case glslang::EOpSubgroupXor:
7340 case glslang::EOpSubgroupInclusiveAdd:
7341 case glslang::EOpSubgroupInclusiveMul:
7342 case glslang::EOpSubgroupInclusiveMin:
7343 case glslang::EOpSubgroupInclusiveMax:
7344 case glslang::EOpSubgroupInclusiveAnd:
7345 case glslang::EOpSubgroupInclusiveOr:
7346 case glslang::EOpSubgroupInclusiveXor:
7347 case glslang::EOpSubgroupExclusiveAdd:
7348 case glslang::EOpSubgroupExclusiveMul:
7349 case glslang::EOpSubgroupExclusiveMin:
7350 case glslang::EOpSubgroupExclusiveMax:
7351 case glslang::EOpSubgroupExclusiveAnd:
7352 case glslang::EOpSubgroupExclusiveOr:
7353 case glslang::EOpSubgroupExclusiveXor:
7354 builder.addCapability(spv::CapabilityGroupNonUniform);
7355 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7356 break;
7357 case glslang::EOpSubgroupClusteredAdd:
7358 case glslang::EOpSubgroupClusteredMul:
7359 case glslang::EOpSubgroupClusteredMin:
7360 case glslang::EOpSubgroupClusteredMax:
7361 case glslang::EOpSubgroupClusteredAnd:
7362 case glslang::EOpSubgroupClusteredOr:
7363 case glslang::EOpSubgroupClusteredXor:
7364 builder.addCapability(spv::CapabilityGroupNonUniform);
7365 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7366 break;
7367 case glslang::EOpSubgroupQuadBroadcast:
7368 case glslang::EOpSubgroupQuadSwapHorizontal:
7369 case glslang::EOpSubgroupQuadSwapVertical:
7370 case glslang::EOpSubgroupQuadSwapDiagonal:
7371 builder.addCapability(spv::CapabilityGroupNonUniform);
7372 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7373 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007374 case glslang::EOpSubgroupPartitionedAdd:
7375 case glslang::EOpSubgroupPartitionedMul:
7376 case glslang::EOpSubgroupPartitionedMin:
7377 case glslang::EOpSubgroupPartitionedMax:
7378 case glslang::EOpSubgroupPartitionedAnd:
7379 case glslang::EOpSubgroupPartitionedOr:
7380 case glslang::EOpSubgroupPartitionedXor:
7381 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7382 case glslang::EOpSubgroupPartitionedInclusiveMul:
7383 case glslang::EOpSubgroupPartitionedInclusiveMin:
7384 case glslang::EOpSubgroupPartitionedInclusiveMax:
7385 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7386 case glslang::EOpSubgroupPartitionedInclusiveOr:
7387 case glslang::EOpSubgroupPartitionedInclusiveXor:
7388 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7389 case glslang::EOpSubgroupPartitionedExclusiveMul:
7390 case glslang::EOpSubgroupPartitionedExclusiveMin:
7391 case glslang::EOpSubgroupPartitionedExclusiveMax:
7392 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7393 case glslang::EOpSubgroupPartitionedExclusiveOr:
7394 case glslang::EOpSubgroupPartitionedExclusiveXor:
7395 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7396 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7397 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007398 default: assert(0 && "Unhandled subgroup operation!");
7399 }
7400
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007401
7402 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7403 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007404 const bool isBool = typeProxy == glslang::EbtBool;
7405
7406 spv::Op opCode = spv::OpNop;
7407
7408 // Figure out which opcode to use.
7409 switch (op) {
7410 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7411 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7412 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7413 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7414 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7415 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7416 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7417 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7418 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7419 case glslang::EOpSubgroupBallotBitCount:
7420 case glslang::EOpSubgroupBallotInclusiveBitCount:
7421 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7422 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7423 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7424 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7425 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7426 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7427 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7428 case glslang::EOpSubgroupAdd:
7429 case glslang::EOpSubgroupInclusiveAdd:
7430 case glslang::EOpSubgroupExclusiveAdd:
7431 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007432 case glslang::EOpSubgroupPartitionedAdd:
7433 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7434 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007435 if (isFloat) {
7436 opCode = spv::OpGroupNonUniformFAdd;
7437 } else {
7438 opCode = spv::OpGroupNonUniformIAdd;
7439 }
7440 break;
7441 case glslang::EOpSubgroupMul:
7442 case glslang::EOpSubgroupInclusiveMul:
7443 case glslang::EOpSubgroupExclusiveMul:
7444 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007445 case glslang::EOpSubgroupPartitionedMul:
7446 case glslang::EOpSubgroupPartitionedInclusiveMul:
7447 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007448 if (isFloat) {
7449 opCode = spv::OpGroupNonUniformFMul;
7450 } else {
7451 opCode = spv::OpGroupNonUniformIMul;
7452 }
7453 break;
7454 case glslang::EOpSubgroupMin:
7455 case glslang::EOpSubgroupInclusiveMin:
7456 case glslang::EOpSubgroupExclusiveMin:
7457 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007458 case glslang::EOpSubgroupPartitionedMin:
7459 case glslang::EOpSubgroupPartitionedInclusiveMin:
7460 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007461 if (isFloat) {
7462 opCode = spv::OpGroupNonUniformFMin;
7463 } else if (isUnsigned) {
7464 opCode = spv::OpGroupNonUniformUMin;
7465 } else {
7466 opCode = spv::OpGroupNonUniformSMin;
7467 }
7468 break;
7469 case glslang::EOpSubgroupMax:
7470 case glslang::EOpSubgroupInclusiveMax:
7471 case glslang::EOpSubgroupExclusiveMax:
7472 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007473 case glslang::EOpSubgroupPartitionedMax:
7474 case glslang::EOpSubgroupPartitionedInclusiveMax:
7475 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007476 if (isFloat) {
7477 opCode = spv::OpGroupNonUniformFMax;
7478 } else if (isUnsigned) {
7479 opCode = spv::OpGroupNonUniformUMax;
7480 } else {
7481 opCode = spv::OpGroupNonUniformSMax;
7482 }
7483 break;
7484 case glslang::EOpSubgroupAnd:
7485 case glslang::EOpSubgroupInclusiveAnd:
7486 case glslang::EOpSubgroupExclusiveAnd:
7487 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007488 case glslang::EOpSubgroupPartitionedAnd:
7489 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7490 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007491 if (isBool) {
7492 opCode = spv::OpGroupNonUniformLogicalAnd;
7493 } else {
7494 opCode = spv::OpGroupNonUniformBitwiseAnd;
7495 }
7496 break;
7497 case glslang::EOpSubgroupOr:
7498 case glslang::EOpSubgroupInclusiveOr:
7499 case glslang::EOpSubgroupExclusiveOr:
7500 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007501 case glslang::EOpSubgroupPartitionedOr:
7502 case glslang::EOpSubgroupPartitionedInclusiveOr:
7503 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007504 if (isBool) {
7505 opCode = spv::OpGroupNonUniformLogicalOr;
7506 } else {
7507 opCode = spv::OpGroupNonUniformBitwiseOr;
7508 }
7509 break;
7510 case glslang::EOpSubgroupXor:
7511 case glslang::EOpSubgroupInclusiveXor:
7512 case glslang::EOpSubgroupExclusiveXor:
7513 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007514 case glslang::EOpSubgroupPartitionedXor:
7515 case glslang::EOpSubgroupPartitionedInclusiveXor:
7516 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007517 if (isBool) {
7518 opCode = spv::OpGroupNonUniformLogicalXor;
7519 } else {
7520 opCode = spv::OpGroupNonUniformBitwiseXor;
7521 }
7522 break;
7523 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7524 case glslang::EOpSubgroupQuadSwapHorizontal:
7525 case glslang::EOpSubgroupQuadSwapVertical:
7526 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7527 default: assert(0 && "Unhandled subgroup operation!");
7528 }
7529
John Kessenich149afc32018-08-14 13:31:43 -06007530 // get the right Group Operation
7531 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007532 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007533 default:
7534 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007535 case glslang::EOpSubgroupBallotBitCount:
7536 case glslang::EOpSubgroupAdd:
7537 case glslang::EOpSubgroupMul:
7538 case glslang::EOpSubgroupMin:
7539 case glslang::EOpSubgroupMax:
7540 case glslang::EOpSubgroupAnd:
7541 case glslang::EOpSubgroupOr:
7542 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007543 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007544 break;
7545 case glslang::EOpSubgroupBallotInclusiveBitCount:
7546 case glslang::EOpSubgroupInclusiveAdd:
7547 case glslang::EOpSubgroupInclusiveMul:
7548 case glslang::EOpSubgroupInclusiveMin:
7549 case glslang::EOpSubgroupInclusiveMax:
7550 case glslang::EOpSubgroupInclusiveAnd:
7551 case glslang::EOpSubgroupInclusiveOr:
7552 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007553 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007554 break;
7555 case glslang::EOpSubgroupBallotExclusiveBitCount:
7556 case glslang::EOpSubgroupExclusiveAdd:
7557 case glslang::EOpSubgroupExclusiveMul:
7558 case glslang::EOpSubgroupExclusiveMin:
7559 case glslang::EOpSubgroupExclusiveMax:
7560 case glslang::EOpSubgroupExclusiveAnd:
7561 case glslang::EOpSubgroupExclusiveOr:
7562 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007563 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007564 break;
7565 case glslang::EOpSubgroupClusteredAdd:
7566 case glslang::EOpSubgroupClusteredMul:
7567 case glslang::EOpSubgroupClusteredMin:
7568 case glslang::EOpSubgroupClusteredMax:
7569 case glslang::EOpSubgroupClusteredAnd:
7570 case glslang::EOpSubgroupClusteredOr:
7571 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007572 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007573 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007574 case glslang::EOpSubgroupPartitionedAdd:
7575 case glslang::EOpSubgroupPartitionedMul:
7576 case glslang::EOpSubgroupPartitionedMin:
7577 case glslang::EOpSubgroupPartitionedMax:
7578 case glslang::EOpSubgroupPartitionedAnd:
7579 case glslang::EOpSubgroupPartitionedOr:
7580 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007581 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007582 break;
7583 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7584 case glslang::EOpSubgroupPartitionedInclusiveMul:
7585 case glslang::EOpSubgroupPartitionedInclusiveMin:
7586 case glslang::EOpSubgroupPartitionedInclusiveMax:
7587 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7588 case glslang::EOpSubgroupPartitionedInclusiveOr:
7589 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007590 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007591 break;
7592 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7593 case glslang::EOpSubgroupPartitionedExclusiveMul:
7594 case glslang::EOpSubgroupPartitionedExclusiveMin:
7595 case glslang::EOpSubgroupPartitionedExclusiveMax:
7596 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7597 case glslang::EOpSubgroupPartitionedExclusiveOr:
7598 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007599 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007600 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007601 }
7602
John Kessenich149afc32018-08-14 13:31:43 -06007603 // build the instruction
7604 std::vector<spv::IdImmediate> spvGroupOperands;
7605
7606 // Every operation begins with the Execution Scope operand.
7607 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7608 spvGroupOperands.push_back(executionScope);
7609
7610 // Next, for all operations that use a Group Operation, push that as an operand.
7611 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007612 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007613 spvGroupOperands.push_back(groupOperand);
7614 }
7615
John Kessenich66011cb2018-03-06 16:12:04 -07007616 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007617 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7618 spv::IdImmediate operand = { true, *opIt };
7619 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007620 }
7621
7622 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007623 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007624 switch (op) {
7625 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007626 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7627 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7628 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7629 }
7630 if (directionId != spv::NoResult) {
7631 spv::IdImmediate direction = { true, directionId };
7632 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007633 }
7634
7635 return builder.createOp(opCode, typeId, spvGroupOperands);
7636}
7637
John Kessenich8985fc92020-03-03 10:25:07 -07007638spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7639 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007640{
John Kessenich66011cb2018-03-06 16:12:04 -07007641 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7642 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007643
John Kessenich140f3df2015-06-26 16:58:36 -06007644 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007645 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007646 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007647 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007648 spv::Id typeId0 = 0;
7649 if (consumedOperands > 0)
7650 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007651 spv::Id typeId1 = 0;
7652 if (consumedOperands > 1)
7653 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007654 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007655
7656 switch (op) {
7657 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007658 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007659 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007660 else if (isUnsigned)
7661 libCall = spv::GLSLstd450UMin;
7662 else
7663 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007664 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007665 break;
7666 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007667 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007668 break;
7669 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007670 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007671 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007672 else if (isUnsigned)
7673 libCall = spv::GLSLstd450UMax;
7674 else
7675 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007676 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007677 break;
7678 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007679 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007680 break;
7681 case glslang::EOpDot:
7682 opCode = spv::OpDot;
7683 break;
7684 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007685 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007686 break;
7687
7688 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007689 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007690 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007691 else if (isUnsigned)
7692 libCall = spv::GLSLstd450UClamp;
7693 else
7694 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007695 builder.promoteScalar(precision, operands.front(), operands[1]);
7696 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007697 break;
7698 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007699 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7700 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007701 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007702 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007703 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007704 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007705 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007706 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007707 break;
7708 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007709 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007710 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007711 break;
7712 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007713 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007714 builder.promoteScalar(precision, operands[0], operands[2]);
7715 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007716 break;
7717
7718 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007719 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007720 break;
7721 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007722 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007723 break;
7724 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007725 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007726 break;
7727 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007728 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007729 break;
7730 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007731 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007732 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007733 case glslang::EOpBarrier:
7734 {
7735 // This is for the extended controlBarrier function, with four operands.
7736 // The unextended barrier() goes through createNoArgOperation.
7737 assert(operands.size() == 4);
7738 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7739 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7740 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007741 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7742 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007743 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7744 spv::MemorySemanticsMakeVisibleKHRMask |
7745 spv::MemorySemanticsOutputMemoryKHRMask |
7746 spv::MemorySemanticsVolatileMask)) {
7747 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7748 }
John Kessenich8985fc92020-03-03 10:25:07 -07007749 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7750 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007751 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7752 }
7753 return 0;
7754 }
7755 break;
7756 case glslang::EOpMemoryBarrier:
7757 {
7758 // This is for the extended memoryBarrier function, with three operands.
7759 // The unextended memoryBarrier() goes through createNoArgOperation.
7760 assert(operands.size() == 3);
7761 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7762 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7763 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7764 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7765 spv::MemorySemanticsMakeVisibleKHRMask |
7766 spv::MemorySemanticsOutputMemoryKHRMask |
7767 spv::MemorySemanticsVolatileMask)) {
7768 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7769 }
7770 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7771 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7772 }
7773 return 0;
7774 }
7775 break;
7776
John Kessenicha28f7a72019-08-06 07:00:58 -06007777#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007778 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007779 if (typeProxy == glslang::EbtFloat16)
7780 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007781 libCall = spv::GLSLstd450InterpolateAtSample;
7782 break;
7783 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007784 if (typeProxy == glslang::EbtFloat16)
7785 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007786 libCall = spv::GLSLstd450InterpolateAtOffset;
7787 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007788 case glslang::EOpAddCarry:
7789 opCode = spv::OpIAddCarry;
7790 typeId = builder.makeStructResultType(typeId0, typeId0);
7791 consumedOperands = 2;
7792 break;
7793 case glslang::EOpSubBorrow:
7794 opCode = spv::OpISubBorrow;
7795 typeId = builder.makeStructResultType(typeId0, typeId0);
7796 consumedOperands = 2;
7797 break;
7798 case glslang::EOpUMulExtended:
7799 opCode = spv::OpUMulExtended;
7800 typeId = builder.makeStructResultType(typeId0, typeId0);
7801 consumedOperands = 2;
7802 break;
7803 case glslang::EOpIMulExtended:
7804 opCode = spv::OpSMulExtended;
7805 typeId = builder.makeStructResultType(typeId0, typeId0);
7806 consumedOperands = 2;
7807 break;
7808 case glslang::EOpBitfieldExtract:
7809 if (isUnsigned)
7810 opCode = spv::OpBitFieldUExtract;
7811 else
7812 opCode = spv::OpBitFieldSExtract;
7813 break;
7814 case glslang::EOpBitfieldInsert:
7815 opCode = spv::OpBitFieldInsert;
7816 break;
7817
7818 case glslang::EOpFma:
7819 libCall = spv::GLSLstd450Fma;
7820 break;
7821 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007822 {
7823 libCall = spv::GLSLstd450FrexpStruct;
7824 assert(builder.isPointerType(typeId1));
7825 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007826 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007827 if (width == 16)
7828 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7829 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007830 if (builder.getNumComponents(operands[0]) == 1)
7831 frexpIntType = builder.makeIntegerType(width, true);
7832 else
John Kessenich8985fc92020-03-03 10:25:07 -07007833 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7834 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007835 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7836 consumedOperands = 1;
7837 }
John Kessenich55e7d112015-11-15 21:33:39 -07007838 break;
7839 case glslang::EOpLdexp:
7840 libCall = spv::GLSLstd450Ldexp;
7841 break;
7842
Rex Xu574ab042016-04-14 16:53:07 +08007843 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007844 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007845
John Kessenich66011cb2018-03-06 16:12:04 -07007846 case glslang::EOpSubgroupBroadcast:
7847 case glslang::EOpSubgroupBallotBitExtract:
7848 case glslang::EOpSubgroupShuffle:
7849 case glslang::EOpSubgroupShuffleXor:
7850 case glslang::EOpSubgroupShuffleUp:
7851 case glslang::EOpSubgroupShuffleDown:
7852 case glslang::EOpSubgroupClusteredAdd:
7853 case glslang::EOpSubgroupClusteredMul:
7854 case glslang::EOpSubgroupClusteredMin:
7855 case glslang::EOpSubgroupClusteredMax:
7856 case glslang::EOpSubgroupClusteredAnd:
7857 case glslang::EOpSubgroupClusteredOr:
7858 case glslang::EOpSubgroupClusteredXor:
7859 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007860 case glslang::EOpSubgroupPartitionedAdd:
7861 case glslang::EOpSubgroupPartitionedMul:
7862 case glslang::EOpSubgroupPartitionedMin:
7863 case glslang::EOpSubgroupPartitionedMax:
7864 case glslang::EOpSubgroupPartitionedAnd:
7865 case glslang::EOpSubgroupPartitionedOr:
7866 case glslang::EOpSubgroupPartitionedXor:
7867 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7868 case glslang::EOpSubgroupPartitionedInclusiveMul:
7869 case glslang::EOpSubgroupPartitionedInclusiveMin:
7870 case glslang::EOpSubgroupPartitionedInclusiveMax:
7871 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7872 case glslang::EOpSubgroupPartitionedInclusiveOr:
7873 case glslang::EOpSubgroupPartitionedInclusiveXor:
7874 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7875 case glslang::EOpSubgroupPartitionedExclusiveMul:
7876 case glslang::EOpSubgroupPartitionedExclusiveMin:
7877 case glslang::EOpSubgroupPartitionedExclusiveMax:
7878 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7879 case glslang::EOpSubgroupPartitionedExclusiveOr:
7880 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007881 return createSubgroupOperation(op, typeId, operands, typeProxy);
7882
Rex Xu9d93a232016-05-05 12:30:44 +08007883 case glslang::EOpSwizzleInvocations:
7884 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7885 libCall = spv::SwizzleInvocationsAMD;
7886 break;
7887 case glslang::EOpSwizzleInvocationsMasked:
7888 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7889 libCall = spv::SwizzleInvocationsMaskedAMD;
7890 break;
7891 case glslang::EOpWriteInvocation:
7892 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7893 libCall = spv::WriteInvocationAMD;
7894 break;
7895
7896 case glslang::EOpMin3:
7897 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7898 if (isFloat)
7899 libCall = spv::FMin3AMD;
7900 else {
7901 if (isUnsigned)
7902 libCall = spv::UMin3AMD;
7903 else
7904 libCall = spv::SMin3AMD;
7905 }
7906 break;
7907 case glslang::EOpMax3:
7908 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7909 if (isFloat)
7910 libCall = spv::FMax3AMD;
7911 else {
7912 if (isUnsigned)
7913 libCall = spv::UMax3AMD;
7914 else
7915 libCall = spv::SMax3AMD;
7916 }
7917 break;
7918 case glslang::EOpMid3:
7919 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7920 if (isFloat)
7921 libCall = spv::FMid3AMD;
7922 else {
7923 if (isUnsigned)
7924 libCall = spv::UMid3AMD;
7925 else
7926 libCall = spv::SMid3AMD;
7927 }
7928 break;
7929
7930 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007931 if (typeProxy == glslang::EbtFloat16)
7932 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007933 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7934 libCall = spv::InterpolateAtVertexAMD;
7935 break;
Chao Chen3c366992018-09-19 11:41:59 -07007936
Daniel Kochdb32b242020-03-17 20:42:47 -04007937 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007938 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007939 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007940 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05007941 case glslang::EOpTraceNV:
7942 builder.createNoResultOp(spv::OpTraceNV, operands);
7943 return 0;
7944 case glslang::EOpTraceKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007945 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007946 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05007947 case glslang::EOpExecuteCallableNV:
7948 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
7949 return 0;
7950 case glslang::EOpExecuteCallableKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007951 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007952 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007953
7954 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007955 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7956 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007957 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007958 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7959 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007960 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007961 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7962 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007963 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007964 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7965 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007966 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007967 typeId = builder.makeBoolType();
7968 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007969 break;
7970 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007971 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007972 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007973 break;
7974 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007975 typeId = builder.makeFloatType(32);
7976 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007977 break;
7978 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007979 typeId = builder.makeIntType(32);
7980 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007981 break;
7982 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007983 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007984 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007985 break;
7986 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007987 typeId = builder.makeIntType(32);
7988 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007989 break;
7990 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007991 typeId = builder.makeIntType(32);
7992 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007993 break;
7994 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Daniel Kochc0bcfaf2020-12-12 12:34:24 -05007995 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007996 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007997 break;
7998 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007999 typeId = builder.makeIntType(32);
8000 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008001 break;
8002 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04008003 typeId = builder.makeIntType(32);
8004 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008005 break;
8006 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04008007 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
8008 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008009 break;
8010 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04008011 typeId = builder.makeBoolType();
8012 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008013 break;
8014 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04008015 typeId = builder.makeBoolType();
8016 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008017 break;
8018 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008019 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8020 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008021 break;
8022 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008023 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8024 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008025 break;
8026 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008027 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8028 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008029 break;
8030 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008031 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8032 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008033 break;
8034 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04008035 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008036 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008037 break;
8038 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04008039 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008040 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008041 break;
Chao Chen3c366992018-09-19 11:41:59 -07008042 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
8043 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
8044 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008045 case glslang::EOpCooperativeMatrixMulAdd:
8046 opCode = spv::OpCooperativeMatrixMulAddNV;
8047 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06008048#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06008049 default:
8050 return 0;
8051 }
8052
8053 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07008054 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05008055 // Use an extended instruction from the standard library.
8056 // Construct the call arguments, without modifying the original operands vector.
8057 // We might need the remaining arguments, e.g. in the EOpFrexp case.
8058 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08008059 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01008060 } else if (opCode == spv::OpDot && !isFloat) {
8061 // int dot(int, int)
8062 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
8063 const int componentCount = builder.getNumComponents(operands[0]);
8064 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
8065 builder.setPrecision(mulOp, precision);
8066 id = builder.createCompositeExtract(mulOp, typeId, 0);
8067 for (int i = 1; i < componentCount; ++i) {
8068 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07008069 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01008070 }
John Kessenich2359bd02015-12-06 19:29:11 -07008071 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07008072 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06008073 case 0:
8074 // should all be handled by visitAggregate and createNoArgOperation
8075 assert(0);
8076 return 0;
8077 case 1:
8078 // should all be handled by createUnaryOperation
8079 assert(0);
8080 return 0;
8081 case 2:
8082 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
8083 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008084 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008085 // anything 3 or over doesn't have l-value operands, so all should be consumed
8086 assert(consumedOperands == operands.size());
8087 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06008088 break;
8089 }
8090 }
8091
John Kessenichb9197c82019-08-11 07:41:45 -06008092#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07008093 // Decode the return types that were structures
8094 switch (op) {
8095 case glslang::EOpAddCarry:
8096 case glslang::EOpSubBorrow:
8097 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8098 id = builder.createCompositeExtract(id, typeId0, 0);
8099 break;
8100 case glslang::EOpUMulExtended:
8101 case glslang::EOpIMulExtended:
8102 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
8103 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8104 break;
8105 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08008106 {
8107 assert(operands.size() == 2);
8108 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
8109 // "exp" is floating-point type (from HLSL intrinsic)
8110 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
8111 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
8112 builder.createStore(member1, operands[1]);
8113 } else
8114 // "exp" is integer type (from GLSL built-in function)
8115 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
8116 id = builder.createCompositeExtract(id, typeId0, 0);
8117 }
John Kessenich55e7d112015-11-15 21:33:39 -07008118 break;
8119 default:
8120 break;
8121 }
John Kessenichb9197c82019-08-11 07:41:45 -06008122#endif
John Kessenich55e7d112015-11-15 21:33:39 -07008123
John Kessenich32cfd492016-02-02 12:37:46 -07008124 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06008125}
8126
Rex Xu9d93a232016-05-05 12:30:44 +08008127// Intrinsics with no arguments (or no return value, and no precision).
8128spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06008129{
Jeff Bolz36831c92018-09-05 10:11:41 -05008130 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07008131 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
8132 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06008133
8134 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06008135 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008136 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05008137 if (glslangIntermediate->usingVulkanMemoryModel()) {
8138 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8139 spv::MemorySemanticsOutputMemoryKHRMask |
8140 spv::MemorySemanticsAcquireReleaseMask);
8141 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
8142 } else {
8143 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
8144 }
John Kessenich82979362017-12-11 04:02:24 -07008145 } else {
8146 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8147 spv::MemorySemanticsWorkgroupMemoryMask |
8148 spv::MemorySemanticsAcquireReleaseMask);
8149 }
John Kessenich140f3df2015-06-26 16:58:36 -06008150 return 0;
8151 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008152 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8153 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008154 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008155 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008156 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8157 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008158 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008159 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008160 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8161 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008162 return 0;
8163 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008164 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8165 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008166 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008167#ifndef GLSLANG_WEB
8168 case glslang::EOpMemoryBarrierAtomicCounter:
8169 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8170 spv::MemorySemanticsAcquireReleaseMask);
8171 return 0;
8172 case glslang::EOpMemoryBarrierImage:
8173 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8174 spv::MemorySemanticsAcquireReleaseMask);
8175 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008176 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008177 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008178 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008179 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008180 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008181 case glslang::EOpDeviceMemoryBarrier:
8182 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8183 spv::MemorySemanticsImageMemoryMask |
8184 spv::MemorySemanticsAcquireReleaseMask);
8185 return 0;
8186 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8187 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8188 spv::MemorySemanticsImageMemoryMask |
8189 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008190 return 0;
8191 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008192 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8193 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008194 return 0;
8195 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008196 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8197 spv::MemorySemanticsWorkgroupMemoryMask |
8198 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008199 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008200 case glslang::EOpSubgroupBarrier:
8201 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8202 spv::MemorySemanticsAcquireReleaseMask);
8203 return spv::NoResult;
8204 case glslang::EOpSubgroupMemoryBarrier:
8205 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8206 spv::MemorySemanticsAcquireReleaseMask);
8207 return spv::NoResult;
8208 case glslang::EOpSubgroupMemoryBarrierBuffer:
8209 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8210 spv::MemorySemanticsAcquireReleaseMask);
8211 return spv::NoResult;
8212 case glslang::EOpSubgroupMemoryBarrierImage:
8213 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8214 spv::MemorySemanticsAcquireReleaseMask);
8215 return spv::NoResult;
8216 case glslang::EOpSubgroupMemoryBarrierShared:
8217 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8218 spv::MemorySemanticsAcquireReleaseMask);
8219 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008220
8221 case glslang::EOpEmitVertex:
8222 builder.createNoResultOp(spv::OpEmitVertex);
8223 return 0;
8224 case glslang::EOpEndPrimitive:
8225 builder.createNoResultOp(spv::OpEndPrimitive);
8226 return 0;
8227
John Kessenich66011cb2018-03-06 16:12:04 -07008228 case glslang::EOpSubgroupElect: {
8229 std::vector<spv::Id> operands;
8230 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8231 }
Rex Xu9d93a232016-05-05 12:30:44 +08008232 case glslang::EOpTime:
8233 {
8234 std::vector<spv::Id> args; // Dummy arguments
8235 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8236 return builder.setPrecision(id, precision);
8237 }
Daniel Kochffccefd2020-11-23 15:41:27 -05008238 case glslang::EOpIgnoreIntersectionNV:
8239 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008240 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05008241 case glslang::EOpTerminateRayNV:
8242 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008243 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008244 case glslang::EOpRayQueryInitialize:
8245 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8246 return 0;
8247 case glslang::EOpRayQueryTerminate:
8248 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8249 return 0;
8250 case glslang::EOpRayQueryGenerateIntersection:
8251 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8252 return 0;
8253 case glslang::EOpRayQueryConfirmIntersection:
8254 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8255 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008256 case glslang::EOpBeginInvocationInterlock:
8257 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8258 return 0;
8259 case glslang::EOpEndInvocationInterlock:
8260 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8261 return 0;
8262
Jeff Bolzba6170b2019-07-01 09:23:23 -05008263 case glslang::EOpIsHelperInvocation:
8264 {
8265 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008266 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8267 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8268 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008269 }
8270
amhagan91fb0092019-07-10 21:14:38 -04008271 case glslang::EOpReadClockSubgroupKHR: {
8272 std::vector<spv::Id> args;
8273 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8274 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8275 builder.addCapability(spv::CapabilityShaderClockKHR);
8276 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8277 }
8278
8279 case glslang::EOpReadClockDeviceKHR: {
8280 std::vector<spv::Id> args;
8281 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8282 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8283 builder.addCapability(spv::CapabilityShaderClockKHR);
8284 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8285 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008286#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008287 default:
John Kessenich155d3512019-08-08 23:29:20 -06008288 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008289 }
John Kessenich155d3512019-08-08 23:29:20 -06008290
8291 logger->missingFunctionality("unknown operation with no arguments");
8292
8293 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008294}
8295
8296spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8297{
John Kessenich2f273362015-07-18 22:34:27 -06008298 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008299 spv::Id id;
8300 if (symbolValues.end() != iter) {
8301 id = iter->second;
8302 return id;
8303 }
8304
8305 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008306 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008307 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008308 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008309 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008310 if (forcedType.second != spv::NoType)
8311 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008312
Rex Xuc884b4a2016-06-29 15:03:44 +08008313 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008314 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8315 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8316 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008317#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008318 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008319 if (symbol->getQualifier().hasComponent())
8320 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8321 if (symbol->getQualifier().hasIndex())
8322 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008323#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008324 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008325 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008326 // atomic counters use this:
8327 if (symbol->getQualifier().hasOffset())
8328 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008329 }
8330
scygan2c864272016-05-18 18:09:17 +02008331 if (symbol->getQualifier().hasLocation())
8332 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008333 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008334 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008335 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008336 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008337 }
John Kessenich140f3df2015-06-26 16:58:36 -06008338 if (symbol->getQualifier().hasSet())
8339 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008340 else if (IsDescriptorResource(symbol->getType())) {
8341 // default to 0
8342 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8343 }
John Kessenich140f3df2015-06-26 16:58:36 -06008344 if (symbol->getQualifier().hasBinding())
8345 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008346 else if (IsDescriptorResource(symbol->getType())) {
8347 // default to 0
8348 builder.addDecoration(id, spv::DecorationBinding, 0);
8349 }
John Kessenich6c292d32016-02-15 20:58:50 -07008350 if (symbol->getQualifier().hasAttachment())
8351 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008352 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008353 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008354 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008355 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008356 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8357 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8358 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8359 }
8360 if (symbol->getQualifier().hasXfbOffset())
8361 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008362 }
8363
John Kessenichb9197c82019-08-11 07:41:45 -06008364 // add built-in variable decoration
8365 if (builtIn != spv::BuiltInMax) {
8366 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8367 }
8368
8369#ifndef GLSLANG_WEB
Daniel Kochffccefd2020-11-23 15:41:27 -05008370 // Subgroup builtins which have input storage class are volatile for ray tracing stages.
8371 if (symbol->getType().isImage() || symbol->getQualifier().isPipeInput()) {
Rex Xu1da878f2016-02-21 20:59:01 +08008372 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008373 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8374 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008375 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008376 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008377 }
8378
chaoc0ad6a4e2016-12-19 16:29:34 -08008379 if (builtIn == spv::BuiltInSampleMask) {
8380 spv::Decoration decoration;
8381 // GL_NV_sample_mask_override_coverage extension
8382 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008383 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008384 else
8385 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008386 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008387 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008388 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008389 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8390 }
8391 }
chaoc771d89f2017-01-13 01:10:53 -08008392 else if (builtIn == spv::BuiltInLayer) {
8393 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008394 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008395 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008396 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8397 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8398 }
John Kessenichb41bff62017-08-11 13:07:17 -06008399 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008400 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8401 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008402 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8403 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8404 }
8405 }
8406
chaoc6e5acae2016-12-20 13:28:52 -08008407 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008408 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008409 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008410 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8411 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008412 if (symbol->getQualifier().pervertexNV) {
8413 builder.addDecoration(id, spv::DecorationPerVertexNV);
8414 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8415 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8416 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008417
John Kessenich5d610ee2018-03-07 18:05:55 -07008418 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8419 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8420 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8421 symbol->getType().getQualifier().semanticName);
8422 }
8423
John Kessenich7015bd62019-08-01 03:28:08 -06008424 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008425 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8426 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008427 }
John Kessenichb9197c82019-08-11 07:41:45 -06008428#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008429
John Kessenich140f3df2015-06-26 16:58:36 -06008430 return id;
8431}
8432
John Kessenicha28f7a72019-08-06 07:00:58 -06008433#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008434// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8435void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8436{
8437 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008438 if (qualifier.perPrimitiveNV) {
8439 // Need to add capability/extension for fragment shader.
8440 // Mesh shader already adds this by default.
8441 if (glslangIntermediate->getStage() == EShLangFragment) {
8442 builder.addCapability(spv::CapabilityMeshShadingNV);
8443 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8444 }
Chao Chen3c366992018-09-19 11:41:59 -07008445 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008446 }
Chao Chen3c366992018-09-19 11:41:59 -07008447 if (qualifier.perViewNV)
8448 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8449 if (qualifier.perTaskNV)
8450 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8451 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008452 if (qualifier.perPrimitiveNV) {
8453 // Need to add capability/extension for fragment shader.
8454 // Mesh shader already adds this by default.
8455 if (glslangIntermediate->getStage() == EShLangFragment) {
8456 builder.addCapability(spv::CapabilityMeshShadingNV);
8457 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8458 }
Chao Chen3c366992018-09-19 11:41:59 -07008459 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008460 }
Chao Chen3c366992018-09-19 11:41:59 -07008461 if (qualifier.perViewNV)
8462 builder.addDecoration(id, spv::DecorationPerViewNV);
8463 if (qualifier.perTaskNV)
8464 builder.addDecoration(id, spv::DecorationPerTaskNV);
8465 }
8466}
8467#endif
8468
John Kessenich55e7d112015-11-15 21:33:39 -07008469// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008470// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008471//
8472// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8473//
8474// Recursively walk the nodes. The nodes form a tree whose leaves are
8475// regular constants, which themselves are trees that createSpvConstant()
8476// recursively walks. So, this function walks the "top" of the tree:
8477// - emit specialization constant-building instructions for specConstant
8478// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008479spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008480{
John Kessenich7cc0e282016-03-20 00:46:02 -06008481 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008482
qining4f4bb812016-04-03 23:55:17 -04008483 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008484 if (! node.getQualifier().specConstant) {
8485 // hand off to the non-spec-constant path
8486 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8487 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008488 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8489 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8490 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008491 }
8492
8493 // We now know we have a specialization constant to build
8494
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008495 // Extra capabilities may be needed.
8496 if (node.getType().contains8BitInt())
8497 builder.addCapability(spv::CapabilityInt8);
8498 if (node.getType().contains16BitFloat())
8499 builder.addCapability(spv::CapabilityFloat16);
8500 if (node.getType().contains16BitInt())
8501 builder.addCapability(spv::CapabilityInt16);
8502 if (node.getType().contains64BitInt())
8503 builder.addCapability(spv::CapabilityInt64);
8504 if (node.getType().containsDouble())
8505 builder.addCapability(spv::CapabilityFloat64);
8506
John Kessenichd94c0032016-05-30 19:29:40 -06008507 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008508 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8509 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8510 std::vector<spv::Id> dimConstId;
8511 for (int dim = 0; dim < 3; ++dim) {
8512 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8513 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008514 if (specConst) {
8515 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8516 glslangIntermediate->getLocalSizeSpecId(dim));
8517 }
qining4f4bb812016-04-03 23:55:17 -04008518 }
8519 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8520 }
8521
8522 // An AST node labelled as specialization constant should be a symbol node.
8523 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8524 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008525 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008526 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008527 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8528 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8529 // will set the builder into spec constant op instruction generating mode.
8530 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008531 result = accessChainLoad(sub_tree->getType());
8532 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008533 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008534 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008535 } else {
8536 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008537 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008538 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008539 builder.addName(result, sn->getName().c_str());
8540 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008541 }
qining4f4bb812016-04-03 23:55:17 -04008542
8543 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8544 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008545 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008546 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008547}
8548
John Kessenich140f3df2015-06-26 16:58:36 -06008549// Use 'consts' as the flattened glslang source of scalar constants to recursively
8550// build the aggregate SPIR-V constant.
8551//
8552// If there are not enough elements present in 'consts', 0 will be substituted;
8553// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8554//
John Kessenich8985fc92020-03-03 10:25:07 -07008555spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8556 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008557{
8558 // vector of constants for SPIR-V
8559 std::vector<spv::Id> spvConsts;
8560
8561 // Type is used for struct and array constants
8562 spv::Id typeId = convertGlslangToSpvType(glslangType);
8563
8564 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008565 glslang::TType elementType(glslangType, 0);
8566 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008567 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008568 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008569 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008570 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008571 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008572 } else if (glslangType.isCoopMat()) {
8573 glslang::TType componentType(glslangType.getBasicType());
8574 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008575 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008576 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8577 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008578 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008579 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008580 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8581 bool zero = nextConst >= consts.size();
8582 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008583 case glslang::EbtInt:
8584 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8585 break;
8586 case glslang::EbtUint:
8587 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8588 break;
8589 case glslang::EbtFloat:
8590 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8591 break;
8592 case glslang::EbtBool:
8593 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8594 break;
8595#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008596 case glslang::EbtInt8:
8597 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8598 break;
8599 case glslang::EbtUint8:
8600 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8601 break;
8602 case glslang::EbtInt16:
8603 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8604 break;
8605 case glslang::EbtUint16:
8606 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8607 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008608 case glslang::EbtInt64:
8609 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8610 break;
8611 case glslang::EbtUint64:
8612 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008614 case glslang::EbtDouble:
8615 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8616 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008617 case glslang::EbtFloat16:
8618 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8619 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008620#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008621 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008622 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008623 break;
8624 }
8625 ++nextConst;
8626 }
8627 } else {
8628 // we have a non-aggregate (scalar) constant
8629 bool zero = nextConst >= consts.size();
8630 spv::Id scalar = 0;
8631 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008632 case glslang::EbtInt:
8633 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8634 break;
8635 case glslang::EbtUint:
8636 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8637 break;
8638 case glslang::EbtFloat:
8639 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8640 break;
8641 case glslang::EbtBool:
8642 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8643 break;
8644#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008645 case glslang::EbtInt8:
8646 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8647 break;
8648 case glslang::EbtUint8:
8649 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8650 break;
8651 case glslang::EbtInt16:
8652 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8653 break;
8654 case glslang::EbtUint16:
8655 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8656 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008657 case glslang::EbtInt64:
8658 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8659 break;
8660 case glslang::EbtUint64:
8661 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8662 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008663 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008664 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008665 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008666 case glslang::EbtFloat16:
8667 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8668 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008669 case glslang::EbtReference:
8670 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8671 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8672 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008673#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008674 case glslang::EbtString:
8675 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8676 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008677 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008678 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008679 break;
8680 }
8681 ++nextConst;
8682 return scalar;
8683 }
8684
8685 return builder.makeCompositeConstant(typeId, spvConsts);
8686}
8687
John Kessenich7c1aa102015-10-15 13:29:11 -06008688// Return true if the node is a constant or symbol whose reading has no
8689// non-trivial observable cost or effect.
8690bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8691{
8692 // don't know what this is
8693 if (node == nullptr)
8694 return false;
8695
8696 // a constant is safe
8697 if (node->getAsConstantUnion() != nullptr)
8698 return true;
8699
8700 // not a symbol means non-trivial
8701 if (node->getAsSymbolNode() == nullptr)
8702 return false;
8703
8704 // a symbol, depends on what's being read
8705 switch (node->getType().getQualifier().storage) {
8706 case glslang::EvqTemporary:
8707 case glslang::EvqGlobal:
8708 case glslang::EvqIn:
8709 case glslang::EvqInOut:
8710 case glslang::EvqConst:
8711 case glslang::EvqConstReadOnly:
8712 case glslang::EvqUniform:
8713 return true;
8714 default:
8715 return false;
8716 }
qining25262b32016-05-06 17:25:16 -04008717}
John Kessenich7c1aa102015-10-15 13:29:11 -06008718
8719// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008720// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008721// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008722// Return true if trivial.
8723bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8724{
8725 if (node == nullptr)
8726 return false;
8727
John Kessenich84cc15f2017-05-24 16:44:47 -06008728 // count non scalars as trivial, as well as anything coming from HLSL
8729 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008730 return true;
8731
John Kessenich7c1aa102015-10-15 13:29:11 -06008732 // symbols and constants are trivial
8733 if (isTrivialLeaf(node))
8734 return true;
8735
8736 // otherwise, it needs to be a simple operation or one or two leaf nodes
8737
8738 // not a simple operation
8739 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8740 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8741 if (binaryNode == nullptr && unaryNode == nullptr)
8742 return false;
8743
8744 // not on leaf nodes
8745 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8746 return false;
8747
8748 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8749 return false;
8750 }
8751
8752 switch (node->getAsOperator()->getOp()) {
8753 case glslang::EOpLogicalNot:
8754 case glslang::EOpConvIntToBool:
8755 case glslang::EOpConvUintToBool:
8756 case glslang::EOpConvFloatToBool:
8757 case glslang::EOpConvDoubleToBool:
8758 case glslang::EOpEqual:
8759 case glslang::EOpNotEqual:
8760 case glslang::EOpLessThan:
8761 case glslang::EOpGreaterThan:
8762 case glslang::EOpLessThanEqual:
8763 case glslang::EOpGreaterThanEqual:
8764 case glslang::EOpIndexDirect:
8765 case glslang::EOpIndexDirectStruct:
8766 case glslang::EOpLogicalXor:
8767 case glslang::EOpAny:
8768 case glslang::EOpAll:
8769 return true;
8770 default:
8771 return false;
8772 }
8773}
8774
8775// Emit short-circuiting code, where 'right' is never evaluated unless
8776// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008777spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8778 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008779{
8780 spv::Id boolTypeId = builder.makeBoolType();
8781
8782 // emit left operand
8783 builder.clearAccessChain();
8784 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008785 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008786
8787 // Operands to accumulate OpPhi operands
8788 std::vector<spv::Id> phiOperands;
8789 // accumulate left operand's phi information
8790 phiOperands.push_back(leftId);
8791 phiOperands.push_back(builder.getBuildPoint()->getId());
8792
8793 // Make the two kinds of operation symmetric with a "!"
8794 // || => emit "if (! left) result = right"
8795 // && => emit "if ( left) result = right"
8796 //
8797 // TODO: this runtime "not" for || could be avoided by adding functionality
8798 // to 'builder' to have an "else" without an "then"
8799 if (op == glslang::EOpLogicalOr)
8800 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8801
8802 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008803 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008804
8805 // emit right operand as the "then" part of the "if"
8806 builder.clearAccessChain();
8807 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008808 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008809
8810 // accumulate left operand's phi information
8811 phiOperands.push_back(rightId);
8812 phiOperands.push_back(builder.getBuildPoint()->getId());
8813
8814 // finish the "if"
8815 ifBuilder.makeEndIf();
8816
8817 // phi together the two results
8818 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8819}
8820
John Kessenicha28f7a72019-08-06 07:00:58 -06008821#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008822// Return type Id of the imported set of extended instructions corresponds to the name.
8823// Import this set if it has not been imported yet.
8824spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8825{
8826 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8827 return extBuiltinMap[name];
8828 else {
Rex Xu51596642016-09-21 18:56:12 +08008829 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008830 spv::Id extBuiltins = builder.import(name);
8831 extBuiltinMap[name] = extBuiltins;
8832 return extBuiltins;
8833 }
8834}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008835#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008836
John Kessenich140f3df2015-06-26 16:58:36 -06008837}; // end anonymous namespace
8838
8839namespace glslang {
8840
John Kessenich68d78fd2015-07-12 19:28:10 -06008841void GetSpirvVersion(std::string& version)
8842{
John Kessenich9e55f632015-07-15 10:03:39 -06008843 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008844 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008845 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008846 version = buf;
8847}
8848
John Kessenicha372a3e2017-11-02 22:32:14 -06008849// For low-order part of the generator's magic number. Bump up
8850// when there is a change in the style (e.g., if SSA form changes,
8851// or a different instruction sequence to do something gets used).
8852int GetSpirvGeneratorVersion()
8853{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008854 // return 1; // start
8855 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008856 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008857 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008858 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008859 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8860 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008861 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008862 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008863 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8864 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008865}
8866
John Kessenich140f3df2015-06-26 16:58:36 -06008867// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008868void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008869{
8870 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008871 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008872 if (out.fail())
8873 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008874 for (int i = 0; i < (int)spirv.size(); ++i) {
8875 unsigned int word = spirv[i];
8876 out.write((const char*)&word, 4);
8877 }
8878 out.close();
8879}
8880
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008881// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008882void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008883{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008884#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008885 std::ofstream out;
8886 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008887 if (out.fail())
8888 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008889 out << "\t// " <<
8890 GetSpirvGeneratorVersion() <<
8891 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8892 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008893 if (varName != nullptr) {
8894 out << "\t #pragma once" << std::endl;
8895 out << "const uint32_t " << varName << "[] = {" << std::endl;
8896 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008897 const int WORDS_PER_LINE = 8;
8898 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8899 out << "\t";
8900 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8901 const unsigned int word = spirv[i + j];
8902 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8903 if (i + j + 1 < (int)spirv.size()) {
8904 out << ",";
8905 }
8906 }
8907 out << std::endl;
8908 }
Flavio15017db2017-02-15 14:29:33 -08008909 if (varName != nullptr) {
8910 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008911 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008912 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008913 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008914#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008915}
8916
John Kessenich140f3df2015-06-26 16:58:36 -06008917//
8918// Set up the glslang traversal
8919//
John Kessenich4e11b612018-08-30 16:56:59 -06008920void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008921{
Lei Zhang17535f72016-05-04 15:55:59 -04008922 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008923 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008924}
8925
John Kessenich4e11b612018-08-30 16:56:59 -06008926void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008927 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008928{
John Kessenich140f3df2015-06-26 16:58:36 -06008929 TIntermNode* root = intermediate.getTreeRoot();
8930
8931 if (root == 0)
8932 return;
8933
John Kessenich4e11b612018-08-30 16:56:59 -06008934 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008935 if (options == nullptr)
8936 options = &defaultOptions;
8937
John Kessenich4e11b612018-08-30 16:56:59 -06008938 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008939
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008940 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008941 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008942 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008943 it.dumpSpv(spirv);
8944
GregFfb03a552018-03-29 11:49:14 -06008945#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008946 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8947 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008948 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008949 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8950 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008951 prelegalization = false;
8952 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008953 else if (options->stripDebugInfo) {
8954 // Strip debug info even if optimization is disabled.
8955 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8956 }
John Kessenich717c80a2018-08-23 15:17:10 -06008957
John Kessenich4e11b612018-08-30 16:56:59 -06008958 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008959 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008960
John Kessenich717c80a2018-08-23 15:17:10 -06008961 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008962 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008963
GregFcd1f1692017-09-21 18:40:22 -06008964#endif
8965
John Kessenich4e11b612018-08-30 16:56:59 -06008966 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008967}
8968
8969}; // end namespace glslang