blob: eea8852807fccb4f74fb7abf15704d3f9353c6c3 [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
3655 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3656 !node->getConstArray().empty()) {
3657 int nextConst = 0;
3658 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3659 node->getConstArray(),
3660 nextConst,
3661 false /* specConst */);
3662 }
3663
John Kessenich435dd802020-06-30 01:27:08 -06003664 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003665}
3666
3667// Return type Id of the sampled type.
3668spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3669{
3670 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003671 case glslang::EbtInt: return builder.makeIntType(32);
3672 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003673 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003674#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003675 case glslang::EbtFloat16:
3676 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3677 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3678 return builder.makeFloatType(16);
Tobski8c1a3a02020-11-04 16:24:23 +00003679 case glslang::EbtInt64: return builder.makeIntType(64);
3680 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3681 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3682 case glslang::EbtUint64: return builder.makeUintType(64);
3683 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3684 builder.addCapability(spv::CapabilityFloat16ImageAMD);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003686 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003687 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003688 return builder.makeFloatType(32);
3689 }
3690}
3691
John Kessenich8c8505c2016-07-26 12:50:38 -06003692// If node is a swizzle operation, return the type that should be used if
3693// the swizzle base is first consumed by another operation, before the swizzle
3694// is applied.
3695spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3696{
John Kessenichecba76f2017-01-06 00:34:48 -07003697 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003698 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3699 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3700 else
3701 return spv::NoType;
3702}
3703
3704// When inverting a swizzle with a parent op, this function
3705// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003706spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3707 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003708{
3709 std::vector<unsigned> swizzle;
3710 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3711 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3712}
3713
John Kessenich8c8505c2016-07-26 12:50:38 -06003714// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3715void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3716{
3717 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3718 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3719 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3720}
3721
John Kessenich3ac051e2015-12-20 11:29:16 -07003722// Convert from a glslang type to an SPV type, by calling into a
3723// recursive version of this function. This establishes the inherited
3724// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003725spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003726{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003727 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003728}
3729
3730// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003731// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003732// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003733spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003734 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3735 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003736{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003737 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003738
3739 switch (type.getBasicType()) {
3740 case glslang::EbtVoid:
3741 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003742 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003745 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3746 // a 32-bit int where non-0 means true.
3747 if (explicitLayout != glslang::ElpNone)
3748 spvType = builder.makeUintType(32);
3749 else
3750 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003751 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003752 case glslang::EbtInt:
3753 spvType = builder.makeIntType(32);
3754 break;
3755 case glslang::EbtUint:
3756 spvType = builder.makeUintType(32);
3757 break;
3758 case glslang::EbtFloat:
3759 spvType = builder.makeFloatType(32);
3760 break;
3761#ifndef GLSLANG_WEB
3762 case glslang::EbtDouble:
3763 spvType = builder.makeFloatType(64);
3764 break;
3765 case glslang::EbtFloat16:
3766 spvType = builder.makeFloatType(16);
3767 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003768 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003769 spvType = builder.makeIntType(8);
3770 break;
3771 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003772 spvType = builder.makeUintType(8);
3773 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003774 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003775 spvType = builder.makeIntType(16);
3776 break;
3777 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003778 spvType = builder.makeUintType(16);
3779 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003780 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003781 spvType = builder.makeIntType(64);
3782 break;
3783 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003784 spvType = builder.makeUintType(64);
3785 break;
John Kessenich426394d2015-07-23 10:22:48 -06003786 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003787 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003788 spvType = builder.makeUintType(32);
3789 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003790 case glslang::EbtAccStruct:
Daniel Koch4d41da32020-11-24 23:06:16 -05003791 switch (glslangIntermediate->getStage()) {
3792 case EShLangRayGen:
3793 case EShLangIntersect:
3794 case EShLangAnyHit:
3795 case EShLangClosestHit:
3796 case EShLangMiss:
3797 case EShLangCallable:
3798 // these all should have the RayTracingNV/KHR capability already
3799 break;
3800 default:
3801 {
3802 auto& extensions = glslangIntermediate->getRequestedExtensions();
3803 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3804 builder.addExtension(spv::E_SPV_KHR_ray_query);
3805 builder.addCapability(spv::CapabilityRayQueryKHR);
3806 }
3807 }
3808 break;
3809 }
Daniel Kochdb32b242020-03-17 20:42:47 -04003810 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003811 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003812 case glslang::EbtRayQuery:
Daniel Koch4d41da32020-11-24 23:06:16 -05003813 {
3814 auto& extensions = glslangIntermediate->getRequestedExtensions();
3815 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3816 builder.addExtension(spv::E_SPV_KHR_ray_query);
3817 builder.addCapability(spv::CapabilityRayQueryKHR);
3818 }
3819 spvType = builder.makeRayQueryType();
3820 }
Torosdagli06c2eee2020-03-19 11:09:57 -04003821 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003822 case glslang::EbtReference:
3823 {
3824 // Make the forward pointer, then recurse to convert the structure type, then
3825 // patch up the forward pointer with a real pointer type.
3826 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3827 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3828 forwardPointers[type.getReferentType()] = forwardId;
3829 }
3830 spvType = forwardPointers[type.getReferentType()];
3831 if (!forwardReferenceOnly) {
3832 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3833 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3834 forwardPointers[type.getReferentType()],
3835 referentType);
3836 }
3837 }
3838 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003839#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003840 case glslang::EbtSampler:
3841 {
3842 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003843 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003844 spvType = builder.makeSamplerType();
3845 } else {
3846 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003847 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3848 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3849 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3850 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003851 // already has both image and sampler, make the combined type
3852 spvType = builder.makeSampledImageType(spvType);
3853 }
John Kessenich55e7d112015-11-15 21:33:39 -07003854 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003855 }
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857 case glslang::EbtStruct:
3858 case glslang::EbtBlock:
3859 {
3860 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003861 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003862
3863 // Try to share structs for different layouts, but not yet for other
3864 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003865 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003866 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003867 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003868 break;
3869
3870 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003871 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003872 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003873 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003874 }
3875 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003876 case glslang::EbtString:
3877 // no type used for OpString
3878 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003879 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003880 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882 }
3883
3884 if (type.isMatrix())
3885 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3886 else {
3887 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3888 if (type.getVectorSize() > 1)
3889 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3890 }
3891
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003892 if (type.isCoopMat()) {
3893 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3894 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3895 if (type.getBasicType() == glslang::EbtFloat16)
3896 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003897 if (type.getBasicType() == glslang::EbtUint8 ||
3898 type.getBasicType() == glslang::EbtInt8) {
3899 builder.addCapability(spv::CapabilityInt8);
3900 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003901
3902 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3903 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3904 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3905
3906 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3907 }
3908
John Kessenich140f3df2015-06-26 16:58:36 -06003909 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003910 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3911
John Kessenichc9a80832015-09-12 12:17:44 -06003912 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003913 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003914 // We need to decorate array strides for types needing explicit layout, except blocks.
3915 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003916 // Use a dummy glslang type for querying internal strides of
3917 // arrays of arrays, but using just a one-dimensional array.
3918 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003919 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3920 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003921
3922 // Will compute the higher-order strides here, rather than making a whole
3923 // pile of types and doing repetitive recursion on their contents.
3924 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3925 }
John Kessenichf8842e52016-01-04 19:22:56 -07003926
3927 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003928 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003929 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003930 if (stride > 0)
3931 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003932 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003933 }
3934 } else {
3935 // single-dimensional array, and don't yet have stride
3936
John Kessenichf8842e52016-01-04 19:22:56 -07003937 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003938 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3939 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003940 }
John Kessenich31ed4832015-09-09 17:51:38 -06003941
John Kessenichead86222018-03-28 18:01:20 -06003942 // Do the outer dimension, which might not be known for a runtime-sized array.
3943 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3944 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003945 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003946 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003947#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003948 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003949 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003950 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3951 }
John Kessenichb9197c82019-08-11 07:41:45 -06003952#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003953 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003954 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003955 if (stride > 0)
3956 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003957 }
3958
3959 return spvType;
3960}
3961
John Kessenich0e737842017-03-24 18:38:16 -06003962// TODO: this functionality should exist at a higher level, in creating the AST
3963//
3964// Identify interface members that don't have their required extension turned on.
3965//
3966bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3967{
John Kessenicha28f7a72019-08-06 07:00:58 -06003968#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003969 auto& extensions = glslangIntermediate->getRequestedExtensions();
3970
Rex Xubcf291a2017-03-29 23:01:36 +08003971 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3972 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3973 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003974 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3975 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3976 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003977
3978 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3979 if (member.getFieldName() == "gl_ViewportMask" &&
3980 extensions.find("GL_NV_viewport_array2") == extensions.end())
3981 return true;
3982 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3983 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3984 return true;
3985 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3986 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3987 return true;
3988 }
3989#endif
John Kessenich0e737842017-03-24 18:38:16 -06003990
3991 return false;
3992};
3993
John Kessenich6090df02016-06-30 21:18:02 -06003994// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3995// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3996// Mutually recursive with convertGlslangToSpvType().
3997spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3998 const glslang::TTypeList* glslangMembers,
3999 glslang::TLayoutPacking explicitLayout,
4000 const glslang::TQualifier& qualifier)
4001{
4002 // Create a vector of struct types for SPIR-V to consume
4003 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07004004 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
4005 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004006 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06004007 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4008 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4009 if (glslangMember.hiddenMember()) {
4010 ++memberDelta;
4011 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08004012 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06004013 } else {
John Kessenich0e737842017-03-24 18:38:16 -06004014 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004015 if (filterMember(glslangMember)) {
4016 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08004017 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06004018 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004019 }
Roy05a5b532020-01-03 16:21:34 +08004020 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06004021 }
John Kessenich6090df02016-06-30 21:18:02 -06004022 // modify just this child's view of the qualifier
4023 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4024 InheritQualifiers(memberQualifier, qualifier);
4025
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004026 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06004027 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004028 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06004029
4030 // recurse
John Kessenichead86222018-03-28 18:01:20 -06004031 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
4032 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004033
4034 // Make forward pointers for any pointer members, and create a list of members to
4035 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06004036 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004037 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
4038 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
4039 }
4040 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004041 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4042 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004043 } else {
4044 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004045 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4046 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004047 }
John Kessenich6090df02016-06-30 21:18:02 -06004048 }
4049 }
4050
4051 // Make the SPIR-V type
4052 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06004053 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06004054 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
4055
4056 // Decorate it
4057 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
4058
John Kessenichd72f4882019-01-16 14:55:37 +07004059 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004060 auto it = deferredForwardPointers[i];
4061 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
4062 }
4063
John Kessenich6090df02016-06-30 21:18:02 -06004064 return spvType;
4065}
4066
4067void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
4068 const glslang::TTypeList* glslangMembers,
4069 glslang::TLayoutPacking explicitLayout,
4070 const glslang::TQualifier& qualifier,
4071 spv::Id spvType)
4072{
4073 // Name and decorate the non-hidden members
4074 int offset = -1;
4075 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08004076 bool memberLocationInvalid = type.isArrayOfArrays() ||
4077 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06004078 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4079 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4080 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06004081 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08004082 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06004083 if (filterMember(glslangMember))
4084 continue;
4085 }
John Kessenich6090df02016-06-30 21:18:02 -06004086
4087 // modify just this child's view of the qualifier
4088 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4089 InheritQualifiers(memberQualifier, qualifier);
4090
4091 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07004092 if (member < 0)
4093 continue;
4094
4095 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
4096 builder.addMemberDecoration(spvType, member,
4097 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
4098 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
4099 // Add interpolation and auxiliary storage decorations only to
4100 // top-level members of Input and Output storage classes
4101 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4102 type.getQualifier().storage == glslang::EvqVaryingOut) {
4103 if (type.getBasicType() == glslang::EbtBlock ||
4104 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4105 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4106 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004107#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004108 addMeshNVDecoration(spvType, member, memberQualifier);
4109#endif
John Kessenich6090df02016-06-30 21:18:02 -06004110 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004111 }
4112 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004113
John Kessenichb9197c82019-08-11 07:41:45 -06004114#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004115 if (type.getBasicType() == glslang::EbtBlock &&
4116 qualifier.storage == glslang::EvqBuffer) {
4117 // Add memory decorations only to top-level members of shader storage block
4118 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004119 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004120 for (unsigned int i = 0; i < memory.size(); ++i)
4121 builder.addMemberDecoration(spvType, member, memory[i]);
4122 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004123
John Kessenichb9197c82019-08-11 07:41:45 -06004124#endif
John Kessenich6090df02016-06-30 21:18:02 -06004125
John Kessenich5d610ee2018-03-07 18:05:55 -07004126 // Location assignment was already completed correctly by the front end,
4127 // just track whether a member needs to be decorated.
4128 // Ignore member locations if the container is an array, as that's
4129 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004130 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004131 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004132
John Kessenich5d610ee2018-03-07 18:05:55 -07004133 if (qualifier.hasLocation()) // track for upcoming inheritance
4134 locationOffset += glslangIntermediate->computeTypeLocationSize(
4135 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004136
John Kessenich5d610ee2018-03-07 18:05:55 -07004137 // component, XFB, others
4138 if (glslangMember.getQualifier().hasComponent())
4139 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4140 glslangMember.getQualifier().layoutComponent);
4141 if (glslangMember.getQualifier().hasXfbOffset())
4142 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4143 glslangMember.getQualifier().layoutXfbOffset);
4144 else if (explicitLayout != glslang::ElpNone) {
4145 // figure out what to do with offset, which is accumulating
4146 int nextOffset;
4147 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4148 if (offset >= 0)
4149 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4150 offset = nextOffset;
4151 }
John Kessenich6090df02016-06-30 21:18:02 -06004152
John Kessenich5d610ee2018-03-07 18:05:55 -07004153 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4154 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4155 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004156
John Kessenich5d610ee2018-03-07 18:05:55 -07004157 // built-in variable decorations
4158 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4159 if (builtIn != spv::BuiltInMax)
4160 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004161
John Kessenichb9197c82019-08-11 07:41:45 -06004162#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004163 // nonuniform
4164 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4165
John Kessenichead86222018-03-28 18:01:20 -06004166 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4167 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4168 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4169 memberQualifier.semanticName);
4170 }
4171
John Kessenich5d610ee2018-03-07 18:05:55 -07004172 if (builtIn == spv::BuiltInLayer) {
4173 // SPV_NV_viewport_array2 extension
4174 if (glslangMember.getQualifier().layoutViewportRelative){
4175 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4176 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4177 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004178 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004179 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4180 builder.addMemberDecoration(spvType, member,
4181 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4182 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4183 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4184 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004185 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004186 }
4187 if (glslangMember.getQualifier().layoutPassthrough) {
4188 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4189 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4190 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4191 }
chaoc771d89f2017-01-13 01:10:53 -08004192#endif
John Kessenich6090df02016-06-30 21:18:02 -06004193 }
4194
4195 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004196 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4197 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004198}
4199
John Kessenich6c292d32016-02-15 20:58:50 -07004200// Turn the expression forming the array size into an id.
4201// This is not quite trivial, because of specialization constants.
4202// Sometimes, a raw constant is turned into an Id, and sometimes
4203// a specialization constant expression is.
4204spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4205{
4206 // First, see if this is sized with a node, meaning a specialization constant:
4207 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4208 if (specNode != nullptr) {
4209 builder.clearAccessChain();
4210 specNode->traverse(this);
4211 return accessChainLoad(specNode->getAsTyped()->getType());
4212 }
qining25262b32016-05-06 17:25:16 -04004213
John Kessenich6c292d32016-02-15 20:58:50 -07004214 // Otherwise, need a compile-time (front end) size, get it:
4215 int size = arraySizes.getDimSize(dim);
4216 assert(size > 0);
4217 return builder.makeUintConstant(size);
4218}
4219
John Kessenich103bef92016-02-08 21:38:15 -07004220// Wrap the builder's accessChainLoad to:
4221// - localize handling of RelaxedPrecision
4222// - use the SPIR-V inferred type instead of another conversion of the glslang type
4223// (avoids unnecessary work and possible type punning for structures)
4224// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004225spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4226{
John Kessenich103bef92016-02-08 21:38:15 -07004227 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004228
4229 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4230 coherentFlags |= TranslateCoherent(type);
4231
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004232 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004233 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004234
John Kessenich5611c6d2018-04-05 11:25:02 -06004235 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
greg-lunarg639f5462020-11-12 11:10:07 -07004236 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004237 TranslateNonUniformDecoration(type.getQualifier()),
4238 nominalTypeId,
4239 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4240 TranslateMemoryScope(coherentFlags),
4241 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004242
4243 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004244 if (type.getBasicType() == glslang::EbtBool) {
4245 if (builder.isScalarType(nominalTypeId)) {
4246 // Conversion for bool
4247 spv::Id boolType = builder.makeBoolType();
4248 if (nominalTypeId != boolType)
4249 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4250 } else if (builder.isVectorType(nominalTypeId)) {
4251 // Conversion for bvec
4252 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4253 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4254 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004255 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4256 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004257 }
4258 }
John Kessenich103bef92016-02-08 21:38:15 -07004259
4260 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004261}
4262
Rex Xu27253232016-02-23 17:51:09 +08004263// Wrap the builder's accessChainStore to:
4264// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004265//
4266// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004267void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4268{
4269 // Need to convert to abstract types when necessary
4270 if (type.getBasicType() == glslang::EbtBool) {
4271 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4272
4273 if (builder.isScalarType(nominalTypeId)) {
4274 // Conversion for bool
4275 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004276 if (nominalTypeId != boolType) {
4277 // keep these outside arguments, for determinant order-of-evaluation
4278 spv::Id one = builder.makeUintConstant(1);
4279 spv::Id zero = builder.makeUintConstant(0);
4280 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4281 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004282 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004283 } else if (builder.isVectorType(nominalTypeId)) {
4284 // Conversion for bvec
4285 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4286 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004287 if (nominalTypeId != bvecType) {
4288 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004289 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4290 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4291 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004292 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004293 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4294 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004295 }
4296 }
4297
Jeff Bolz36831c92018-09-05 10:11:41 -05004298 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4299 coherentFlags |= TranslateCoherent(type);
4300
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004301 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004302 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004303
greg-lunarg639f5462020-11-12 11:10:07 -07004304 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004305 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4306 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004307 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004308}
4309
John Kessenich4bf71552016-09-02 11:20:21 -06004310// For storing when types match at the glslang level, but not might match at the
4311// SPIR-V level.
4312//
4313// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004314// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004315// as in a member-decorated way.
4316//
4317// NOTE: This function can handle any store request; if it's not special it
4318// simplifies to a simple OpStore.
4319//
4320// Implicitly uses the existing builder.accessChain as the storage target.
4321void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4322{
John Kessenichb3e24e42016-09-11 12:33:43 -06004323 // we only do the complex path here if it's an aggregate
4324 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004325 accessChainStore(type, rValue);
4326 return;
4327 }
4328
John Kessenichb3e24e42016-09-11 12:33:43 -06004329 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004330 spv::Id rType = builder.getTypeId(rValue);
4331 spv::Id lValue = builder.accessChainGetLValue();
4332 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4333 if (lType == rType) {
4334 accessChainStore(type, rValue);
4335 return;
4336 }
4337
John Kessenichb3e24e42016-09-11 12:33:43 -06004338 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004339 // where the two types were the same type in GLSL. This requires member
4340 // by member copy, recursively.
4341
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004342 // SPIR-V 1.4 added an instruction to do help do this.
4343 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4344 // However, bool in uniform space is changed to int, so
4345 // OpCopyLogical does not work for that.
4346 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4347 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4348 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4349 if (lBool == rBool) {
4350 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4351 accessChainStore(type, logicalCopy);
4352 return;
4353 }
4354 }
4355
John Kessenichb3e24e42016-09-11 12:33:43 -06004356 // If an array, copy element by element.
4357 if (type.isArray()) {
4358 glslang::TType glslangElementType(type, 0);
4359 spv::Id elementRType = builder.getContainedTypeId(rType);
4360 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4361 // get the source member
4362 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004363
John Kessenichb3e24e42016-09-11 12:33:43 -06004364 // set up the target storage
4365 builder.clearAccessChain();
4366 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004367 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4368 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004369
John Kessenichb3e24e42016-09-11 12:33:43 -06004370 // store the member
4371 multiTypeStore(glslangElementType, elementRValue);
4372 }
4373 } else {
4374 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004375
John Kessenichb3e24e42016-09-11 12:33:43 -06004376 // loop over structure members
4377 const glslang::TTypeList& members = *type.getStruct();
4378 for (int m = 0; m < (int)members.size(); ++m) {
4379 const glslang::TType& glslangMemberType = *members[m].type;
4380
4381 // get the source member
4382 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4383 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4384
4385 // set up the target storage
4386 builder.clearAccessChain();
4387 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004388 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4389 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004390
4391 // store the member
4392 multiTypeStore(glslangMemberType, memberRValue);
4393 }
John Kessenich4bf71552016-09-02 11:20:21 -06004394 }
4395}
4396
John Kessenichf85e8062015-12-19 13:57:10 -07004397// Decide whether or not this type should be
4398// decorated with offsets and strides, and if so
4399// whether std140 or std430 rules should be applied.
4400glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004401{
John Kessenichf85e8062015-12-19 13:57:10 -07004402 // has to be a block
4403 if (type.getBasicType() != glslang::EbtBlock)
4404 return glslang::ElpNone;
4405
Chao Chen3c366992018-09-19 11:41:59 -07004406 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004407 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004408 type.getQualifier().storage != glslang::EvqBuffer &&
4409 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004410 return glslang::ElpNone;
4411
4412 // return the layout to use
4413 switch (type.getQualifier().layoutPacking) {
4414 case glslang::ElpStd140:
4415 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004416 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004417 return type.getQualifier().layoutPacking;
4418 default:
4419 return glslang::ElpNone;
4420 }
John Kessenich31ed4832015-09-09 17:51:38 -06004421}
4422
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004423// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004424int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4425 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004426{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004427 int size;
John Kessenich49987892015-12-29 17:11:44 -07004428 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004429 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4430 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004431
4432 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004433}
4434
John Kessenich49987892015-12-29 17:11:44 -07004435// 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 -07004436// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004437int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4438 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004439{
John Kessenich49987892015-12-29 17:11:44 -07004440 glslang::TType elementType;
4441 elementType.shallowCopy(matrixType);
4442 elementType.clearArraySizes();
4443
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004444 int size;
John Kessenich49987892015-12-29 17:11:44 -07004445 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004446 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4447 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004448
4449 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004450}
4451
John Kessenich5e4b1242015-08-06 22:53:06 -06004452// Given a member type of a struct, realign the current offset for it, and compute
4453// the next (not yet aligned) offset for the next member, which will get aligned
4454// on the next call.
4455// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4456// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4457// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004458void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4459 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004460{
4461 // this will get a positive value when deemed necessary
4462 nextOffset = -1;
4463
John Kessenich5e4b1242015-08-06 22:53:06 -06004464 // override anything in currentOffset with user-set offset
4465 if (memberType.getQualifier().hasOffset())
4466 currentOffset = memberType.getQualifier().layoutOffset;
4467
4468 // It could be that current linker usage in glslang updated all the layoutOffset,
4469 // in which case the following code does not matter. But, that's not quite right
4470 // once cross-compilation unit GLSL validation is done, as the original user
4471 // settings are needed in layoutOffset, and then the following will come into play.
4472
John Kessenichf85e8062015-12-19 13:57:10 -07004473 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004474 if (! memberType.getQualifier().hasOffset())
4475 currentOffset = -1;
4476
4477 return;
4478 }
4479
John Kessenichf85e8062015-12-19 13:57:10 -07004480 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004481 if (currentOffset < 0)
4482 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004483
John Kessenich5e4b1242015-08-06 22:53:06 -06004484 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4485 // but possibly not yet correctly aligned.
4486
4487 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004488 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004489 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4490 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004491
4492 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004493 // TODO: make this consistent in early phases of code:
4494 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4495 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4496 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004497 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004498 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004499 int dummySize;
4500 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4501 if (componentAlignment <= 4)
4502 memberAlignment = componentAlignment;
4503 }
4504
4505 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004506 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004507
4508 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004509 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4510 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004511 glslang::RoundToPow2(currentOffset, 16);
4512
John Kessenich5e4b1242015-08-06 22:53:06 -06004513 nextOffset = currentOffset + memberSize;
4514}
4515
David Netoa901ffe2016-06-08 14:11:40 +01004516void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004517{
David Netoa901ffe2016-06-08 14:11:40 +01004518 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4519 switch (glslangBuiltIn)
4520 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004521 case glslang::EbvPointSize:
4522#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004523 case glslang::EbvClipDistance:
4524 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004525 case glslang::EbvViewportMaskNV:
4526 case glslang::EbvSecondaryPositionNV:
4527 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004528 case glslang::EbvPositionPerViewNV:
4529 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004530 case glslang::EbvTaskCountNV:
4531 case glslang::EbvPrimitiveCountNV:
4532 case glslang::EbvPrimitiveIndicesNV:
4533 case glslang::EbvClipDistancePerViewNV:
4534 case glslang::EbvCullDistancePerViewNV:
4535 case glslang::EbvLayerPerViewNV:
4536 case glslang::EbvMeshViewCountNV:
4537 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004538#endif
David Netoa901ffe2016-06-08 14:11:40 +01004539 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4540 // Alternately, we could just call this for any glslang built-in, since the
4541 // capability already guards against duplicates.
4542 TranslateBuiltInDecoration(glslangBuiltIn, false);
4543 break;
4544 default:
4545 // Capabilities were already generated when the struct was declared.
4546 break;
4547 }
John Kessenichebb50532016-05-16 19:22:05 -06004548}
4549
John Kessenich6fccb3c2016-09-19 16:01:41 -06004550bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004551{
John Kessenicheee9d532016-09-19 18:09:30 -06004552 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004553}
4554
John Kessenichd41993d2017-09-10 15:21:05 -06004555// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004556// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4557// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004558bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004559{
John Kessenich6a14f782017-12-04 02:48:10 -07004560 assert(qualifier == glslang::EvqIn ||
4561 qualifier == glslang::EvqOut ||
4562 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004563 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004564 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004565 return qualifier != glslang::EvqConstReadOnly &&
4566 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004567}
4568
4569// Is parameter pass-by-original?
4570bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4571 bool implicitThisParam)
4572{
4573 if (implicitThisParam) // implicit this
4574 return true;
4575 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004576 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004577 return paramType.containsOpaque() || // sampler, etc.
4578 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4579}
4580
John Kessenich140f3df2015-06-26 16:58:36 -06004581// Make all the functions, skeletally, without actually visiting their bodies.
4582void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4583{
John Kessenich8985fc92020-03-03 10:25:07 -07004584 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4585 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004586 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4587 if (paramPrecision != spv::NoPrecision)
4588 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004589 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004590 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004591 // Original and non-writable params pass the pointer directly and
4592 // use restrict/aliased, others are stored to a pointer in Function
4593 // memory and use RestrictPointer/AliasedPointer.
4594 if (originalParam(type.getQualifier().storage, type, false) ||
4595 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004596 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4597 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004598 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004599 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4600 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004601 }
4602 }
John Kessenichfad62972017-07-18 02:35:46 -06004603 };
4604
John Kessenich140f3df2015-06-26 16:58:36 -06004605 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4606 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004607 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004608 continue;
4609
4610 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004611 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004612 //
qining25262b32016-05-06 17:25:16 -04004613 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004614 // function. What it is an address of varies:
4615 //
John Kessenich4bf71552016-09-02 11:20:21 -06004616 // - "in" parameters not marked as "const" can be written to without modifying the calling
4617 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004618 //
4619 // - "const in" parameters can just be the r-value, as no writes need occur.
4620 //
John Kessenich4bf71552016-09-02 11:20:21 -06004621 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4622 // 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 -06004623
4624 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004625 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004626 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4627
John Kessenich155d3512019-08-08 23:29:20 -06004628#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004629 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4630 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004631#else
4632 bool implicitThis = false;
4633#endif
John Kessenich37789792017-03-21 23:56:40 -06004634
John Kessenichfad62972017-07-18 02:35:46 -06004635 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004636 for (int p = 0; p < (int)parameters.size(); ++p) {
4637 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4638 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004639 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004640 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004641 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004642 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4643 else
John Kessenich4bf71552016-09-02 11:20:21 -06004644 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004645 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004646 paramTypes.push_back(typeId);
4647 }
4648
4649 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004650 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4651 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004652 glslFunction->getName().c_str(), paramTypes,
4653 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004654 if (implicitThis)
4655 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004656
4657 // Track function to emit/call later
4658 functionMap[glslFunction->getName().c_str()] = function;
4659
4660 // Set the parameter id's
4661 for (int p = 0; p < (int)parameters.size(); ++p) {
4662 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4663 // give a name too
4664 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004665
4666 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004667 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004668 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004669 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004670 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004671 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004672 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004673 }
4674 }
4675}
4676
4677// Process all the initializers, while skipping the functions and link objects
4678void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4679{
4680 builder.setBuildPoint(shaderEntry->getLastBlock());
4681 for (int i = 0; i < (int)initializers.size(); ++i) {
4682 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004683 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4684 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004685
4686 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004687 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004688 initializer->traverse(this);
4689 }
4690 }
4691}
Daniel Kochffccefd2020-11-23 15:41:27 -05004692// Walk over all linker objects to create a map for payload and callable data linker objects
4693// and their location to be used during codegen for OpTraceKHR and OpExecuteCallableKHR
4694// This is done here since it is possible that these linker objects are not be referenced in the AST
4695void TGlslangToSpvTraverser::collectRayTracingLinkerObjects()
4696{
4697 glslang::TIntermAggregate* linkerObjects = glslangIntermediate->findLinkerObjects();
4698 for (auto& objSeq : linkerObjects->getSequence()) {
4699 auto objNode = objSeq->getAsSymbolNode();
4700 if (objNode != nullptr) {
4701 if (objNode->getQualifier().hasLocation()) {
4702 unsigned int location = objNode->getQualifier().layoutLocation;
4703 auto st = objNode->getQualifier().storage;
4704 int set;
4705 switch (st)
4706 {
4707 case glslang::EvqPayload:
4708 case glslang::EvqPayloadIn:
4709 set = 0;
4710 break;
4711 case glslang::EvqCallableData:
4712 case glslang::EvqCallableDataIn:
4713 set = 1;
4714 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004715
Daniel Kochffccefd2020-11-23 15:41:27 -05004716 default:
4717 set = -1;
4718 }
4719 if (set != -1)
4720 locationToSymbol[set].insert(std::make_pair(location, objNode));
4721 }
4722 }
4723 }
4724}
John Kessenich140f3df2015-06-26 16:58:36 -06004725// Process all the functions, while skipping initializers.
4726void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4727{
4728 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4729 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004730 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004731 node->traverse(this);
4732 }
4733}
4734
4735void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4736{
qining25262b32016-05-06 17:25:16 -04004737 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004738 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004739 currentFunction = functionMap[node->getName().c_str()];
4740 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004741 builder.setBuildPoint(functionBlock);
4742}
4743
John Kessenich8985fc92020-03-03 10:25:07 -07004744void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4745 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004746{
Rex Xufc618912015-09-09 16:42:49 +08004747 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004748
4749 glslang::TSampler sampler = {};
4750 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004751#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004752 bool f16ShadowCompare = false;
4753#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004754 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004755 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4756 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004757#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004758 f16ShadowCompare = sampler.shadow &&
4759 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004760#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004761 }
4762
John Kessenich140f3df2015-06-26 16:58:36 -06004763 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4764 builder.clearAccessChain();
4765 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004766
John Kessenicha28f7a72019-08-06 07:00:58 -06004767#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004768 // Special case l-value operands
4769 bool lvalue = false;
4770 switch (node.getOp()) {
4771 case glslang::EOpImageAtomicAdd:
4772 case glslang::EOpImageAtomicMin:
4773 case glslang::EOpImageAtomicMax:
4774 case glslang::EOpImageAtomicAnd:
4775 case glslang::EOpImageAtomicOr:
4776 case glslang::EOpImageAtomicXor:
4777 case glslang::EOpImageAtomicExchange:
4778 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004779 case glslang::EOpImageAtomicLoad:
4780 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004781 if (i == 0)
4782 lvalue = true;
4783 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004784 case glslang::EOpSparseImageLoad:
4785 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4786 lvalue = true;
4787 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004788 case glslang::EOpSparseTexture:
4789 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4790 lvalue = true;
4791 break;
4792 case glslang::EOpSparseTextureClamp:
4793 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4794 lvalue = true;
4795 break;
4796 case glslang::EOpSparseTextureLod:
4797 case glslang::EOpSparseTextureOffset:
4798 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4799 lvalue = true;
4800 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004801 case glslang::EOpSparseTextureFetch:
4802 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4803 lvalue = true;
4804 break;
4805 case glslang::EOpSparseTextureFetchOffset:
4806 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4807 lvalue = true;
4808 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004809 case glslang::EOpSparseTextureLodOffset:
4810 case glslang::EOpSparseTextureGrad:
4811 case glslang::EOpSparseTextureOffsetClamp:
4812 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4813 lvalue = true;
4814 break;
4815 case glslang::EOpSparseTextureGradOffset:
4816 case glslang::EOpSparseTextureGradClamp:
4817 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4818 lvalue = true;
4819 break;
4820 case glslang::EOpSparseTextureGradOffsetClamp:
4821 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4822 lvalue = true;
4823 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004824 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004825 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4826 lvalue = true;
4827 break;
4828 case glslang::EOpSparseTextureGatherOffset:
4829 case glslang::EOpSparseTextureGatherOffsets:
4830 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4831 lvalue = true;
4832 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004833 case glslang::EOpSparseTextureGatherLod:
4834 if (i == 3)
4835 lvalue = true;
4836 break;
4837 case glslang::EOpSparseTextureGatherLodOffset:
4838 case glslang::EOpSparseTextureGatherLodOffsets:
4839 if (i == 4)
4840 lvalue = true;
4841 break;
Rex Xu129799a2017-07-05 17:23:28 +08004842 case glslang::EOpSparseImageLoadLod:
4843 if (i == 3)
4844 lvalue = true;
4845 break;
Chao Chen3a137962018-09-19 11:41:27 -07004846 case glslang::EOpImageSampleFootprintNV:
4847 if (i == 4)
4848 lvalue = true;
4849 break;
4850 case glslang::EOpImageSampleFootprintClampNV:
4851 case glslang::EOpImageSampleFootprintLodNV:
4852 if (i == 5)
4853 lvalue = true;
4854 break;
4855 case glslang::EOpImageSampleFootprintGradNV:
4856 if (i == 6)
4857 lvalue = true;
4858 break;
4859 case glslang::EOpImageSampleFootprintGradClampNV:
4860 if (i == 7)
4861 lvalue = true;
4862 break;
Rex Xufc618912015-09-09 16:42:49 +08004863 default:
4864 break;
4865 }
4866
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004867 if (lvalue) {
greg-lunarg639f5462020-11-12 11:10:07 -07004868 spv::Id lvalue_id = builder.accessChainGetLValue();
4869 arguments.push_back(lvalue_id);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004870 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
greg-lunarg639f5462020-11-12 11:10:07 -07004871 builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004872 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4873 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004874#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004875 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004876 }
4877}
4878
John Kessenichfc51d282015-08-19 13:34:18 -06004879void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004880{
John Kessenichfc51d282015-08-19 13:34:18 -06004881 builder.clearAccessChain();
4882 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004883 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004884}
John Kessenich140f3df2015-06-26 16:58:36 -06004885
John Kessenichfc51d282015-08-19 13:34:18 -06004886spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4887{
John Kesseniche485c7a2017-05-31 18:50:53 -06004888 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004889 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004890
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004891 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004892
John Kessenichfc51d282015-08-19 13:34:18 -06004893 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004894
John Kessenichf43c7392019-03-31 10:51:57 -06004895 const glslang::TType &imageType = node->getAsAggregate()
4896 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4897 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004898 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004899#ifdef GLSLANG_WEB
4900 const bool f16ShadowCompare = false;
4901#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004902 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004903 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4904 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004905#endif
4906
John Kessenichf43c7392019-03-31 10:51:57 -06004907 const auto signExtensionMask = [&]() {
4908 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4909 if (sampler.type == glslang::EbtUint)
4910 return spv::ImageOperandsZeroExtendMask;
4911 else if (sampler.type == glslang::EbtInt)
4912 return spv::ImageOperandsSignExtendMask;
4913 }
4914 return spv::ImageOperandsMaskNone;
4915 };
4916
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004917 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4918
John Kessenichfc51d282015-08-19 13:34:18 -06004919 std::vector<spv::Id> arguments;
4920 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004921 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004922 else
4923 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004924 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004925
4926 spv::Builder::TextureParameters params = { };
4927 params.sampler = arguments[0];
4928
Rex Xu04db3f52015-09-16 11:44:02 +08004929 glslang::TCrackedTextureOp cracked;
4930 node->crackTexture(sampler, cracked);
4931
amhagan05506bb2017-06-13 16:53:02 -04004932 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004933
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004934 if (builder.isSampledImage(params.sampler) &&
4935 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4936 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4937 if (imageType.getQualifier().isNonUniform()) {
4938 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4939 }
4940 }
John Kessenichfc51d282015-08-19 13:34:18 -06004941 // Check for queries
4942 if (cracked.query) {
4943 switch (node->getOp()) {
4944 case glslang::EOpImageQuerySize:
4945 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004946 if (arguments.size() > 1) {
4947 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004948 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004949 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004950 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004951#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004952 case glslang::EOpImageQuerySamples:
4953 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004954 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004955 case glslang::EOpTextureQueryLod:
4956 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004957 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004958 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004959 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004960 case glslang::EOpSparseTexelsResident:
4961 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004962#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004963 default:
4964 assert(0);
4965 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004966 }
John Kessenich140f3df2015-06-26 16:58:36 -06004967 }
4968
LoopDawg4425f242018-02-18 11:40:01 -07004969 int components = node->getType().getVectorSize();
4970
4971 if (node->getOp() == glslang::EOpTextureFetch) {
4972 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4973 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4974 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4975 // here around e.g. which ones return scalars or other types.
4976 components = 4;
4977 }
4978
4979 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4980
4981 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4982
Rex Xufc618912015-09-09 16:42:49 +08004983 // Check for image functions other than queries
4984 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004985 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004986 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004987 spv::IdImmediate image = { true, *(opIt++) };
4988 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004989
4990 // Handle subpass operations
4991 // TODO: GLSL should change to have the "MS" only on the type rather than the
4992 // built-in function.
4993 if (cracked.subpass) {
4994 // add on the (0,0) coordinate
4995 spv::Id zero = builder.makeIntConstant(0);
4996 std::vector<spv::Id> comps;
4997 comps.push_back(zero);
4998 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004999 spv::IdImmediate coord = { true,
5000 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
5001 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06005002 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
5003 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005004 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005005 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
5006 }
5007 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06005008 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005009 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005010 spv::IdImmediate imageOperand = { true, *(opIt++) };
5011 operands.push_back(imageOperand);
5012 }
John Kessenich6c292d32016-02-15 20:58:50 -07005013 }
John Kessenichfe4e5722017-10-19 02:07:30 -06005014 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
5015 builder.setPrecision(result, precision);
5016 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07005017 }
5018
John Kessenich149afc32018-08-14 13:31:43 -06005019 spv::IdImmediate coord = { true, *(opIt++) };
5020 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08005021 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005022 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005023 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005024 mask = mask | spv::ImageOperandsSampleMask;
5025 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005026 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005027 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5028 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05005029 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07005030 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005031 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5032 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005033 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005034 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005035 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5036 operands.push_back(imageOperands);
5037 }
5038 if (mask & spv::ImageOperandsSampleMask) {
5039 spv::IdImmediate imageOperand = { true, *opIt++ };
5040 operands.push_back(imageOperand);
5041 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005042 if (mask & spv::ImageOperandsLodMask) {
5043 spv::IdImmediate imageOperand = { true, *opIt++ };
5044 operands.push_back(imageOperand);
5045 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005046 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005047 spv::IdImmediate imageOperand = { true,
5048 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005049 operands.push_back(imageOperand);
5050 }
5051
John Kessenich149afc32018-08-14 13:31:43 -06005052 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005053 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06005054
John Kessenich149afc32018-08-14 13:31:43 -06005055 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07005056 builder.setPrecision(result[0], precision);
5057
5058 // If needed, add a conversion constructor to the proper size.
5059 if (components != node->getType().getVectorSize())
5060 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5061
5062 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08005063 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08005064
Jeff Bolz36831c92018-09-05 10:11:41 -05005065 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005066 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06005067 spv::IdImmediate texel = { true, *(opIt + 1) };
5068 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06005069 } else {
5070 spv::IdImmediate texel = { true, *opIt };
5071 operands.push_back(texel);
5072 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005073
5074 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005075 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005076 mask = mask | spv::ImageOperandsSampleMask;
5077 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005078 if (cracked.lod) {
5079 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5080 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5081 mask = mask | spv::ImageOperandsLodMask;
5082 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005083 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5084 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005085 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005086 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005087 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5088 operands.push_back(imageOperands);
5089 }
5090 if (mask & spv::ImageOperandsSampleMask) {
5091 spv::IdImmediate imageOperand = { true, *opIt++ };
5092 operands.push_back(imageOperand);
5093 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005094 if (mask & spv::ImageOperandsLodMask) {
5095 spv::IdImmediate imageOperand = { true, *opIt++ };
5096 operands.push_back(imageOperand);
5097 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005098 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005099 spv::IdImmediate imageOperand = { true,
5100 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005101 operands.push_back(imageOperand);
5102 }
5103
John Kessenich56bab042015-09-16 10:54:31 -06005104 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06005105 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005106 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06005107 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06005108 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
5109 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08005110 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06005111 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08005112 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
5113
Jeff Bolz36831c92018-09-05 10:11:41 -05005114 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005115 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005116 mask = mask | spv::ImageOperandsSampleMask;
5117 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005118 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005119 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5120 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5121
Jeff Bolz36831c92018-09-05 10:11:41 -05005122 mask = mask | spv::ImageOperandsLodMask;
5123 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005124 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5125 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005126 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005127 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005128 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06005129 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05005130 }
5131 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06005132 spv::IdImmediate imageOperand = { true, *opIt++ };
5133 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05005134 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005135 if (mask & spv::ImageOperandsLodMask) {
5136 spv::IdImmediate imageOperand = { true, *opIt++ };
5137 operands.push_back(imageOperand);
5138 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005139 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005140 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5141 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005142 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005143 }
5144
5145 // Create the return type that was a special structure
5146 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005147 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005148 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5149 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5150
5151 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5152
5153 // Decode the return type
5154 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5155 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005156 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005157 // Process image atomic operations
5158
5159 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5160 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005161 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005162 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005163 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005164
Jeff Bolz36831c92018-09-05 10:11:41 -05005165 spv::Id resultTypeId;
5166 // imageAtomicStore has a void return type so base the pointer type on
5167 // the type of the value operand.
5168 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005169 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005170 } else {
5171 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5172 }
John Kessenich56bab042015-09-16 10:54:31 -06005173 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005174 if (imageType.getQualifier().nonUniform) {
5175 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5176 }
Rex Xufc618912015-09-09 16:42:49 +08005177
5178 std::vector<spv::Id> operands;
5179 operands.push_back(pointer);
5180 for (; opIt != arguments.end(); ++opIt)
5181 operands.push_back(*opIt);
5182
John Kessenich8985fc92020-03-03 10:25:07 -07005183 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5184 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005185 }
5186 }
5187
John Kessenicha28f7a72019-08-06 07:00:58 -06005188#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005189 // Check for fragment mask functions other than queries
5190 if (cracked.fragMask) {
5191 assert(sampler.ms);
5192
5193 auto opIt = arguments.begin();
5194 std::vector<spv::Id> operands;
5195
amhagan05506bb2017-06-13 16:53:02 -04005196 operands.push_back(params.sampler);
5197 ++opIt;
5198
5199 if (sampler.isSubpass()) {
5200 // add on the (0,0) coordinate
5201 spv::Id zero = builder.makeIntConstant(0);
5202 std::vector<spv::Id> comps;
5203 comps.push_back(zero);
5204 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005205 operands.push_back(builder.makeCompositeConstant(
5206 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005207 }
5208
5209 for (; opIt != arguments.end(); ++opIt)
5210 operands.push_back(*opIt);
5211
5212 spv::Op fragMaskOp = spv::OpNop;
5213 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5214 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5215 else if (node->getOp() == glslang::EOpFragmentFetch)
5216 fragMaskOp = spv::OpFragmentFetchAMD;
5217
5218 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5219 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5220 return builder.createOp(fragMaskOp, resultType(), operands);
5221 }
5222#endif
5223
Rex Xufc618912015-09-09 16:42:49 +08005224 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005225 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005226 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005227 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005228
John Kessenichfc51d282015-08-19 13:34:18 -06005229 // check for bias argument
5230 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005231 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005232 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005233 if (cracked.gather)
5234 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005235
5236 if (f16ShadowCompare)
5237 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005238 if (cracked.offset)
5239 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005240 else if (cracked.offsets)
5241 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005242 if (cracked.grad)
5243 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005244 if (cracked.lodClamp)
5245 ++nonBiasArgCount;
5246 if (sparse)
5247 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005248 if (imageFootprint)
5249 //Following three extra arguments
5250 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5251 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005252 if ((int)arguments.size() > nonBiasArgCount)
5253 bias = true;
5254 }
5255
John Kessenicha28f7a72019-08-06 07:00:58 -06005256#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005257 if (cracked.gather) {
5258 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5259 if (bias || cracked.lod ||
5260 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5261 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005262 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005263 }
5264 }
5265#endif
5266
John Kessenichfc51d282015-08-19 13:34:18 -06005267 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005268
John Kessenichfc51d282015-08-19 13:34:18 -06005269 params.coords = arguments[1];
5270 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005271 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005272
5273 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005274 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005275 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005276 ++extraArgs;
5277 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005278 params.Dref = arguments[2];
5279 ++extraArgs;
5280 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005281 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005282 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005283 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005284 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005285 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005286 dRefComp = builder.getNumComponents(params.coords) - 1;
5287 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005288 params.Dref = builder.createCompositeExtract(params.coords,
5289 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005290 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005291
5292 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005293 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005294 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005295 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005296 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5297 !(glslangIntermediate->getStage() == EShLangCompute &&
5298 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005299 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5300 noImplicitLod = true;
5301 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005302
5303 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005304 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005305 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005306 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005307 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005308
5309 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005310 if (cracked.grad) {
5311 params.gradX = arguments[2 + extraArgs];
5312 params.gradY = arguments[3 + extraArgs];
5313 extraArgs += 2;
5314 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005315
5316 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005317 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005318 params.offset = arguments[2 + extraArgs];
5319 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005320 } else if (cracked.offsets) {
5321 params.offsets = arguments[2 + extraArgs];
5322 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005323 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005324
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005325#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005326 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005327 if (cracked.lodClamp) {
5328 params.lodClamp = arguments[2 + extraArgs];
5329 ++extraArgs;
5330 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005331 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005332 if (sparse) {
5333 params.texelOut = arguments[2 + extraArgs];
5334 ++extraArgs;
5335 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005336 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005337 if (cracked.gather && ! sampler.shadow) {
5338 // default component is 0, if missing, otherwise an argument
5339 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005340 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005341 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005342 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005343 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005344 }
Chao Chen3a137962018-09-19 11:41:27 -07005345 spv::Id resultStruct = spv::NoResult;
5346 if (imageFootprint) {
5347 //Following three extra arguments
5348 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5349 params.granularity = arguments[2 + extraArgs];
5350 params.coarse = arguments[3 + extraArgs];
5351 resultStruct = arguments[4 + extraArgs];
5352 extraArgs += 3;
5353 }
5354#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005355 // bias
5356 if (bias) {
5357 params.bias = arguments[2 + extraArgs];
5358 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005359 }
John Kessenichfc51d282015-08-19 13:34:18 -06005360
John Kessenicha28f7a72019-08-06 07:00:58 -06005361#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005362 if (imageFootprint) {
5363 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5364 builder.addCapability(spv::CapabilityImageFootprintNV);
5365
5366
5367 //resultStructType(OpenGL type) contains 5 elements:
5368 //struct gl_TextureFootprint2DNV {
5369 // uvec2 anchor;
5370 // uvec2 offset;
5371 // uvec2 mask;
5372 // uint lod;
5373 // uint granularity;
5374 //};
5375 //or
5376 //struct gl_TextureFootprint3DNV {
5377 // uvec3 anchor;
5378 // uvec3 offset;
5379 // uvec2 mask;
5380 // uint lod;
5381 // uint granularity;
5382 //};
5383 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5384 assert(builder.isStructType(resultStructType));
5385
5386 //resType (SPIR-V type) contains 6 elements:
5387 //Member 0 must be a Boolean type scalar(LOD),
5388 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5389 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5390 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5391 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5392 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5393 std::vector<spv::Id> members;
5394 members.push_back(resultType());
5395 for (int i = 0; i < 5; i++) {
5396 members.push_back(builder.getContainedTypeId(resultStructType, i));
5397 }
5398 spv::Id resType = builder.makeStructType(members, "ResType");
5399
5400 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005401 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5402 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005403
5404 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5405 for (int i = 0; i < 5; i++) {
5406 builder.clearAccessChain();
5407 builder.setAccessChainLValue(resultStruct);
5408
5409 //Accessing to a struct we created, no coherent flag is set
5410 spv::Builder::AccessChain::CoherentFlags flags;
5411 flags.clear();
5412
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005413 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005414 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005415 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005416 }
5417 return builder.createCompositeExtract(res, resultType(), 0);
5418 }
5419#endif
5420
John Kessenich65336482016-06-16 14:06:26 -06005421 // projective component (might not to move)
5422 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5423 // are divided by the last component of P."
5424 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5425 // unused components will appear after all used components."
5426 if (cracked.proj) {
5427 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5428 int projTargetComp;
5429 switch (sampler.dim) {
5430 case glslang::Esd1D: projTargetComp = 1; break;
5431 case glslang::Esd2D: projTargetComp = 2; break;
5432 case glslang::EsdRect: projTargetComp = 2; break;
5433 default: projTargetComp = projSourceComp; break;
5434 }
5435 // copy the projective coordinate if we have to
5436 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005437 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005438 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005439 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005440 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005441 }
5442 }
5443
John Kessenichf8d1d742019-10-21 06:55:11 -06005444#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005445 // nonprivate
5446 if (imageType.getQualifier().nonprivate) {
5447 params.nonprivate = true;
5448 }
5449
5450 // volatile
5451 if (imageType.getQualifier().volatil) {
5452 params.volatil = true;
5453 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005454#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005455
St0fFa1184dd2018-04-09 21:08:14 +02005456 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005457 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5458 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005459 );
LoopDawg4425f242018-02-18 11:40:01 -07005460
5461 if (components != node->getType().getVectorSize())
5462 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5463
5464 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005465}
5466
5467spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5468{
5469 // Grab the function's pointer from the previously created function
5470 spv::Function* function = functionMap[node->getName().c_str()];
5471 if (! function)
5472 return 0;
5473
5474 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5475 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5476
5477 // See comments in makeFunctions() for details about the semantics for parameter passing.
5478 //
5479 // These imply we need a four step process:
5480 // 1. Evaluate the arguments
5481 // 2. Allocate and make copies of in, out, and inout arguments
5482 // 3. Make the call
5483 // 4. Copy back the results
5484
John Kessenichd3ed90b2018-05-04 11:43:03 -06005485 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005486 std::vector<spv::Builder::AccessChain> lValues;
5487 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005488 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005490 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005491 // build l-value
5492 builder.clearAccessChain();
5493 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005494 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005495 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005496 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005497 // save l-value
5498 lValues.push_back(builder.getAccessChain());
5499 } else {
5500 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005501 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005502 }
5503 }
5504
5505 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5506 // copy the original into that space.
5507 //
5508 // Also, build up the list of actual arguments to pass in for the call
5509 int lValueCount = 0;
5510 int rValueCount = 0;
5511 std::vector<spv::Id> spvArgs;
5512 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5513 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005514 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005515 builder.setAccessChain(lValues[lValueCount]);
5516 arg = builder.accessChainGetLValue();
5517 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005518 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005519 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005520 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005521 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005522 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5523 // need to copy the input into output space
5524 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005525 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005526 builder.clearAccessChain();
5527 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005528 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005529 }
5530 ++lValueCount;
5531 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005532 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005533 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005534 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005535 {
John Kessenich435dd802020-06-30 01:27:08 -06005536 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005537 builder.clearAccessChain();
5538 builder.setAccessChainLValue(argCopy);
5539 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005540 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005541 } else
5542 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005543 ++rValueCount;
5544 }
5545 spvArgs.push_back(arg);
5546 }
5547
5548 // 3. Make the call.
5549 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005550 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
greg-lunarg639f5462020-11-12 11:10:07 -07005551 builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005552
5553 // 4. Copy back out an "out" arguments.
5554 lValueCount = 0;
5555 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005556 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005557 ++lValueCount;
5558 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005559 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005560 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
greg-lunarg639f5462020-11-12 11:10:07 -07005561 builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005562 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005563 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005564 }
5565 ++lValueCount;
5566 }
5567 }
5568
5569 return result;
5570}
5571
5572// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005573spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005574 spv::Id typeId, spv::Id left, spv::Id right,
5575 glslang::TBasicType typeProxy, bool reduceComparison)
5576{
John Kessenich66011cb2018-03-06 16:12:04 -07005577 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5578 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005579 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005580
5581 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005582 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005583 bool comparison = false;
5584
5585 switch (op) {
5586 case glslang::EOpAdd:
5587 case glslang::EOpAddAssign:
5588 if (isFloat)
5589 binOp = spv::OpFAdd;
5590 else
5591 binOp = spv::OpIAdd;
5592 break;
5593 case glslang::EOpSub:
5594 case glslang::EOpSubAssign:
5595 if (isFloat)
5596 binOp = spv::OpFSub;
5597 else
5598 binOp = spv::OpISub;
5599 break;
5600 case glslang::EOpMul:
5601 case glslang::EOpMulAssign:
5602 if (isFloat)
5603 binOp = spv::OpFMul;
5604 else
5605 binOp = spv::OpIMul;
5606 break;
5607 case glslang::EOpVectorTimesScalar:
5608 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005609 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005610 if (builder.isVector(right))
5611 std::swap(left, right);
5612 assert(builder.isScalar(right));
5613 needMatchingVectors = false;
5614 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005615 } else if (isFloat)
5616 binOp = spv::OpFMul;
5617 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005618 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005619 break;
5620 case glslang::EOpVectorTimesMatrix:
5621 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005622 binOp = spv::OpVectorTimesMatrix;
5623 break;
5624 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005625 binOp = spv::OpMatrixTimesVector;
5626 break;
5627 case glslang::EOpMatrixTimesScalar:
5628 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005629 binOp = spv::OpMatrixTimesScalar;
5630 break;
5631 case glslang::EOpMatrixTimesMatrix:
5632 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005633 binOp = spv::OpMatrixTimesMatrix;
5634 break;
5635 case glslang::EOpOuterProduct:
5636 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005637 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005638 break;
5639
5640 case glslang::EOpDiv:
5641 case glslang::EOpDivAssign:
5642 if (isFloat)
5643 binOp = spv::OpFDiv;
5644 else if (isUnsigned)
5645 binOp = spv::OpUDiv;
5646 else
5647 binOp = spv::OpSDiv;
5648 break;
5649 case glslang::EOpMod:
5650 case glslang::EOpModAssign:
5651 if (isFloat)
5652 binOp = spv::OpFMod;
5653 else if (isUnsigned)
5654 binOp = spv::OpUMod;
5655 else
5656 binOp = spv::OpSMod;
5657 break;
5658 case glslang::EOpRightShift:
5659 case glslang::EOpRightShiftAssign:
5660 if (isUnsigned)
5661 binOp = spv::OpShiftRightLogical;
5662 else
5663 binOp = spv::OpShiftRightArithmetic;
5664 break;
5665 case glslang::EOpLeftShift:
5666 case glslang::EOpLeftShiftAssign:
5667 binOp = spv::OpShiftLeftLogical;
5668 break;
5669 case glslang::EOpAnd:
5670 case glslang::EOpAndAssign:
5671 binOp = spv::OpBitwiseAnd;
5672 break;
5673 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005674 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005675 binOp = spv::OpLogicalAnd;
5676 break;
5677 case glslang::EOpInclusiveOr:
5678 case glslang::EOpInclusiveOrAssign:
5679 binOp = spv::OpBitwiseOr;
5680 break;
5681 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005682 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005683 binOp = spv::OpLogicalOr;
5684 break;
5685 case glslang::EOpExclusiveOr:
5686 case glslang::EOpExclusiveOrAssign:
5687 binOp = spv::OpBitwiseXor;
5688 break;
5689 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005690 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005691 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005692 break;
5693
Ian Romanickb3bd4022019-01-21 08:57:25 -08005694 case glslang::EOpAbsDifference:
5695 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5696 break;
5697
5698 case glslang::EOpAddSaturate:
5699 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5700 break;
5701
5702 case glslang::EOpSubSaturate:
5703 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5704 break;
5705
5706 case glslang::EOpAverage:
5707 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5708 break;
5709
5710 case glslang::EOpAverageRounded:
5711 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5712 break;
5713
5714 case glslang::EOpMul32x16:
5715 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5716 break;
5717
John Kessenich140f3df2015-06-26 16:58:36 -06005718 case glslang::EOpLessThan:
5719 case glslang::EOpGreaterThan:
5720 case glslang::EOpLessThanEqual:
5721 case glslang::EOpGreaterThanEqual:
5722 case glslang::EOpEqual:
5723 case glslang::EOpNotEqual:
5724 case glslang::EOpVectorEqual:
5725 case glslang::EOpVectorNotEqual:
5726 comparison = true;
5727 break;
5728 default:
5729 break;
5730 }
5731
John Kessenich7c1aa102015-10-15 13:29:11 -06005732 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005733 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005734 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005735 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5736 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005737 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005738
5739 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005740 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005741 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005742
qining25262b32016-05-06 17:25:16 -04005743 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005744 decorations.addNoContraction(builder, result);
5745 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005746 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005747 }
5748
5749 if (! comparison)
5750 return 0;
5751
John Kessenich7c1aa102015-10-15 13:29:11 -06005752 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005753
John Kessenich4583b612016-08-07 19:14:22 -06005754 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005755 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5756 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005757 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005758 return result;
5759 }
John Kessenich140f3df2015-06-26 16:58:36 -06005760
5761 switch (op) {
5762 case glslang::EOpLessThan:
5763 if (isFloat)
5764 binOp = spv::OpFOrdLessThan;
5765 else if (isUnsigned)
5766 binOp = spv::OpULessThan;
5767 else
5768 binOp = spv::OpSLessThan;
5769 break;
5770 case glslang::EOpGreaterThan:
5771 if (isFloat)
5772 binOp = spv::OpFOrdGreaterThan;
5773 else if (isUnsigned)
5774 binOp = spv::OpUGreaterThan;
5775 else
5776 binOp = spv::OpSGreaterThan;
5777 break;
5778 case glslang::EOpLessThanEqual:
5779 if (isFloat)
5780 binOp = spv::OpFOrdLessThanEqual;
5781 else if (isUnsigned)
5782 binOp = spv::OpULessThanEqual;
5783 else
5784 binOp = spv::OpSLessThanEqual;
5785 break;
5786 case glslang::EOpGreaterThanEqual:
5787 if (isFloat)
5788 binOp = spv::OpFOrdGreaterThanEqual;
5789 else if (isUnsigned)
5790 binOp = spv::OpUGreaterThanEqual;
5791 else
5792 binOp = spv::OpSGreaterThanEqual;
5793 break;
5794 case glslang::EOpEqual:
5795 case glslang::EOpVectorEqual:
5796 if (isFloat)
5797 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005798 else if (isBool)
5799 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005800 else
5801 binOp = spv::OpIEqual;
5802 break;
5803 case glslang::EOpNotEqual:
5804 case glslang::EOpVectorNotEqual:
5805 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005806 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005807 else if (isBool)
5808 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 else
5810 binOp = spv::OpINotEqual;
5811 break;
5812 default:
5813 break;
5814 }
5815
qining25262b32016-05-06 17:25:16 -04005816 if (binOp != spv::OpNop) {
5817 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005818 decorations.addNoContraction(builder, result);
5819 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005820 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005821 }
John Kessenich140f3df2015-06-26 16:58:36 -06005822
5823 return 0;
5824}
5825
John Kessenich04bb8a02015-12-12 12:28:14 -07005826//
5827// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5828// These can be any of:
5829//
5830// matrix * scalar
5831// scalar * matrix
5832// matrix * matrix linear algebraic
5833// matrix * vector
5834// vector * matrix
5835// matrix * matrix componentwise
5836// matrix op matrix op in {+, -, /}
5837// matrix op scalar op in {+, -, /}
5838// scalar op matrix op in {+, -, /}
5839//
John Kessenichead86222018-03-28 18:01:20 -06005840spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5841 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005842{
5843 bool firstClass = true;
5844
5845 // First, handle first-class matrix operations (* and matrix/scalar)
5846 switch (op) {
5847 case spv::OpFDiv:
5848 if (builder.isMatrix(left) && builder.isScalar(right)) {
5849 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005850 spv::Id resultType = builder.getTypeId(right);
5851 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005852 op = spv::OpMatrixTimesScalar;
5853 } else
5854 firstClass = false;
5855 break;
5856 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005857 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005858 std::swap(left, right);
5859 assert(builder.isScalar(right));
5860 break;
5861 case spv::OpVectorTimesMatrix:
5862 assert(builder.isVector(left));
5863 assert(builder.isMatrix(right));
5864 break;
5865 case spv::OpMatrixTimesVector:
5866 assert(builder.isMatrix(left));
5867 assert(builder.isVector(right));
5868 break;
5869 case spv::OpMatrixTimesMatrix:
5870 assert(builder.isMatrix(left));
5871 assert(builder.isMatrix(right));
5872 break;
5873 default:
5874 firstClass = false;
5875 break;
5876 }
5877
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005878 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5879 firstClass = true;
5880
qining25262b32016-05-06 17:25:16 -04005881 if (firstClass) {
5882 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005883 decorations.addNoContraction(builder, result);
5884 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005885 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005886 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005887
LoopDawg592860c2016-06-09 08:57:35 -06005888 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005889 // The result type of all of them is the same type as the (a) matrix operand.
5890 // The algorithm is to:
5891 // - break the matrix(es) into vectors
5892 // - smear any scalar to a vector
5893 // - do vector operations
5894 // - make a matrix out the vector results
5895 switch (op) {
5896 case spv::OpFAdd:
5897 case spv::OpFSub:
5898 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005899 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005900 case spv::OpFMul:
5901 {
5902 // one time set up...
5903 bool leftMat = builder.isMatrix(left);
5904 bool rightMat = builder.isMatrix(right);
5905 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5906 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5907 spv::Id scalarType = builder.getScalarTypeId(typeId);
5908 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5909 std::vector<spv::Id> results;
5910 spv::Id smearVec = spv::NoResult;
5911 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005912 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005913 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005914 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005915
5916 // do each vector op
5917 for (unsigned int c = 0; c < numCols; ++c) {
5918 std::vector<unsigned int> indexes;
5919 indexes.push_back(c);
5920 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5921 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005922 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005923 decorations.addNoContraction(builder, result);
5924 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005925 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005926 }
5927
5928 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005929 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005930 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005931 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005932 }
5933 default:
5934 assert(0);
5935 return spv::NoResult;
5936 }
5937}
5938
John Kessenichead86222018-03-28 18:01:20 -06005939spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005940 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005941{
5942 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005943 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005944 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005945 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5946 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005947
5948 switch (op) {
5949 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005950 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005951 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005952 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005953 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005954 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005955 unaryOp = spv::OpSNegate;
5956 break;
5957
5958 case glslang::EOpLogicalNot:
5959 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005960 unaryOp = spv::OpLogicalNot;
5961 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005962 case glslang::EOpBitwiseNot:
5963 unaryOp = spv::OpNot;
5964 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005965
John Kessenich140f3df2015-06-26 16:58:36 -06005966 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005967 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005968 break;
5969 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005970 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005971 break;
5972 case glslang::EOpTranspose:
5973 unaryOp = spv::OpTranspose;
5974 break;
5975
5976 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005977 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005978 break;
5979 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005980 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005981 break;
5982 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005983 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005984 break;
5985 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005986 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005987 break;
5988 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005989 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005990 break;
5991 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005992 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005993 break;
5994 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005995 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005996 break;
5997 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005998 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005999 break;
6000
6001 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006002 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006003 break;
6004 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006005 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006006 break;
6007 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006008 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006009 break;
6010 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006011 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006012 break;
6013 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006014 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
6016 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006017 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006018 break;
6019
6020 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06006021 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06006022 break;
6023 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06006024 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06006025 break;
6026
6027 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006028 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06006029 break;
6030 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06006031 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06006032 break;
6033 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006034 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06006035 break;
6036 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006037 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06006038 break;
6039 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006040 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006041 break;
6042 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006043 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006044 break;
6045
6046 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06006047 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06006048 break;
6049 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06006050 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06006051 break;
6052 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06006053 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06006054 break;
6055 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06006056 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06006057 break;
6058 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06006059 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06006060 break;
6061 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006062 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06006063 break;
6064
6065 case glslang::EOpIsNan:
6066 unaryOp = spv::OpIsNan;
6067 break;
6068 case glslang::EOpIsInf:
6069 unaryOp = spv::OpIsInf;
6070 break;
LoopDawg592860c2016-06-09 08:57:35 -06006071 case glslang::EOpIsFinite:
6072 unaryOp = spv::OpIsFinite;
6073 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006074
Rex Xucbc426e2015-12-15 16:03:10 +08006075 case glslang::EOpFloatBitsToInt:
6076 case glslang::EOpFloatBitsToUint:
6077 case glslang::EOpIntBitsToFloat:
6078 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08006079 case glslang::EOpDoubleBitsToInt64:
6080 case glslang::EOpDoubleBitsToUint64:
6081 case glslang::EOpInt64BitsToDouble:
6082 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08006083 case glslang::EOpFloat16BitsToInt16:
6084 case glslang::EOpFloat16BitsToUint16:
6085 case glslang::EOpInt16BitsToFloat16:
6086 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08006087 unaryOp = spv::OpBitcast;
6088 break;
6089
John Kessenich140f3df2015-06-26 16:58:36 -06006090 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006091 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006092 break;
6093 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006094 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006095 break;
6096 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006097 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006098 break;
6099 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006100 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006101 break;
6102 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006103 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006104 break;
6105 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006106 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006107 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006108#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06006109 case glslang::EOpPackSnorm4x8:
6110 libCall = spv::GLSLstd450PackSnorm4x8;
6111 break;
6112 case glslang::EOpUnpackSnorm4x8:
6113 libCall = spv::GLSLstd450UnpackSnorm4x8;
6114 break;
6115 case glslang::EOpPackUnorm4x8:
6116 libCall = spv::GLSLstd450PackUnorm4x8;
6117 break;
6118 case glslang::EOpUnpackUnorm4x8:
6119 libCall = spv::GLSLstd450UnpackUnorm4x8;
6120 break;
6121 case glslang::EOpPackDouble2x32:
6122 libCall = spv::GLSLstd450PackDouble2x32;
6123 break;
6124 case glslang::EOpUnpackDouble2x32:
6125 libCall = spv::GLSLstd450UnpackDouble2x32;
6126 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006127#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006128
Rex Xu8ff43de2016-04-22 16:51:45 +08006129 case glslang::EOpPackInt2x32:
6130 case glslang::EOpUnpackInt2x32:
6131 case glslang::EOpPackUint2x32:
6132 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07006133 case glslang::EOpPack16:
6134 case glslang::EOpPack32:
6135 case glslang::EOpPack64:
6136 case glslang::EOpUnpack32:
6137 case glslang::EOpUnpack16:
6138 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006139 case glslang::EOpPackInt2x16:
6140 case glslang::EOpUnpackInt2x16:
6141 case glslang::EOpPackUint2x16:
6142 case glslang::EOpUnpackUint2x16:
6143 case glslang::EOpPackInt4x16:
6144 case glslang::EOpUnpackInt4x16:
6145 case glslang::EOpPackUint4x16:
6146 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006147 case glslang::EOpPackFloat2x16:
6148 case glslang::EOpUnpackFloat2x16:
6149 unaryOp = spv::OpBitcast;
6150 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006151
John Kessenich140f3df2015-06-26 16:58:36 -06006152 case glslang::EOpDPdx:
6153 unaryOp = spv::OpDPdx;
6154 break;
6155 case glslang::EOpDPdy:
6156 unaryOp = spv::OpDPdy;
6157 break;
6158 case glslang::EOpFwidth:
6159 unaryOp = spv::OpFwidth;
6160 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006161
John Kessenich140f3df2015-06-26 16:58:36 -06006162 case glslang::EOpAny:
6163 unaryOp = spv::OpAny;
6164 break;
6165 case glslang::EOpAll:
6166 unaryOp = spv::OpAll;
6167 break;
6168
6169 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006170 if (isFloat)
6171 libCall = spv::GLSLstd450FAbs;
6172 else
6173 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006174 break;
6175 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006176 if (isFloat)
6177 libCall = spv::GLSLstd450FSign;
6178 else
6179 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006180 break;
6181
John Kessenicha28f7a72019-08-06 07:00:58 -06006182#ifndef GLSLANG_WEB
6183 case glslang::EOpDPdxFine:
6184 unaryOp = spv::OpDPdxFine;
6185 break;
6186 case glslang::EOpDPdyFine:
6187 unaryOp = spv::OpDPdyFine;
6188 break;
6189 case glslang::EOpFwidthFine:
6190 unaryOp = spv::OpFwidthFine;
6191 break;
6192 case glslang::EOpDPdxCoarse:
6193 unaryOp = spv::OpDPdxCoarse;
6194 break;
6195 case glslang::EOpDPdyCoarse:
6196 unaryOp = spv::OpDPdyCoarse;
6197 break;
6198 case glslang::EOpFwidthCoarse:
6199 unaryOp = spv::OpFwidthCoarse;
6200 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006201 case glslang::EOpRayQueryProceed:
6202 unaryOp = spv::OpRayQueryProceedKHR;
6203 break;
6204 case glslang::EOpRayQueryGetRayTMin:
6205 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6206 break;
6207 case glslang::EOpRayQueryGetRayFlags:
6208 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6209 break;
6210 case glslang::EOpRayQueryGetWorldRayOrigin:
6211 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6212 break;
6213 case glslang::EOpRayQueryGetWorldRayDirection:
6214 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6215 break;
6216 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6217 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6218 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006219 case glslang::EOpInterpolateAtCentroid:
6220 if (typeProxy == glslang::EbtFloat16)
6221 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6222 libCall = spv::GLSLstd450InterpolateAtCentroid;
6223 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006224 case glslang::EOpAtomicCounterIncrement:
6225 case glslang::EOpAtomicCounterDecrement:
6226 case glslang::EOpAtomicCounter:
6227 {
6228 // Handle all of the atomics in one place, in createAtomicOperation()
6229 std::vector<spv::Id> operands;
6230 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006231 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006232 }
6233
John Kessenichfc51d282015-08-19 13:34:18 -06006234 case glslang::EOpBitFieldReverse:
6235 unaryOp = spv::OpBitReverse;
6236 break;
6237 case glslang::EOpBitCount:
6238 unaryOp = spv::OpBitCount;
6239 break;
6240 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006241 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006242 break;
6243 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006244 if (isUnsigned)
6245 libCall = spv::GLSLstd450FindUMsb;
6246 else
6247 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006248 break;
6249
Ian Romanickb3bd4022019-01-21 08:57:25 -08006250 case glslang::EOpCountLeadingZeros:
6251 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6252 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6253 unaryOp = spv::OpUCountLeadingZerosINTEL;
6254 break;
6255
6256 case glslang::EOpCountTrailingZeros:
6257 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6258 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6259 unaryOp = spv::OpUCountTrailingZerosINTEL;
6260 break;
6261
Rex Xu574ab042016-04-14 16:53:07 +08006262 case glslang::EOpBallot:
6263 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006264 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006265 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006266 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006267 case glslang::EOpMinInvocations:
6268 case glslang::EOpMaxInvocations:
6269 case glslang::EOpAddInvocations:
6270 case glslang::EOpMinInvocationsNonUniform:
6271 case glslang::EOpMaxInvocationsNonUniform:
6272 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006273 case glslang::EOpMinInvocationsInclusiveScan:
6274 case glslang::EOpMaxInvocationsInclusiveScan:
6275 case glslang::EOpAddInvocationsInclusiveScan:
6276 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6277 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6278 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6279 case glslang::EOpMinInvocationsExclusiveScan:
6280 case glslang::EOpMaxInvocationsExclusiveScan:
6281 case glslang::EOpAddInvocationsExclusiveScan:
6282 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6283 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6284 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006285 {
6286 std::vector<spv::Id> operands;
6287 operands.push_back(operand);
6288 return createInvocationsOperation(op, typeId, operands, typeProxy);
6289 }
John Kessenich66011cb2018-03-06 16:12:04 -07006290 case glslang::EOpSubgroupAll:
6291 case glslang::EOpSubgroupAny:
6292 case glslang::EOpSubgroupAllEqual:
6293 case glslang::EOpSubgroupBroadcastFirst:
6294 case glslang::EOpSubgroupBallot:
6295 case glslang::EOpSubgroupInverseBallot:
6296 case glslang::EOpSubgroupBallotBitCount:
6297 case glslang::EOpSubgroupBallotInclusiveBitCount:
6298 case glslang::EOpSubgroupBallotExclusiveBitCount:
6299 case glslang::EOpSubgroupBallotFindLSB:
6300 case glslang::EOpSubgroupBallotFindMSB:
6301 case glslang::EOpSubgroupAdd:
6302 case glslang::EOpSubgroupMul:
6303 case glslang::EOpSubgroupMin:
6304 case glslang::EOpSubgroupMax:
6305 case glslang::EOpSubgroupAnd:
6306 case glslang::EOpSubgroupOr:
6307 case glslang::EOpSubgroupXor:
6308 case glslang::EOpSubgroupInclusiveAdd:
6309 case glslang::EOpSubgroupInclusiveMul:
6310 case glslang::EOpSubgroupInclusiveMin:
6311 case glslang::EOpSubgroupInclusiveMax:
6312 case glslang::EOpSubgroupInclusiveAnd:
6313 case glslang::EOpSubgroupInclusiveOr:
6314 case glslang::EOpSubgroupInclusiveXor:
6315 case glslang::EOpSubgroupExclusiveAdd:
6316 case glslang::EOpSubgroupExclusiveMul:
6317 case glslang::EOpSubgroupExclusiveMin:
6318 case glslang::EOpSubgroupExclusiveMax:
6319 case glslang::EOpSubgroupExclusiveAnd:
6320 case glslang::EOpSubgroupExclusiveOr:
6321 case glslang::EOpSubgroupExclusiveXor:
6322 case glslang::EOpSubgroupQuadSwapHorizontal:
6323 case glslang::EOpSubgroupQuadSwapVertical:
6324 case glslang::EOpSubgroupQuadSwapDiagonal: {
6325 std::vector<spv::Id> operands;
6326 operands.push_back(operand);
6327 return createSubgroupOperation(op, typeId, operands, typeProxy);
6328 }
Rex Xu9d93a232016-05-05 12:30:44 +08006329 case glslang::EOpMbcnt:
6330 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6331 libCall = spv::MbcntAMD;
6332 break;
6333
6334 case glslang::EOpCubeFaceIndex:
6335 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6336 libCall = spv::CubeFaceIndexAMD;
6337 break;
6338
6339 case glslang::EOpCubeFaceCoord:
6340 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6341 libCall = spv::CubeFaceCoordAMD;
6342 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006343 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006344 unaryOp = spv::OpGroupNonUniformPartitionNV;
6345 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006346 case glslang::EOpConstructReference:
6347 unaryOp = spv::OpBitcast;
6348 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05006349
6350 case glslang::EOpConvUint64ToAccStruct:
6351 case glslang::EOpConvUvec2ToAccStruct:
6352 unaryOp = spv::OpConvertUToAccelerationStructureKHR;
6353 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006354#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006355
6356 case glslang::EOpCopyObject:
6357 unaryOp = spv::OpCopyObject;
6358 break;
6359
John Kessenich140f3df2015-06-26 16:58:36 -06006360 default:
6361 return 0;
6362 }
6363
6364 spv::Id id;
6365 if (libCall >= 0) {
6366 std::vector<spv::Id> args;
6367 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006368 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006369 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006370 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006371 }
John Kessenich140f3df2015-06-26 16:58:36 -06006372
John Kessenichb9197c82019-08-11 07:41:45 -06006373 decorations.addNoContraction(builder, id);
6374 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006375 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006376}
6377
John Kessenich7a53f762016-01-20 11:19:27 -07006378// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006379spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6380 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006381{
6382 // Handle unary operations vector by vector.
6383 // The result type is the same type as the original type.
6384 // The algorithm is to:
6385 // - break the matrix into vectors
6386 // - apply the operation to each vector
6387 // - make a matrix out the vector results
6388
6389 // get the types sorted out
6390 int numCols = builder.getNumColumns(operand);
6391 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006392 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6393 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006394 std::vector<spv::Id> results;
6395
6396 // do each vector op
6397 for (int c = 0; c < numCols; ++c) {
6398 std::vector<unsigned int> indexes;
6399 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006400 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6401 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006402 decorations.addNoContraction(builder, destVec);
6403 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006404 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006405 }
6406
6407 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006408 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006409 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006410 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006411}
6412
John Kessenichad7645f2018-06-04 19:11:25 -06006413// For converting integers where both the bitwidth and the signedness could
6414// change, but only do the width change here. The caller is still responsible
6415// for the signedness conversion.
6416spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006417{
John Kessenichad7645f2018-06-04 19:11:25 -06006418 // Get the result type width, based on the type to convert to.
6419 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006420 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006421 case glslang::EOpConvInt16ToUint8:
6422 case glslang::EOpConvIntToUint8:
6423 case glslang::EOpConvInt64ToUint8:
6424 case glslang::EOpConvUint16ToInt8:
6425 case glslang::EOpConvUintToInt8:
6426 case glslang::EOpConvUint64ToInt8:
6427 width = 8;
6428 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006429 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006430 case glslang::EOpConvIntToUint16:
6431 case glslang::EOpConvInt64ToUint16:
6432 case glslang::EOpConvUint8ToInt16:
6433 case glslang::EOpConvUintToInt16:
6434 case glslang::EOpConvUint64ToInt16:
6435 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006436 break;
6437 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006438 case glslang::EOpConvInt16ToUint:
6439 case glslang::EOpConvInt64ToUint:
6440 case glslang::EOpConvUint8ToInt:
6441 case glslang::EOpConvUint16ToInt:
6442 case glslang::EOpConvUint64ToInt:
6443 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006444 break;
6445 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006446 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006447 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006448 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006449 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006450 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006451 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006452 break;
6453
6454 default:
6455 assert(false && "Default missing");
6456 break;
6457 }
6458
John Kessenichad7645f2018-06-04 19:11:25 -06006459 // Get the conversion operation and result type,
6460 // based on the target width, but the source type.
6461 spv::Id type = spv::NoType;
6462 spv::Op convOp = spv::OpNop;
6463 switch(op) {
6464 case glslang::EOpConvInt8ToUint16:
6465 case glslang::EOpConvInt8ToUint:
6466 case glslang::EOpConvInt8ToUint64:
6467 case glslang::EOpConvInt16ToUint8:
6468 case glslang::EOpConvInt16ToUint:
6469 case glslang::EOpConvInt16ToUint64:
6470 case glslang::EOpConvIntToUint8:
6471 case glslang::EOpConvIntToUint16:
6472 case glslang::EOpConvIntToUint64:
6473 case glslang::EOpConvInt64ToUint8:
6474 case glslang::EOpConvInt64ToUint16:
6475 case glslang::EOpConvInt64ToUint:
6476 convOp = spv::OpSConvert;
6477 type = builder.makeIntType(width);
6478 break;
6479 default:
6480 convOp = spv::OpUConvert;
6481 type = builder.makeUintType(width);
6482 break;
6483 }
6484
John Kessenich66011cb2018-03-06 16:12:04 -07006485 if (vectorSize > 0)
6486 type = builder.makeVectorType(type, vectorSize);
6487
John Kessenichad7645f2018-06-04 19:11:25 -06006488 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006489}
6490
John Kessenichead86222018-03-28 18:01:20 -06006491spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6492 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006493{
6494 spv::Op convOp = spv::OpNop;
6495 spv::Id zero = 0;
6496 spv::Id one = 0;
6497
6498 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6499
6500 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006501 case glslang::EOpConvIntToBool:
6502 case glslang::EOpConvUintToBool:
6503 zero = builder.makeUintConstant(0);
6504 zero = makeSmearedConstant(zero, vectorSize);
6505 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006506 case glslang::EOpConvFloatToBool:
6507 zero = builder.makeFloatConstant(0.0F);
6508 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006509 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006510 case glslang::EOpConvBoolToFloat:
6511 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006512 zero = builder.makeFloatConstant(0.0F);
6513 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006514 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006515
John Kessenich140f3df2015-06-26 16:58:36 -06006516 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006517 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006518#ifndef GLSLANG_WEB
6519 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006520 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006521 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006522 } else
6523#endif
6524 {
6525 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006526 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006527 }
Rex Xucabbb782017-03-24 13:41:14 +08006528
John Kessenich140f3df2015-06-26 16:58:36 -06006529 convOp = spv::OpSelect;
6530 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006531
John Kessenich140f3df2015-06-26 16:58:36 -06006532 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006533 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006534#ifndef GLSLANG_WEB
6535 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006536 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006537 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006538 } else
6539#endif
6540 {
6541 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006542 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006543 }
Rex Xucabbb782017-03-24 13:41:14 +08006544
John Kessenich140f3df2015-06-26 16:58:36 -06006545 convOp = spv::OpSelect;
6546 break;
6547
John Kessenich66011cb2018-03-06 16:12:04 -07006548 case glslang::EOpConvInt8ToFloat16:
6549 case glslang::EOpConvInt8ToFloat:
6550 case glslang::EOpConvInt8ToDouble:
6551 case glslang::EOpConvInt16ToFloat16:
6552 case glslang::EOpConvInt16ToFloat:
6553 case glslang::EOpConvInt16ToDouble:
6554 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006555 case glslang::EOpConvIntToFloat:
6556 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006557 case glslang::EOpConvInt64ToFloat:
6558 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006559 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006560 convOp = spv::OpConvertSToF;
6561 break;
6562
John Kessenich66011cb2018-03-06 16:12:04 -07006563 case glslang::EOpConvUint8ToFloat16:
6564 case glslang::EOpConvUint8ToFloat:
6565 case glslang::EOpConvUint8ToDouble:
6566 case glslang::EOpConvUint16ToFloat16:
6567 case glslang::EOpConvUint16ToFloat:
6568 case glslang::EOpConvUint16ToDouble:
6569 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006570 case glslang::EOpConvUintToFloat:
6571 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006572 case glslang::EOpConvUint64ToFloat:
6573 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006574 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006575 convOp = spv::OpConvertUToF;
6576 break;
6577
John Kessenich66011cb2018-03-06 16:12:04 -07006578 case glslang::EOpConvFloat16ToInt8:
6579 case glslang::EOpConvFloatToInt8:
6580 case glslang::EOpConvDoubleToInt8:
6581 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006582 case glslang::EOpConvFloatToInt16:
6583 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006584 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006585 case glslang::EOpConvFloatToInt:
6586 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006587 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006588 case glslang::EOpConvFloatToInt64:
6589 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006590 convOp = spv::OpConvertFToS;
6591 break;
6592
John Kessenich66011cb2018-03-06 16:12:04 -07006593 case glslang::EOpConvUint8ToInt8:
6594 case glslang::EOpConvInt8ToUint8:
6595 case glslang::EOpConvUint16ToInt16:
6596 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006597 case glslang::EOpConvUintToInt:
6598 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006599 case glslang::EOpConvUint64ToInt64:
6600 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006601 if (builder.isInSpecConstCodeGenMode()) {
6602 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006603#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006604 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6605 zero = builder.makeUint8Constant(0);
6606 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006607 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006608 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6609 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006610 } else
6611#endif
6612 {
Rex Xucabbb782017-03-24 13:41:14 +08006613 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006614 }
qining189b2032016-04-12 23:16:20 -04006615 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006616 // Use OpIAdd, instead of OpBitcast to do the conversion when
6617 // generating for OpSpecConstantOp instruction.
6618 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6619 }
6620 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006621 convOp = spv::OpBitcast;
6622 break;
6623
John Kessenich66011cb2018-03-06 16:12:04 -07006624 case glslang::EOpConvFloat16ToUint8:
6625 case glslang::EOpConvFloatToUint8:
6626 case glslang::EOpConvDoubleToUint8:
6627 case glslang::EOpConvFloat16ToUint16:
6628 case glslang::EOpConvFloatToUint16:
6629 case glslang::EOpConvDoubleToUint16:
6630 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006631 case glslang::EOpConvFloatToUint:
6632 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006633 case glslang::EOpConvFloatToUint64:
6634 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006635 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006636 convOp = spv::OpConvertFToU;
6637 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006638
John Kessenich39697cd2019-08-08 10:35:51 -06006639#ifndef GLSLANG_WEB
6640 case glslang::EOpConvInt8ToBool:
6641 case glslang::EOpConvUint8ToBool:
6642 zero = builder.makeUint8Constant(0);
6643 zero = makeSmearedConstant(zero, vectorSize);
6644 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6645 case glslang::EOpConvInt16ToBool:
6646 case glslang::EOpConvUint16ToBool:
6647 zero = builder.makeUint16Constant(0);
6648 zero = makeSmearedConstant(zero, vectorSize);
6649 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6650 case glslang::EOpConvInt64ToBool:
6651 case glslang::EOpConvUint64ToBool:
6652 zero = builder.makeUint64Constant(0);
6653 zero = makeSmearedConstant(zero, vectorSize);
6654 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6655 case glslang::EOpConvDoubleToBool:
6656 zero = builder.makeDoubleConstant(0.0);
6657 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006658 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006659 case glslang::EOpConvFloat16ToBool:
6660 zero = builder.makeFloat16Constant(0.0F);
6661 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006662 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006663 case glslang::EOpConvBoolToDouble:
6664 convOp = spv::OpSelect;
6665 zero = builder.makeDoubleConstant(0.0);
6666 one = builder.makeDoubleConstant(1.0);
6667 break;
6668 case glslang::EOpConvBoolToFloat16:
6669 convOp = spv::OpSelect;
6670 zero = builder.makeFloat16Constant(0.0F);
6671 one = builder.makeFloat16Constant(1.0F);
6672 break;
6673 case glslang::EOpConvBoolToInt8:
6674 zero = builder.makeInt8Constant(0);
6675 one = builder.makeInt8Constant(1);
6676 convOp = spv::OpSelect;
6677 break;
6678 case glslang::EOpConvBoolToUint8:
6679 zero = builder.makeUint8Constant(0);
6680 one = builder.makeUint8Constant(1);
6681 convOp = spv::OpSelect;
6682 break;
6683 case glslang::EOpConvBoolToInt16:
6684 zero = builder.makeInt16Constant(0);
6685 one = builder.makeInt16Constant(1);
6686 convOp = spv::OpSelect;
6687 break;
6688 case glslang::EOpConvBoolToUint16:
6689 zero = builder.makeUint16Constant(0);
6690 one = builder.makeUint16Constant(1);
6691 convOp = spv::OpSelect;
6692 break;
6693 case glslang::EOpConvDoubleToFloat:
6694 case glslang::EOpConvFloatToDouble:
6695 case glslang::EOpConvDoubleToFloat16:
6696 case glslang::EOpConvFloat16ToDouble:
6697 case glslang::EOpConvFloatToFloat16:
6698 case glslang::EOpConvFloat16ToFloat:
6699 convOp = spv::OpFConvert;
6700 if (builder.isMatrixType(destType))
6701 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6702 break;
6703
John Kessenich66011cb2018-03-06 16:12:04 -07006704 case glslang::EOpConvInt8ToInt16:
6705 case glslang::EOpConvInt8ToInt:
6706 case glslang::EOpConvInt8ToInt64:
6707 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006708 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006709 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006710 case glslang::EOpConvIntToInt8:
6711 case glslang::EOpConvIntToInt16:
6712 case glslang::EOpConvIntToInt64:
6713 case glslang::EOpConvInt64ToInt8:
6714 case glslang::EOpConvInt64ToInt16:
6715 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006716 convOp = spv::OpSConvert;
6717 break;
6718
John Kessenich66011cb2018-03-06 16:12:04 -07006719 case glslang::EOpConvUint8ToUint16:
6720 case glslang::EOpConvUint8ToUint:
6721 case glslang::EOpConvUint8ToUint64:
6722 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006723 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006724 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006725 case glslang::EOpConvUintToUint8:
6726 case glslang::EOpConvUintToUint16:
6727 case glslang::EOpConvUintToUint64:
6728 case glslang::EOpConvUint64ToUint8:
6729 case glslang::EOpConvUint64ToUint16:
6730 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006731 convOp = spv::OpUConvert;
6732 break;
6733
John Kessenich66011cb2018-03-06 16:12:04 -07006734 case glslang::EOpConvInt8ToUint16:
6735 case glslang::EOpConvInt8ToUint:
6736 case glslang::EOpConvInt8ToUint64:
6737 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006738 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006739 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006740 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006741 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006742 case glslang::EOpConvIntToUint64:
6743 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006744 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006745 case glslang::EOpConvInt64ToUint:
6746 case glslang::EOpConvUint8ToInt16:
6747 case glslang::EOpConvUint8ToInt:
6748 case glslang::EOpConvUint8ToInt64:
6749 case glslang::EOpConvUint16ToInt8:
6750 case glslang::EOpConvUint16ToInt:
6751 case glslang::EOpConvUint16ToInt64:
6752 case glslang::EOpConvUintToInt8:
6753 case glslang::EOpConvUintToInt16:
6754 case glslang::EOpConvUintToInt64:
6755 case glslang::EOpConvUint64ToInt8:
6756 case glslang::EOpConvUint64ToInt16:
6757 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006758 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006759 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006760
6761 if (builder.isInSpecConstCodeGenMode()) {
6762 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006763 switch(op) {
6764 case glslang::EOpConvInt16ToUint8:
6765 case glslang::EOpConvIntToUint8:
6766 case glslang::EOpConvInt64ToUint8:
6767 case glslang::EOpConvUint16ToInt8:
6768 case glslang::EOpConvUintToInt8:
6769 case glslang::EOpConvUint64ToInt8:
6770 zero = builder.makeUint8Constant(0);
6771 break;
6772 case glslang::EOpConvInt8ToUint16:
6773 case glslang::EOpConvIntToUint16:
6774 case glslang::EOpConvInt64ToUint16:
6775 case glslang::EOpConvUint8ToInt16:
6776 case glslang::EOpConvUintToInt16:
6777 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006778 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006779 break;
6780 case glslang::EOpConvInt8ToUint:
6781 case glslang::EOpConvInt16ToUint:
6782 case glslang::EOpConvInt64ToUint:
6783 case glslang::EOpConvUint8ToInt:
6784 case glslang::EOpConvUint16ToInt:
6785 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006786 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006787 break;
6788 case glslang::EOpConvInt8ToUint64:
6789 case glslang::EOpConvInt16ToUint64:
6790 case glslang::EOpConvIntToUint64:
6791 case glslang::EOpConvUint8ToInt64:
6792 case glslang::EOpConvUint16ToInt64:
6793 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006794 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006795 break;
6796 default:
6797 assert(false && "Default missing");
6798 break;
6799 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006800 zero = makeSmearedConstant(zero, vectorSize);
6801 // Use OpIAdd, instead of OpBitcast to do the conversion when
6802 // generating for OpSpecConstantOp instruction.
6803 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6804 }
6805 // For normal run-time conversion instruction, use OpBitcast.
6806 convOp = spv::OpBitcast;
6807 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006808 case glslang::EOpConvUint64ToPtr:
6809 convOp = spv::OpConvertUToPtr;
6810 break;
6811 case glslang::EOpConvPtrToUint64:
6812 convOp = spv::OpConvertPtrToU;
6813 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006814 case glslang::EOpConvPtrToUvec2:
6815 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006816 if (builder.isVector(operand))
6817 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6818 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006819 convOp = spv::OpBitcast;
6820 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006821#endif
6822
John Kessenich140f3df2015-06-26 16:58:36 -06006823 default:
6824 break;
6825 }
6826
6827 spv::Id result = 0;
6828 if (convOp == spv::OpNop)
6829 return result;
6830
6831 if (convOp == spv::OpSelect) {
6832 zero = makeSmearedConstant(zero, vectorSize);
6833 one = makeSmearedConstant(one, vectorSize);
6834 result = builder.createTriOp(convOp, destType, operand, one, zero);
6835 } else
6836 result = builder.createUnaryOp(convOp, destType, operand);
6837
John Kessenichead86222018-03-28 18:01:20 -06006838 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006839 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006840 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006841}
6842
6843spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6844{
6845 if (vectorSize == 0)
6846 return constant;
6847
6848 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6849 std::vector<spv::Id> components;
6850 for (int c = 0; c < vectorSize; ++c)
6851 components.push_back(constant);
6852 return builder.makeCompositeConstant(vectorTypeId, components);
6853}
6854
John Kessenich426394d2015-07-23 10:22:48 -06006855// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006856spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6857 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6858 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006859{
6860 spv::Op opCode = spv::OpNop;
6861
6862 switch (op) {
6863 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006864 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006865 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006866 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006867 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6868 opCode = spv::OpAtomicFAddEXT;
6869 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6870 if (typeProxy == glslang::EbtFloat)
6871 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6872 else
6873 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6874 }
John Kessenich426394d2015-07-23 10:22:48 -06006875 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006876 case glslang::EOpAtomicCounterSubtract:
6877 opCode = spv::OpAtomicISub;
6878 break;
John Kessenich426394d2015-07-23 10:22:48 -06006879 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006880 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006881 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006882 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6883 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006884 break;
6885 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006886 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006887 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006888 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6889 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006890 break;
6891 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006892 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006893 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006894 opCode = spv::OpAtomicAnd;
6895 break;
6896 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006897 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006898 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006899 opCode = spv::OpAtomicOr;
6900 break;
6901 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006902 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006903 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006904 opCode = spv::OpAtomicXor;
6905 break;
6906 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006907 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006908 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006909 opCode = spv::OpAtomicExchange;
6910 break;
6911 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006912 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006913 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006914 opCode = spv::OpAtomicCompareExchange;
6915 break;
6916 case glslang::EOpAtomicCounterIncrement:
6917 opCode = spv::OpAtomicIIncrement;
6918 break;
6919 case glslang::EOpAtomicCounterDecrement:
6920 opCode = spv::OpAtomicIDecrement;
6921 break;
6922 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006923 case glslang::EOpImageAtomicLoad:
6924 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006925 opCode = spv::OpAtomicLoad;
6926 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006927 case glslang::EOpAtomicStore:
6928 case glslang::EOpImageAtomicStore:
6929 opCode = spv::OpAtomicStore;
6930 break;
John Kessenich426394d2015-07-23 10:22:48 -06006931 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006932 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006933 break;
6934 }
6935
Rex Xue8fe8b02017-09-26 15:42:56 +08006936 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6937 builder.addCapability(spv::CapabilityInt64Atomics);
6938
John Kessenich426394d2015-07-23 10:22:48 -06006939 // Sort out the operands
6940 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006941 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006942 // - compare-exchange swaps the value and comparator
6943 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006944 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006945 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6946 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6947 spv::Id scopeId;
6948 if (glslangIntermediate->usingVulkanMemoryModel()) {
6949 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6950 } else {
6951 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6952 }
6953 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006954 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6955 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006956 spv::MemorySemanticsVolatileMask :
6957 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006958 spv::Id semanticsId2 = semanticsId;
6959
6960 pointerId = operands[0];
6961 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6962 // no additional operands
6963 } else if (opCode == spv::OpAtomicCompareExchange) {
6964 compareId = operands[1];
6965 valueId = operands[2];
6966 if (operands.size() > 3) {
6967 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006968 semanticsId = builder.makeUintConstant(
6969 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6970 semanticsId2 = builder.makeUintConstant(
6971 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006972 }
6973 } else if (opCode == spv::OpAtomicLoad) {
6974 if (operands.size() > 1) {
6975 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006976 semanticsId = builder.makeUintConstant(
6977 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006978 }
6979 } else {
6980 // atomic store or RMW
6981 valueId = operands[1];
6982 if (operands.size() > 2) {
6983 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006984 semanticsId = builder.makeUintConstant
6985 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006986 }
Rex Xu04db3f52015-09-16 11:44:02 +08006987 }
John Kessenich426394d2015-07-23 10:22:48 -06006988
Jeff Bolz36831c92018-09-05 10:11:41 -05006989 // Check for capabilities
6990 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006991 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6992 spv::MemorySemanticsMakeVisibleKHRMask |
6993 spv::MemorySemanticsOutputMemoryKHRMask |
6994 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006995 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6996 }
John Kessenich426394d2015-07-23 10:22:48 -06006997
Jeff Bolz36831c92018-09-05 10:11:41 -05006998 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6999 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7000 }
John Kessenich48d6e792017-10-06 21:21:48 -06007001
Jeff Bolz36831c92018-09-05 10:11:41 -05007002 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
7003 spvAtomicOperands.push_back(pointerId);
7004 spvAtomicOperands.push_back(scopeId);
7005 spvAtomicOperands.push_back(semanticsId);
7006 if (opCode == spv::OpAtomicCompareExchange) {
7007 spvAtomicOperands.push_back(semanticsId2);
7008 spvAtomicOperands.push_back(valueId);
7009 spvAtomicOperands.push_back(compareId);
7010 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
7011 spvAtomicOperands.push_back(valueId);
7012 }
John Kessenich48d6e792017-10-06 21:21:48 -06007013
Jeff Bolz36831c92018-09-05 10:11:41 -05007014 if (opCode == spv::OpAtomicStore) {
7015 builder.createNoResultOp(opCode, spvAtomicOperands);
7016 return 0;
7017 } else {
7018 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
7019
7020 // GLSL and HLSL atomic-counter decrement return post-decrement value,
7021 // while SPIR-V returns pre-decrement value. Translate between these semantics.
7022 if (op == glslang::EOpAtomicCounterDecrement)
7023 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
7024
7025 return resultId;
7026 }
John Kessenich426394d2015-07-23 10:22:48 -06007027}
7028
John Kessenich91cef522016-05-05 16:45:40 -06007029// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07007030spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
7031 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06007032{
John Kessenich66011cb2018-03-06 16:12:04 -07007033 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7034 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08007035
Rex Xu51596642016-09-21 18:56:12 +08007036 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06007037 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08007038 spv::GroupOperation groupOperation = spv::GroupOperationMax;
7039
chaocf200da82016-12-20 12:44:35 -08007040 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
7041 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08007042 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
7043 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007044 } else if (op == glslang::EOpAnyInvocation ||
7045 op == glslang::EOpAllInvocations ||
7046 op == glslang::EOpAllInvocationsEqual) {
7047 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
7048 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08007049 } else {
7050 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08007051 if (op == glslang::EOpMinInvocationsNonUniform ||
7052 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08007053 op == glslang::EOpAddInvocationsNonUniform ||
7054 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7055 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7056 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
7057 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
7058 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
7059 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08007060 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08007061
Rex Xu430ef402016-10-14 17:22:23 +08007062 switch (op) {
7063 case glslang::EOpMinInvocations:
7064 case glslang::EOpMaxInvocations:
7065 case glslang::EOpAddInvocations:
7066 case glslang::EOpMinInvocationsNonUniform:
7067 case glslang::EOpMaxInvocationsNonUniform:
7068 case glslang::EOpAddInvocationsNonUniform:
7069 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08007070 break;
7071 case glslang::EOpMinInvocationsInclusiveScan:
7072 case glslang::EOpMaxInvocationsInclusiveScan:
7073 case glslang::EOpAddInvocationsInclusiveScan:
7074 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7075 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7076 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7077 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007078 break;
7079 case glslang::EOpMinInvocationsExclusiveScan:
7080 case glslang::EOpMaxInvocationsExclusiveScan:
7081 case glslang::EOpAddInvocationsExclusiveScan:
7082 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7083 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7084 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7085 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007086 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07007087 default:
7088 break;
Rex Xu430ef402016-10-14 17:22:23 +08007089 }
John Kessenich149afc32018-08-14 13:31:43 -06007090 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7091 spvGroupOperands.push_back(scope);
7092 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007093 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007094 spvGroupOperands.push_back(groupOp);
7095 }
Rex Xu51596642016-09-21 18:56:12 +08007096 }
7097
John Kessenich149afc32018-08-14 13:31:43 -06007098 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
7099 spv::IdImmediate op = { true, *opIt };
7100 spvGroupOperands.push_back(op);
7101 }
John Kessenich91cef522016-05-05 16:45:40 -06007102
7103 switch (op) {
7104 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007105 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08007106 break;
John Kessenich91cef522016-05-05 16:45:40 -06007107 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007108 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08007109 break;
John Kessenich91cef522016-05-05 16:45:40 -06007110 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007111 opCode = spv::OpSubgroupAllEqualKHR;
7112 break;
Rex Xu51596642016-09-21 18:56:12 +08007113 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08007114 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08007115 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007116 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007117 break;
7118 case glslang::EOpReadFirstInvocation:
7119 opCode = spv::OpSubgroupFirstInvocationKHR;
7120 break;
7121 case glslang::EOpBallot:
7122 {
7123 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
7124 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
7125 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
7126 //
7127 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
7128 //
7129 spv::Id uintType = builder.makeUintType(32);
7130 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
7131 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
7132
7133 std::vector<spv::Id> components;
7134 components.push_back(builder.createCompositeExtract(result, uintType, 0));
7135 components.push_back(builder.createCompositeExtract(result, uintType, 1));
7136
7137 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
7138 return builder.createUnaryOp(spv::OpBitcast, typeId,
7139 builder.createCompositeConstruct(uvec2Type, components));
7140 }
7141
Rex Xu9d93a232016-05-05 12:30:44 +08007142 case glslang::EOpMinInvocations:
7143 case glslang::EOpMaxInvocations:
7144 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007145 case glslang::EOpMinInvocationsInclusiveScan:
7146 case glslang::EOpMaxInvocationsInclusiveScan:
7147 case glslang::EOpAddInvocationsInclusiveScan:
7148 case glslang::EOpMinInvocationsExclusiveScan:
7149 case glslang::EOpMaxInvocationsExclusiveScan:
7150 case glslang::EOpAddInvocationsExclusiveScan:
7151 if (op == glslang::EOpMinInvocations ||
7152 op == glslang::EOpMinInvocationsInclusiveScan ||
7153 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007154 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007155 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007156 else {
7157 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007158 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007159 else
Rex Xu51596642016-09-21 18:56:12 +08007160 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007161 }
Rex Xu430ef402016-10-14 17:22:23 +08007162 } else if (op == glslang::EOpMaxInvocations ||
7163 op == glslang::EOpMaxInvocationsInclusiveScan ||
7164 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007165 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007166 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007167 else {
7168 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007169 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007170 else
Rex Xu51596642016-09-21 18:56:12 +08007171 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007172 }
7173 } else {
7174 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007175 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007176 else
Rex Xu51596642016-09-21 18:56:12 +08007177 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007178 }
7179
Rex Xu2bbbe062016-08-23 15:41:05 +08007180 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007181 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007182
7183 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007184 case glslang::EOpMinInvocationsNonUniform:
7185 case glslang::EOpMaxInvocationsNonUniform:
7186 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007187 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7188 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7189 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7190 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7191 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7192 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7193 if (op == glslang::EOpMinInvocationsNonUniform ||
7194 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7195 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007196 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007197 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007198 else {
7199 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007200 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007201 else
Rex Xu51596642016-09-21 18:56:12 +08007202 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007203 }
7204 }
Rex Xu430ef402016-10-14 17:22:23 +08007205 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7206 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7207 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007208 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007209 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007210 else {
7211 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007212 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007213 else
Rex Xu51596642016-09-21 18:56:12 +08007214 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007215 }
7216 }
7217 else {
7218 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007219 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007220 else
Rex Xu51596642016-09-21 18:56:12 +08007221 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007222 }
7223
Rex Xu2bbbe062016-08-23 15:41:05 +08007224 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007225 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007226
7227 break;
John Kessenich91cef522016-05-05 16:45:40 -06007228 default:
7229 logger->missingFunctionality("invocation operation");
7230 return spv::NoResult;
7231 }
Rex Xu51596642016-09-21 18:56:12 +08007232
7233 assert(opCode != spv::OpNop);
7234 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007235}
7236
Rex Xu2bbbe062016-08-23 15:41:05 +08007237// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007238spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7239 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007240{
7241 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7242 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007243 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007244 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007245 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7246 op == spv::OpGroupSMinNonUniformAMD ||
7247 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7248 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007249 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7250
7251 // Handle group invocation operations scalar by scalar.
7252 // The result type is the same type as the original type.
7253 // The algorithm is to:
7254 // - break the vector into scalars
7255 // - apply the operation to each scalar
7256 // - make a vector out the scalar results
7257
7258 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007259 int numComponents = builder.getNumComponents(operands[0]);
7260 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007261 std::vector<spv::Id> results;
7262
7263 // do each scalar op
7264 for (int comp = 0; comp < numComponents; ++comp) {
7265 std::vector<unsigned int> indexes;
7266 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007267 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7268 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007269 if (op == spv::OpSubgroupReadInvocationKHR) {
7270 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007271 spv::IdImmediate operand = { true, operands[1] };
7272 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007273 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007274 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7275 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007276 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007277 spv::IdImmediate operand = { true, operands[1] };
7278 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007279 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007280 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7281 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007282 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007283 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007284 spvGroupOperands.push_back(scalar);
7285 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007286
Rex Xub7072052016-09-26 15:53:40 +08007287 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007288 }
7289
7290 // put the pieces together
7291 return builder.createCompositeConstruct(typeId, results);
7292}
Rex Xu2bbbe062016-08-23 15:41:05 +08007293
John Kessenich66011cb2018-03-06 16:12:04 -07007294// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007295spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7296 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007297{
7298 // Add the required capabilities.
7299 switch (op) {
7300 case glslang::EOpSubgroupElect:
7301 builder.addCapability(spv::CapabilityGroupNonUniform);
7302 break;
7303 case glslang::EOpSubgroupAll:
7304 case glslang::EOpSubgroupAny:
7305 case glslang::EOpSubgroupAllEqual:
7306 builder.addCapability(spv::CapabilityGroupNonUniform);
7307 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7308 break;
7309 case glslang::EOpSubgroupBroadcast:
7310 case glslang::EOpSubgroupBroadcastFirst:
7311 case glslang::EOpSubgroupBallot:
7312 case glslang::EOpSubgroupInverseBallot:
7313 case glslang::EOpSubgroupBallotBitExtract:
7314 case glslang::EOpSubgroupBallotBitCount:
7315 case glslang::EOpSubgroupBallotInclusiveBitCount:
7316 case glslang::EOpSubgroupBallotExclusiveBitCount:
7317 case glslang::EOpSubgroupBallotFindLSB:
7318 case glslang::EOpSubgroupBallotFindMSB:
7319 builder.addCapability(spv::CapabilityGroupNonUniform);
7320 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7321 break;
7322 case glslang::EOpSubgroupShuffle:
7323 case glslang::EOpSubgroupShuffleXor:
7324 builder.addCapability(spv::CapabilityGroupNonUniform);
7325 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7326 break;
7327 case glslang::EOpSubgroupShuffleUp:
7328 case glslang::EOpSubgroupShuffleDown:
7329 builder.addCapability(spv::CapabilityGroupNonUniform);
7330 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7331 break;
7332 case glslang::EOpSubgroupAdd:
7333 case glslang::EOpSubgroupMul:
7334 case glslang::EOpSubgroupMin:
7335 case glslang::EOpSubgroupMax:
7336 case glslang::EOpSubgroupAnd:
7337 case glslang::EOpSubgroupOr:
7338 case glslang::EOpSubgroupXor:
7339 case glslang::EOpSubgroupInclusiveAdd:
7340 case glslang::EOpSubgroupInclusiveMul:
7341 case glslang::EOpSubgroupInclusiveMin:
7342 case glslang::EOpSubgroupInclusiveMax:
7343 case glslang::EOpSubgroupInclusiveAnd:
7344 case glslang::EOpSubgroupInclusiveOr:
7345 case glslang::EOpSubgroupInclusiveXor:
7346 case glslang::EOpSubgroupExclusiveAdd:
7347 case glslang::EOpSubgroupExclusiveMul:
7348 case glslang::EOpSubgroupExclusiveMin:
7349 case glslang::EOpSubgroupExclusiveMax:
7350 case glslang::EOpSubgroupExclusiveAnd:
7351 case glslang::EOpSubgroupExclusiveOr:
7352 case glslang::EOpSubgroupExclusiveXor:
7353 builder.addCapability(spv::CapabilityGroupNonUniform);
7354 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7355 break;
7356 case glslang::EOpSubgroupClusteredAdd:
7357 case glslang::EOpSubgroupClusteredMul:
7358 case glslang::EOpSubgroupClusteredMin:
7359 case glslang::EOpSubgroupClusteredMax:
7360 case glslang::EOpSubgroupClusteredAnd:
7361 case glslang::EOpSubgroupClusteredOr:
7362 case glslang::EOpSubgroupClusteredXor:
7363 builder.addCapability(spv::CapabilityGroupNonUniform);
7364 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7365 break;
7366 case glslang::EOpSubgroupQuadBroadcast:
7367 case glslang::EOpSubgroupQuadSwapHorizontal:
7368 case glslang::EOpSubgroupQuadSwapVertical:
7369 case glslang::EOpSubgroupQuadSwapDiagonal:
7370 builder.addCapability(spv::CapabilityGroupNonUniform);
7371 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7372 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007373 case glslang::EOpSubgroupPartitionedAdd:
7374 case glslang::EOpSubgroupPartitionedMul:
7375 case glslang::EOpSubgroupPartitionedMin:
7376 case glslang::EOpSubgroupPartitionedMax:
7377 case glslang::EOpSubgroupPartitionedAnd:
7378 case glslang::EOpSubgroupPartitionedOr:
7379 case glslang::EOpSubgroupPartitionedXor:
7380 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7381 case glslang::EOpSubgroupPartitionedInclusiveMul:
7382 case glslang::EOpSubgroupPartitionedInclusiveMin:
7383 case glslang::EOpSubgroupPartitionedInclusiveMax:
7384 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7385 case glslang::EOpSubgroupPartitionedInclusiveOr:
7386 case glslang::EOpSubgroupPartitionedInclusiveXor:
7387 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7388 case glslang::EOpSubgroupPartitionedExclusiveMul:
7389 case glslang::EOpSubgroupPartitionedExclusiveMin:
7390 case glslang::EOpSubgroupPartitionedExclusiveMax:
7391 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7392 case glslang::EOpSubgroupPartitionedExclusiveOr:
7393 case glslang::EOpSubgroupPartitionedExclusiveXor:
7394 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7395 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7396 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007397 default: assert(0 && "Unhandled subgroup operation!");
7398 }
7399
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007400
7401 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7402 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007403 const bool isBool = typeProxy == glslang::EbtBool;
7404
7405 spv::Op opCode = spv::OpNop;
7406
7407 // Figure out which opcode to use.
7408 switch (op) {
7409 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7410 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7411 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7412 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7413 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7414 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7415 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7416 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7417 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7418 case glslang::EOpSubgroupBallotBitCount:
7419 case glslang::EOpSubgroupBallotInclusiveBitCount:
7420 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7421 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7422 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7423 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7424 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7425 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7426 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7427 case glslang::EOpSubgroupAdd:
7428 case glslang::EOpSubgroupInclusiveAdd:
7429 case glslang::EOpSubgroupExclusiveAdd:
7430 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007431 case glslang::EOpSubgroupPartitionedAdd:
7432 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7433 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007434 if (isFloat) {
7435 opCode = spv::OpGroupNonUniformFAdd;
7436 } else {
7437 opCode = spv::OpGroupNonUniformIAdd;
7438 }
7439 break;
7440 case glslang::EOpSubgroupMul:
7441 case glslang::EOpSubgroupInclusiveMul:
7442 case glslang::EOpSubgroupExclusiveMul:
7443 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007444 case glslang::EOpSubgroupPartitionedMul:
7445 case glslang::EOpSubgroupPartitionedInclusiveMul:
7446 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007447 if (isFloat) {
7448 opCode = spv::OpGroupNonUniformFMul;
7449 } else {
7450 opCode = spv::OpGroupNonUniformIMul;
7451 }
7452 break;
7453 case glslang::EOpSubgroupMin:
7454 case glslang::EOpSubgroupInclusiveMin:
7455 case glslang::EOpSubgroupExclusiveMin:
7456 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007457 case glslang::EOpSubgroupPartitionedMin:
7458 case glslang::EOpSubgroupPartitionedInclusiveMin:
7459 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007460 if (isFloat) {
7461 opCode = spv::OpGroupNonUniformFMin;
7462 } else if (isUnsigned) {
7463 opCode = spv::OpGroupNonUniformUMin;
7464 } else {
7465 opCode = spv::OpGroupNonUniformSMin;
7466 }
7467 break;
7468 case glslang::EOpSubgroupMax:
7469 case glslang::EOpSubgroupInclusiveMax:
7470 case glslang::EOpSubgroupExclusiveMax:
7471 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007472 case glslang::EOpSubgroupPartitionedMax:
7473 case glslang::EOpSubgroupPartitionedInclusiveMax:
7474 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007475 if (isFloat) {
7476 opCode = spv::OpGroupNonUniformFMax;
7477 } else if (isUnsigned) {
7478 opCode = spv::OpGroupNonUniformUMax;
7479 } else {
7480 opCode = spv::OpGroupNonUniformSMax;
7481 }
7482 break;
7483 case glslang::EOpSubgroupAnd:
7484 case glslang::EOpSubgroupInclusiveAnd:
7485 case glslang::EOpSubgroupExclusiveAnd:
7486 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007487 case glslang::EOpSubgroupPartitionedAnd:
7488 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7489 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007490 if (isBool) {
7491 opCode = spv::OpGroupNonUniformLogicalAnd;
7492 } else {
7493 opCode = spv::OpGroupNonUniformBitwiseAnd;
7494 }
7495 break;
7496 case glslang::EOpSubgroupOr:
7497 case glslang::EOpSubgroupInclusiveOr:
7498 case glslang::EOpSubgroupExclusiveOr:
7499 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007500 case glslang::EOpSubgroupPartitionedOr:
7501 case glslang::EOpSubgroupPartitionedInclusiveOr:
7502 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007503 if (isBool) {
7504 opCode = spv::OpGroupNonUniformLogicalOr;
7505 } else {
7506 opCode = spv::OpGroupNonUniformBitwiseOr;
7507 }
7508 break;
7509 case glslang::EOpSubgroupXor:
7510 case glslang::EOpSubgroupInclusiveXor:
7511 case glslang::EOpSubgroupExclusiveXor:
7512 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007513 case glslang::EOpSubgroupPartitionedXor:
7514 case glslang::EOpSubgroupPartitionedInclusiveXor:
7515 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007516 if (isBool) {
7517 opCode = spv::OpGroupNonUniformLogicalXor;
7518 } else {
7519 opCode = spv::OpGroupNonUniformBitwiseXor;
7520 }
7521 break;
7522 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7523 case glslang::EOpSubgroupQuadSwapHorizontal:
7524 case glslang::EOpSubgroupQuadSwapVertical:
7525 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7526 default: assert(0 && "Unhandled subgroup operation!");
7527 }
7528
John Kessenich149afc32018-08-14 13:31:43 -06007529 // get the right Group Operation
7530 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007531 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007532 default:
7533 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007534 case glslang::EOpSubgroupBallotBitCount:
7535 case glslang::EOpSubgroupAdd:
7536 case glslang::EOpSubgroupMul:
7537 case glslang::EOpSubgroupMin:
7538 case glslang::EOpSubgroupMax:
7539 case glslang::EOpSubgroupAnd:
7540 case glslang::EOpSubgroupOr:
7541 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007542 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007543 break;
7544 case glslang::EOpSubgroupBallotInclusiveBitCount:
7545 case glslang::EOpSubgroupInclusiveAdd:
7546 case glslang::EOpSubgroupInclusiveMul:
7547 case glslang::EOpSubgroupInclusiveMin:
7548 case glslang::EOpSubgroupInclusiveMax:
7549 case glslang::EOpSubgroupInclusiveAnd:
7550 case glslang::EOpSubgroupInclusiveOr:
7551 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007552 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007553 break;
7554 case glslang::EOpSubgroupBallotExclusiveBitCount:
7555 case glslang::EOpSubgroupExclusiveAdd:
7556 case glslang::EOpSubgroupExclusiveMul:
7557 case glslang::EOpSubgroupExclusiveMin:
7558 case glslang::EOpSubgroupExclusiveMax:
7559 case glslang::EOpSubgroupExclusiveAnd:
7560 case glslang::EOpSubgroupExclusiveOr:
7561 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007562 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007563 break;
7564 case glslang::EOpSubgroupClusteredAdd:
7565 case glslang::EOpSubgroupClusteredMul:
7566 case glslang::EOpSubgroupClusteredMin:
7567 case glslang::EOpSubgroupClusteredMax:
7568 case glslang::EOpSubgroupClusteredAnd:
7569 case glslang::EOpSubgroupClusteredOr:
7570 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007571 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007572 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007573 case glslang::EOpSubgroupPartitionedAdd:
7574 case glslang::EOpSubgroupPartitionedMul:
7575 case glslang::EOpSubgroupPartitionedMin:
7576 case glslang::EOpSubgroupPartitionedMax:
7577 case glslang::EOpSubgroupPartitionedAnd:
7578 case glslang::EOpSubgroupPartitionedOr:
7579 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007580 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007581 break;
7582 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7583 case glslang::EOpSubgroupPartitionedInclusiveMul:
7584 case glslang::EOpSubgroupPartitionedInclusiveMin:
7585 case glslang::EOpSubgroupPartitionedInclusiveMax:
7586 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7587 case glslang::EOpSubgroupPartitionedInclusiveOr:
7588 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007589 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007590 break;
7591 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7592 case glslang::EOpSubgroupPartitionedExclusiveMul:
7593 case glslang::EOpSubgroupPartitionedExclusiveMin:
7594 case glslang::EOpSubgroupPartitionedExclusiveMax:
7595 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7596 case glslang::EOpSubgroupPartitionedExclusiveOr:
7597 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007598 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007599 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007600 }
7601
John Kessenich149afc32018-08-14 13:31:43 -06007602 // build the instruction
7603 std::vector<spv::IdImmediate> spvGroupOperands;
7604
7605 // Every operation begins with the Execution Scope operand.
7606 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7607 spvGroupOperands.push_back(executionScope);
7608
7609 // Next, for all operations that use a Group Operation, push that as an operand.
7610 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007611 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007612 spvGroupOperands.push_back(groupOperand);
7613 }
7614
John Kessenich66011cb2018-03-06 16:12:04 -07007615 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007616 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7617 spv::IdImmediate operand = { true, *opIt };
7618 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007619 }
7620
7621 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007622 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007623 switch (op) {
7624 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007625 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7626 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7627 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7628 }
7629 if (directionId != spv::NoResult) {
7630 spv::IdImmediate direction = { true, directionId };
7631 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007632 }
7633
7634 return builder.createOp(opCode, typeId, spvGroupOperands);
7635}
7636
John Kessenich8985fc92020-03-03 10:25:07 -07007637spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7638 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007639{
John Kessenich66011cb2018-03-06 16:12:04 -07007640 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7641 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007642
John Kessenich140f3df2015-06-26 16:58:36 -06007643 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007644 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007645 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007646 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007647 spv::Id typeId0 = 0;
7648 if (consumedOperands > 0)
7649 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007650 spv::Id typeId1 = 0;
7651 if (consumedOperands > 1)
7652 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007653 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007654
7655 switch (op) {
7656 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007657 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007658 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007659 else if (isUnsigned)
7660 libCall = spv::GLSLstd450UMin;
7661 else
7662 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007663 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007664 break;
7665 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007666 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007667 break;
7668 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007669 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007670 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007671 else if (isUnsigned)
7672 libCall = spv::GLSLstd450UMax;
7673 else
7674 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007675 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007676 break;
7677 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007678 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007679 break;
7680 case glslang::EOpDot:
7681 opCode = spv::OpDot;
7682 break;
7683 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007684 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007685 break;
7686
7687 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007688 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007689 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007690 else if (isUnsigned)
7691 libCall = spv::GLSLstd450UClamp;
7692 else
7693 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007694 builder.promoteScalar(precision, operands.front(), operands[1]);
7695 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007696 break;
7697 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007698 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7699 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007700 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007701 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007702 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007703 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007704 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007705 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007706 break;
7707 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007708 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007709 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007710 break;
7711 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007712 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007713 builder.promoteScalar(precision, operands[0], operands[2]);
7714 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007715 break;
7716
7717 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007718 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007719 break;
7720 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007721 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007722 break;
7723 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007724 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007725 break;
7726 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007727 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007728 break;
7729 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007730 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007731 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007732 case glslang::EOpBarrier:
7733 {
7734 // This is for the extended controlBarrier function, with four operands.
7735 // The unextended barrier() goes through createNoArgOperation.
7736 assert(operands.size() == 4);
7737 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7738 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7739 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007740 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7741 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007742 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7743 spv::MemorySemanticsMakeVisibleKHRMask |
7744 spv::MemorySemanticsOutputMemoryKHRMask |
7745 spv::MemorySemanticsVolatileMask)) {
7746 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7747 }
John Kessenich8985fc92020-03-03 10:25:07 -07007748 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7749 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007750 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7751 }
7752 return 0;
7753 }
7754 break;
7755 case glslang::EOpMemoryBarrier:
7756 {
7757 // This is for the extended memoryBarrier function, with three operands.
7758 // The unextended memoryBarrier() goes through createNoArgOperation.
7759 assert(operands.size() == 3);
7760 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7761 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7762 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7763 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7764 spv::MemorySemanticsMakeVisibleKHRMask |
7765 spv::MemorySemanticsOutputMemoryKHRMask |
7766 spv::MemorySemanticsVolatileMask)) {
7767 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7768 }
7769 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7770 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7771 }
7772 return 0;
7773 }
7774 break;
7775
John Kessenicha28f7a72019-08-06 07:00:58 -06007776#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007777 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007778 if (typeProxy == glslang::EbtFloat16)
7779 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007780 libCall = spv::GLSLstd450InterpolateAtSample;
7781 break;
7782 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007783 if (typeProxy == glslang::EbtFloat16)
7784 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007785 libCall = spv::GLSLstd450InterpolateAtOffset;
7786 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007787 case glslang::EOpAddCarry:
7788 opCode = spv::OpIAddCarry;
7789 typeId = builder.makeStructResultType(typeId0, typeId0);
7790 consumedOperands = 2;
7791 break;
7792 case glslang::EOpSubBorrow:
7793 opCode = spv::OpISubBorrow;
7794 typeId = builder.makeStructResultType(typeId0, typeId0);
7795 consumedOperands = 2;
7796 break;
7797 case glslang::EOpUMulExtended:
7798 opCode = spv::OpUMulExtended;
7799 typeId = builder.makeStructResultType(typeId0, typeId0);
7800 consumedOperands = 2;
7801 break;
7802 case glslang::EOpIMulExtended:
7803 opCode = spv::OpSMulExtended;
7804 typeId = builder.makeStructResultType(typeId0, typeId0);
7805 consumedOperands = 2;
7806 break;
7807 case glslang::EOpBitfieldExtract:
7808 if (isUnsigned)
7809 opCode = spv::OpBitFieldUExtract;
7810 else
7811 opCode = spv::OpBitFieldSExtract;
7812 break;
7813 case glslang::EOpBitfieldInsert:
7814 opCode = spv::OpBitFieldInsert;
7815 break;
7816
7817 case glslang::EOpFma:
7818 libCall = spv::GLSLstd450Fma;
7819 break;
7820 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007821 {
7822 libCall = spv::GLSLstd450FrexpStruct;
7823 assert(builder.isPointerType(typeId1));
7824 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007825 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007826 if (width == 16)
7827 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7828 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007829 if (builder.getNumComponents(operands[0]) == 1)
7830 frexpIntType = builder.makeIntegerType(width, true);
7831 else
John Kessenich8985fc92020-03-03 10:25:07 -07007832 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7833 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007834 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7835 consumedOperands = 1;
7836 }
John Kessenich55e7d112015-11-15 21:33:39 -07007837 break;
7838 case glslang::EOpLdexp:
7839 libCall = spv::GLSLstd450Ldexp;
7840 break;
7841
Rex Xu574ab042016-04-14 16:53:07 +08007842 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007843 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007844
John Kessenich66011cb2018-03-06 16:12:04 -07007845 case glslang::EOpSubgroupBroadcast:
7846 case glslang::EOpSubgroupBallotBitExtract:
7847 case glslang::EOpSubgroupShuffle:
7848 case glslang::EOpSubgroupShuffleXor:
7849 case glslang::EOpSubgroupShuffleUp:
7850 case glslang::EOpSubgroupShuffleDown:
7851 case glslang::EOpSubgroupClusteredAdd:
7852 case glslang::EOpSubgroupClusteredMul:
7853 case glslang::EOpSubgroupClusteredMin:
7854 case glslang::EOpSubgroupClusteredMax:
7855 case glslang::EOpSubgroupClusteredAnd:
7856 case glslang::EOpSubgroupClusteredOr:
7857 case glslang::EOpSubgroupClusteredXor:
7858 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007859 case glslang::EOpSubgroupPartitionedAdd:
7860 case glslang::EOpSubgroupPartitionedMul:
7861 case glslang::EOpSubgroupPartitionedMin:
7862 case glslang::EOpSubgroupPartitionedMax:
7863 case glslang::EOpSubgroupPartitionedAnd:
7864 case glslang::EOpSubgroupPartitionedOr:
7865 case glslang::EOpSubgroupPartitionedXor:
7866 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7867 case glslang::EOpSubgroupPartitionedInclusiveMul:
7868 case glslang::EOpSubgroupPartitionedInclusiveMin:
7869 case glslang::EOpSubgroupPartitionedInclusiveMax:
7870 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7871 case glslang::EOpSubgroupPartitionedInclusiveOr:
7872 case glslang::EOpSubgroupPartitionedInclusiveXor:
7873 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7874 case glslang::EOpSubgroupPartitionedExclusiveMul:
7875 case glslang::EOpSubgroupPartitionedExclusiveMin:
7876 case glslang::EOpSubgroupPartitionedExclusiveMax:
7877 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7878 case glslang::EOpSubgroupPartitionedExclusiveOr:
7879 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007880 return createSubgroupOperation(op, typeId, operands, typeProxy);
7881
Rex Xu9d93a232016-05-05 12:30:44 +08007882 case glslang::EOpSwizzleInvocations:
7883 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7884 libCall = spv::SwizzleInvocationsAMD;
7885 break;
7886 case glslang::EOpSwizzleInvocationsMasked:
7887 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7888 libCall = spv::SwizzleInvocationsMaskedAMD;
7889 break;
7890 case glslang::EOpWriteInvocation:
7891 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7892 libCall = spv::WriteInvocationAMD;
7893 break;
7894
7895 case glslang::EOpMin3:
7896 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7897 if (isFloat)
7898 libCall = spv::FMin3AMD;
7899 else {
7900 if (isUnsigned)
7901 libCall = spv::UMin3AMD;
7902 else
7903 libCall = spv::SMin3AMD;
7904 }
7905 break;
7906 case glslang::EOpMax3:
7907 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7908 if (isFloat)
7909 libCall = spv::FMax3AMD;
7910 else {
7911 if (isUnsigned)
7912 libCall = spv::UMax3AMD;
7913 else
7914 libCall = spv::SMax3AMD;
7915 }
7916 break;
7917 case glslang::EOpMid3:
7918 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7919 if (isFloat)
7920 libCall = spv::FMid3AMD;
7921 else {
7922 if (isUnsigned)
7923 libCall = spv::UMid3AMD;
7924 else
7925 libCall = spv::SMid3AMD;
7926 }
7927 break;
7928
7929 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007930 if (typeProxy == glslang::EbtFloat16)
7931 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007932 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7933 libCall = spv::InterpolateAtVertexAMD;
7934 break;
Chao Chen3c366992018-09-19 11:41:59 -07007935
Daniel Kochdb32b242020-03-17 20:42:47 -04007936 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007937 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007938 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007939 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05007940 case glslang::EOpTraceNV:
7941 builder.createNoResultOp(spv::OpTraceNV, operands);
7942 return 0;
7943 case glslang::EOpTraceKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007944 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007945 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05007946 case glslang::EOpExecuteCallableNV:
7947 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
7948 return 0;
7949 case glslang::EOpExecuteCallableKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007950 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007951 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007952
7953 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007954 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7955 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007956 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007957 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7958 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007959 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007960 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7961 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007962 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007963 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7964 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007965 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007966 typeId = builder.makeBoolType();
7967 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007968 break;
7969 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007970 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007971 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007972 break;
7973 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007974 typeId = builder.makeFloatType(32);
7975 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007976 break;
7977 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007978 typeId = builder.makeIntType(32);
7979 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007980 break;
7981 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007982 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007983 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007984 break;
7985 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007986 typeId = builder.makeIntType(32);
7987 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007988 break;
7989 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007990 typeId = builder.makeIntType(32);
7991 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007992 break;
7993 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Daniel Kochc0bcfaf2020-12-12 12:34:24 -05007994 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007995 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007996 break;
7997 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007998 typeId = builder.makeIntType(32);
7999 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008000 break;
8001 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04008002 typeId = builder.makeIntType(32);
8003 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008004 break;
8005 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04008006 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
8007 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008008 break;
8009 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04008010 typeId = builder.makeBoolType();
8011 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008012 break;
8013 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04008014 typeId = builder.makeBoolType();
8015 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008016 break;
8017 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008018 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8019 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008020 break;
8021 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008022 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8023 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008024 break;
8025 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008026 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8027 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008028 break;
8029 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008030 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8031 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008032 break;
8033 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04008034 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008035 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008036 break;
8037 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04008038 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008039 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008040 break;
Chao Chen3c366992018-09-19 11:41:59 -07008041 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
8042 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
8043 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008044 case glslang::EOpCooperativeMatrixMulAdd:
8045 opCode = spv::OpCooperativeMatrixMulAddNV;
8046 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06008047#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06008048 default:
8049 return 0;
8050 }
8051
8052 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07008053 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05008054 // Use an extended instruction from the standard library.
8055 // Construct the call arguments, without modifying the original operands vector.
8056 // We might need the remaining arguments, e.g. in the EOpFrexp case.
8057 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08008058 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01008059 } else if (opCode == spv::OpDot && !isFloat) {
8060 // int dot(int, int)
8061 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
8062 const int componentCount = builder.getNumComponents(operands[0]);
8063 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
8064 builder.setPrecision(mulOp, precision);
8065 id = builder.createCompositeExtract(mulOp, typeId, 0);
8066 for (int i = 1; i < componentCount; ++i) {
8067 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07008068 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01008069 }
John Kessenich2359bd02015-12-06 19:29:11 -07008070 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07008071 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06008072 case 0:
8073 // should all be handled by visitAggregate and createNoArgOperation
8074 assert(0);
8075 return 0;
8076 case 1:
8077 // should all be handled by createUnaryOperation
8078 assert(0);
8079 return 0;
8080 case 2:
8081 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
8082 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008083 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008084 // anything 3 or over doesn't have l-value operands, so all should be consumed
8085 assert(consumedOperands == operands.size());
8086 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06008087 break;
8088 }
8089 }
8090
John Kessenichb9197c82019-08-11 07:41:45 -06008091#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07008092 // Decode the return types that were structures
8093 switch (op) {
8094 case glslang::EOpAddCarry:
8095 case glslang::EOpSubBorrow:
8096 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8097 id = builder.createCompositeExtract(id, typeId0, 0);
8098 break;
8099 case glslang::EOpUMulExtended:
8100 case glslang::EOpIMulExtended:
8101 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
8102 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8103 break;
8104 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08008105 {
8106 assert(operands.size() == 2);
8107 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
8108 // "exp" is floating-point type (from HLSL intrinsic)
8109 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
8110 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
8111 builder.createStore(member1, operands[1]);
8112 } else
8113 // "exp" is integer type (from GLSL built-in function)
8114 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
8115 id = builder.createCompositeExtract(id, typeId0, 0);
8116 }
John Kessenich55e7d112015-11-15 21:33:39 -07008117 break;
8118 default:
8119 break;
8120 }
John Kessenichb9197c82019-08-11 07:41:45 -06008121#endif
John Kessenich55e7d112015-11-15 21:33:39 -07008122
John Kessenich32cfd492016-02-02 12:37:46 -07008123 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06008124}
8125
Rex Xu9d93a232016-05-05 12:30:44 +08008126// Intrinsics with no arguments (or no return value, and no precision).
8127spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06008128{
Jeff Bolz36831c92018-09-05 10:11:41 -05008129 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07008130 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
8131 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06008132
8133 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06008134 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008135 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05008136 if (glslangIntermediate->usingVulkanMemoryModel()) {
8137 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8138 spv::MemorySemanticsOutputMemoryKHRMask |
8139 spv::MemorySemanticsAcquireReleaseMask);
8140 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
8141 } else {
8142 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
8143 }
John Kessenich82979362017-12-11 04:02:24 -07008144 } else {
8145 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8146 spv::MemorySemanticsWorkgroupMemoryMask |
8147 spv::MemorySemanticsAcquireReleaseMask);
8148 }
John Kessenich140f3df2015-06-26 16:58:36 -06008149 return 0;
8150 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008151 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8152 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008153 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008154 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008155 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8156 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008157 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008158 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008159 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8160 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008161 return 0;
8162 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008163 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8164 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008165 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008166#ifndef GLSLANG_WEB
8167 case glslang::EOpMemoryBarrierAtomicCounter:
8168 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8169 spv::MemorySemanticsAcquireReleaseMask);
8170 return 0;
8171 case glslang::EOpMemoryBarrierImage:
8172 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8173 spv::MemorySemanticsAcquireReleaseMask);
8174 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008175 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008176 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008177 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008178 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008179 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008180 case glslang::EOpDeviceMemoryBarrier:
8181 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8182 spv::MemorySemanticsImageMemoryMask |
8183 spv::MemorySemanticsAcquireReleaseMask);
8184 return 0;
8185 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8186 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8187 spv::MemorySemanticsImageMemoryMask |
8188 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008189 return 0;
8190 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008191 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8192 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008193 return 0;
8194 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008195 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8196 spv::MemorySemanticsWorkgroupMemoryMask |
8197 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008198 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008199 case glslang::EOpSubgroupBarrier:
8200 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8201 spv::MemorySemanticsAcquireReleaseMask);
8202 return spv::NoResult;
8203 case glslang::EOpSubgroupMemoryBarrier:
8204 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8205 spv::MemorySemanticsAcquireReleaseMask);
8206 return spv::NoResult;
8207 case glslang::EOpSubgroupMemoryBarrierBuffer:
8208 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8209 spv::MemorySemanticsAcquireReleaseMask);
8210 return spv::NoResult;
8211 case glslang::EOpSubgroupMemoryBarrierImage:
8212 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8213 spv::MemorySemanticsAcquireReleaseMask);
8214 return spv::NoResult;
8215 case glslang::EOpSubgroupMemoryBarrierShared:
8216 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8217 spv::MemorySemanticsAcquireReleaseMask);
8218 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008219
8220 case glslang::EOpEmitVertex:
8221 builder.createNoResultOp(spv::OpEmitVertex);
8222 return 0;
8223 case glslang::EOpEndPrimitive:
8224 builder.createNoResultOp(spv::OpEndPrimitive);
8225 return 0;
8226
John Kessenich66011cb2018-03-06 16:12:04 -07008227 case glslang::EOpSubgroupElect: {
8228 std::vector<spv::Id> operands;
8229 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8230 }
Rex Xu9d93a232016-05-05 12:30:44 +08008231 case glslang::EOpTime:
8232 {
8233 std::vector<spv::Id> args; // Dummy arguments
8234 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8235 return builder.setPrecision(id, precision);
8236 }
Daniel Kochffccefd2020-11-23 15:41:27 -05008237 case glslang::EOpIgnoreIntersectionNV:
8238 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008239 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05008240 case glslang::EOpTerminateRayNV:
8241 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008242 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008243 case glslang::EOpRayQueryInitialize:
8244 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8245 return 0;
8246 case glslang::EOpRayQueryTerminate:
8247 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8248 return 0;
8249 case glslang::EOpRayQueryGenerateIntersection:
8250 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8251 return 0;
8252 case glslang::EOpRayQueryConfirmIntersection:
8253 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8254 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008255 case glslang::EOpBeginInvocationInterlock:
8256 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8257 return 0;
8258 case glslang::EOpEndInvocationInterlock:
8259 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8260 return 0;
8261
Jeff Bolzba6170b2019-07-01 09:23:23 -05008262 case glslang::EOpIsHelperInvocation:
8263 {
8264 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008265 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8266 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8267 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008268 }
8269
amhagan91fb0092019-07-10 21:14:38 -04008270 case glslang::EOpReadClockSubgroupKHR: {
8271 std::vector<spv::Id> args;
8272 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8273 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8274 builder.addCapability(spv::CapabilityShaderClockKHR);
8275 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8276 }
8277
8278 case glslang::EOpReadClockDeviceKHR: {
8279 std::vector<spv::Id> args;
8280 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8281 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8282 builder.addCapability(spv::CapabilityShaderClockKHR);
8283 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8284 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008285#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008286 default:
John Kessenich155d3512019-08-08 23:29:20 -06008287 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008288 }
John Kessenich155d3512019-08-08 23:29:20 -06008289
8290 logger->missingFunctionality("unknown operation with no arguments");
8291
8292 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008293}
8294
8295spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8296{
John Kessenich2f273362015-07-18 22:34:27 -06008297 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008298 spv::Id id;
8299 if (symbolValues.end() != iter) {
8300 id = iter->second;
8301 return id;
8302 }
8303
8304 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008305 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008306 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008307 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008308 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008309 if (forcedType.second != spv::NoType)
8310 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008311
Rex Xuc884b4a2016-06-29 15:03:44 +08008312 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008313 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8314 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8315 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008316#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008317 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008318 if (symbol->getQualifier().hasComponent())
8319 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8320 if (symbol->getQualifier().hasIndex())
8321 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008322#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008323 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008324 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008325 // atomic counters use this:
8326 if (symbol->getQualifier().hasOffset())
8327 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008328 }
8329
scygan2c864272016-05-18 18:09:17 +02008330 if (symbol->getQualifier().hasLocation())
8331 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008332 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008333 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008334 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008335 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008336 }
John Kessenich140f3df2015-06-26 16:58:36 -06008337 if (symbol->getQualifier().hasSet())
8338 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008339 else if (IsDescriptorResource(symbol->getType())) {
8340 // default to 0
8341 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8342 }
John Kessenich140f3df2015-06-26 16:58:36 -06008343 if (symbol->getQualifier().hasBinding())
8344 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008345 else if (IsDescriptorResource(symbol->getType())) {
8346 // default to 0
8347 builder.addDecoration(id, spv::DecorationBinding, 0);
8348 }
John Kessenich6c292d32016-02-15 20:58:50 -07008349 if (symbol->getQualifier().hasAttachment())
8350 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008351 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008352 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008353 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008354 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008355 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8356 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8357 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8358 }
8359 if (symbol->getQualifier().hasXfbOffset())
8360 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008361 }
8362
John Kessenichb9197c82019-08-11 07:41:45 -06008363 // add built-in variable decoration
8364 if (builtIn != spv::BuiltInMax) {
8365 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8366 }
8367
8368#ifndef GLSLANG_WEB
Daniel Kochffccefd2020-11-23 15:41:27 -05008369 // Subgroup builtins which have input storage class are volatile for ray tracing stages.
8370 if (symbol->getType().isImage() || symbol->getQualifier().isPipeInput()) {
Rex Xu1da878f2016-02-21 20:59:01 +08008371 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008372 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8373 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008374 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008375 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008376 }
8377
chaoc0ad6a4e2016-12-19 16:29:34 -08008378 if (builtIn == spv::BuiltInSampleMask) {
8379 spv::Decoration decoration;
8380 // GL_NV_sample_mask_override_coverage extension
8381 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008382 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008383 else
8384 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008385 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008386 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008387 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008388 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8389 }
8390 }
chaoc771d89f2017-01-13 01:10:53 -08008391 else if (builtIn == spv::BuiltInLayer) {
8392 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008393 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008394 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008395 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8396 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8397 }
John Kessenichb41bff62017-08-11 13:07:17 -06008398 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008399 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8400 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008401 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8402 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8403 }
8404 }
8405
chaoc6e5acae2016-12-20 13:28:52 -08008406 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008407 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008408 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008409 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8410 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008411 if (symbol->getQualifier().pervertexNV) {
8412 builder.addDecoration(id, spv::DecorationPerVertexNV);
8413 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8414 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8415 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008416
John Kessenich5d610ee2018-03-07 18:05:55 -07008417 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8418 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8419 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8420 symbol->getType().getQualifier().semanticName);
8421 }
8422
John Kessenich7015bd62019-08-01 03:28:08 -06008423 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008424 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8425 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008426 }
John Kessenichb9197c82019-08-11 07:41:45 -06008427#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008428
John Kessenich140f3df2015-06-26 16:58:36 -06008429 return id;
8430}
8431
John Kessenicha28f7a72019-08-06 07:00:58 -06008432#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008433// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8434void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8435{
8436 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008437 if (qualifier.perPrimitiveNV) {
8438 // Need to add capability/extension for fragment shader.
8439 // Mesh shader already adds this by default.
8440 if (glslangIntermediate->getStage() == EShLangFragment) {
8441 builder.addCapability(spv::CapabilityMeshShadingNV);
8442 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8443 }
Chao Chen3c366992018-09-19 11:41:59 -07008444 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008445 }
Chao Chen3c366992018-09-19 11:41:59 -07008446 if (qualifier.perViewNV)
8447 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8448 if (qualifier.perTaskNV)
8449 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8450 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008451 if (qualifier.perPrimitiveNV) {
8452 // Need to add capability/extension for fragment shader.
8453 // Mesh shader already adds this by default.
8454 if (glslangIntermediate->getStage() == EShLangFragment) {
8455 builder.addCapability(spv::CapabilityMeshShadingNV);
8456 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8457 }
Chao Chen3c366992018-09-19 11:41:59 -07008458 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008459 }
Chao Chen3c366992018-09-19 11:41:59 -07008460 if (qualifier.perViewNV)
8461 builder.addDecoration(id, spv::DecorationPerViewNV);
8462 if (qualifier.perTaskNV)
8463 builder.addDecoration(id, spv::DecorationPerTaskNV);
8464 }
8465}
8466#endif
8467
John Kessenich55e7d112015-11-15 21:33:39 -07008468// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008469// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008470//
8471// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8472//
8473// Recursively walk the nodes. The nodes form a tree whose leaves are
8474// regular constants, which themselves are trees that createSpvConstant()
8475// recursively walks. So, this function walks the "top" of the tree:
8476// - emit specialization constant-building instructions for specConstant
8477// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008478spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008479{
John Kessenich7cc0e282016-03-20 00:46:02 -06008480 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008481
qining4f4bb812016-04-03 23:55:17 -04008482 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008483 if (! node.getQualifier().specConstant) {
8484 // hand off to the non-spec-constant path
8485 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8486 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008487 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8488 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8489 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008490 }
8491
8492 // We now know we have a specialization constant to build
8493
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008494 // Extra capabilities may be needed.
8495 if (node.getType().contains8BitInt())
8496 builder.addCapability(spv::CapabilityInt8);
8497 if (node.getType().contains16BitFloat())
8498 builder.addCapability(spv::CapabilityFloat16);
8499 if (node.getType().contains16BitInt())
8500 builder.addCapability(spv::CapabilityInt16);
8501 if (node.getType().contains64BitInt())
8502 builder.addCapability(spv::CapabilityInt64);
8503 if (node.getType().containsDouble())
8504 builder.addCapability(spv::CapabilityFloat64);
8505
John Kessenichd94c0032016-05-30 19:29:40 -06008506 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008507 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8508 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8509 std::vector<spv::Id> dimConstId;
8510 for (int dim = 0; dim < 3; ++dim) {
8511 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8512 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008513 if (specConst) {
8514 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8515 glslangIntermediate->getLocalSizeSpecId(dim));
8516 }
qining4f4bb812016-04-03 23:55:17 -04008517 }
8518 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8519 }
8520
8521 // An AST node labelled as specialization constant should be a symbol node.
8522 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8523 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008524 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008525 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008526 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8527 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8528 // will set the builder into spec constant op instruction generating mode.
8529 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008530 result = accessChainLoad(sub_tree->getType());
8531 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008532 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008533 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008534 } else {
8535 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008536 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008537 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008538 builder.addName(result, sn->getName().c_str());
8539 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008540 }
qining4f4bb812016-04-03 23:55:17 -04008541
8542 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8543 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008544 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008545 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008546}
8547
John Kessenich140f3df2015-06-26 16:58:36 -06008548// Use 'consts' as the flattened glslang source of scalar constants to recursively
8549// build the aggregate SPIR-V constant.
8550//
8551// If there are not enough elements present in 'consts', 0 will be substituted;
8552// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8553//
John Kessenich8985fc92020-03-03 10:25:07 -07008554spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8555 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008556{
8557 // vector of constants for SPIR-V
8558 std::vector<spv::Id> spvConsts;
8559
8560 // Type is used for struct and array constants
8561 spv::Id typeId = convertGlslangToSpvType(glslangType);
8562
8563 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008564 glslang::TType elementType(glslangType, 0);
8565 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008566 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008567 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008568 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008569 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008570 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008571 } else if (glslangType.isCoopMat()) {
8572 glslang::TType componentType(glslangType.getBasicType());
8573 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008574 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008575 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8576 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008577 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008578 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008579 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8580 bool zero = nextConst >= consts.size();
8581 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008582 case glslang::EbtInt:
8583 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8584 break;
8585 case glslang::EbtUint:
8586 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8587 break;
8588 case glslang::EbtFloat:
8589 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8590 break;
8591 case glslang::EbtBool:
8592 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8593 break;
8594#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008595 case glslang::EbtInt8:
8596 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8597 break;
8598 case glslang::EbtUint8:
8599 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8600 break;
8601 case glslang::EbtInt16:
8602 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8603 break;
8604 case glslang::EbtUint16:
8605 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8606 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008607 case glslang::EbtInt64:
8608 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8609 break;
8610 case glslang::EbtUint64:
8611 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8612 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008613 case glslang::EbtDouble:
8614 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8615 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008616 case glslang::EbtFloat16:
8617 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8618 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008619#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008620 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008621 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008622 break;
8623 }
8624 ++nextConst;
8625 }
8626 } else {
8627 // we have a non-aggregate (scalar) constant
8628 bool zero = nextConst >= consts.size();
8629 spv::Id scalar = 0;
8630 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008631 case glslang::EbtInt:
8632 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8633 break;
8634 case glslang::EbtUint:
8635 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8636 break;
8637 case glslang::EbtFloat:
8638 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8639 break;
8640 case glslang::EbtBool:
8641 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8642 break;
8643#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008644 case glslang::EbtInt8:
8645 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8646 break;
8647 case glslang::EbtUint8:
8648 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8649 break;
8650 case glslang::EbtInt16:
8651 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8652 break;
8653 case glslang::EbtUint16:
8654 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8655 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008656 case glslang::EbtInt64:
8657 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8658 break;
8659 case glslang::EbtUint64:
8660 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8661 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008662 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008663 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008664 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008665 case glslang::EbtFloat16:
8666 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8667 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008668 case glslang::EbtReference:
8669 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8670 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8671 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008672#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008673 case glslang::EbtString:
8674 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008676 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008677 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008678 break;
8679 }
8680 ++nextConst;
8681 return scalar;
8682 }
8683
8684 return builder.makeCompositeConstant(typeId, spvConsts);
8685}
8686
John Kessenich7c1aa102015-10-15 13:29:11 -06008687// Return true if the node is a constant or symbol whose reading has no
8688// non-trivial observable cost or effect.
8689bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8690{
8691 // don't know what this is
8692 if (node == nullptr)
8693 return false;
8694
8695 // a constant is safe
8696 if (node->getAsConstantUnion() != nullptr)
8697 return true;
8698
8699 // not a symbol means non-trivial
8700 if (node->getAsSymbolNode() == nullptr)
8701 return false;
8702
8703 // a symbol, depends on what's being read
8704 switch (node->getType().getQualifier().storage) {
8705 case glslang::EvqTemporary:
8706 case glslang::EvqGlobal:
8707 case glslang::EvqIn:
8708 case glslang::EvqInOut:
8709 case glslang::EvqConst:
8710 case glslang::EvqConstReadOnly:
8711 case glslang::EvqUniform:
8712 return true;
8713 default:
8714 return false;
8715 }
qining25262b32016-05-06 17:25:16 -04008716}
John Kessenich7c1aa102015-10-15 13:29:11 -06008717
8718// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008719// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008720// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008721// Return true if trivial.
8722bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8723{
8724 if (node == nullptr)
8725 return false;
8726
John Kessenich84cc15f2017-05-24 16:44:47 -06008727 // count non scalars as trivial, as well as anything coming from HLSL
8728 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008729 return true;
8730
John Kessenich7c1aa102015-10-15 13:29:11 -06008731 // symbols and constants are trivial
8732 if (isTrivialLeaf(node))
8733 return true;
8734
8735 // otherwise, it needs to be a simple operation or one or two leaf nodes
8736
8737 // not a simple operation
8738 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8739 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8740 if (binaryNode == nullptr && unaryNode == nullptr)
8741 return false;
8742
8743 // not on leaf nodes
8744 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8745 return false;
8746
8747 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8748 return false;
8749 }
8750
8751 switch (node->getAsOperator()->getOp()) {
8752 case glslang::EOpLogicalNot:
8753 case glslang::EOpConvIntToBool:
8754 case glslang::EOpConvUintToBool:
8755 case glslang::EOpConvFloatToBool:
8756 case glslang::EOpConvDoubleToBool:
8757 case glslang::EOpEqual:
8758 case glslang::EOpNotEqual:
8759 case glslang::EOpLessThan:
8760 case glslang::EOpGreaterThan:
8761 case glslang::EOpLessThanEqual:
8762 case glslang::EOpGreaterThanEqual:
8763 case glslang::EOpIndexDirect:
8764 case glslang::EOpIndexDirectStruct:
8765 case glslang::EOpLogicalXor:
8766 case glslang::EOpAny:
8767 case glslang::EOpAll:
8768 return true;
8769 default:
8770 return false;
8771 }
8772}
8773
8774// Emit short-circuiting code, where 'right' is never evaluated unless
8775// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008776spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8777 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008778{
8779 spv::Id boolTypeId = builder.makeBoolType();
8780
8781 // emit left operand
8782 builder.clearAccessChain();
8783 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008784 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008785
8786 // Operands to accumulate OpPhi operands
8787 std::vector<spv::Id> phiOperands;
8788 // accumulate left operand's phi information
8789 phiOperands.push_back(leftId);
8790 phiOperands.push_back(builder.getBuildPoint()->getId());
8791
8792 // Make the two kinds of operation symmetric with a "!"
8793 // || => emit "if (! left) result = right"
8794 // && => emit "if ( left) result = right"
8795 //
8796 // TODO: this runtime "not" for || could be avoided by adding functionality
8797 // to 'builder' to have an "else" without an "then"
8798 if (op == glslang::EOpLogicalOr)
8799 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8800
8801 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008802 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008803
8804 // emit right operand as the "then" part of the "if"
8805 builder.clearAccessChain();
8806 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008807 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008808
8809 // accumulate left operand's phi information
8810 phiOperands.push_back(rightId);
8811 phiOperands.push_back(builder.getBuildPoint()->getId());
8812
8813 // finish the "if"
8814 ifBuilder.makeEndIf();
8815
8816 // phi together the two results
8817 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8818}
8819
John Kessenicha28f7a72019-08-06 07:00:58 -06008820#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008821// Return type Id of the imported set of extended instructions corresponds to the name.
8822// Import this set if it has not been imported yet.
8823spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8824{
8825 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8826 return extBuiltinMap[name];
8827 else {
Rex Xu51596642016-09-21 18:56:12 +08008828 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008829 spv::Id extBuiltins = builder.import(name);
8830 extBuiltinMap[name] = extBuiltins;
8831 return extBuiltins;
8832 }
8833}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008834#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008835
John Kessenich140f3df2015-06-26 16:58:36 -06008836}; // end anonymous namespace
8837
8838namespace glslang {
8839
John Kessenich68d78fd2015-07-12 19:28:10 -06008840void GetSpirvVersion(std::string& version)
8841{
John Kessenich9e55f632015-07-15 10:03:39 -06008842 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008843 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008844 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008845 version = buf;
8846}
8847
John Kessenicha372a3e2017-11-02 22:32:14 -06008848// For low-order part of the generator's magic number. Bump up
8849// when there is a change in the style (e.g., if SSA form changes,
8850// or a different instruction sequence to do something gets used).
8851int GetSpirvGeneratorVersion()
8852{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008853 // return 1; // start
8854 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008855 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008856 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008857 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008858 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8859 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008860 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008861 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008862 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8863 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008864}
8865
John Kessenich140f3df2015-06-26 16:58:36 -06008866// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008867void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008868{
8869 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008870 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008871 if (out.fail())
8872 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008873 for (int i = 0; i < (int)spirv.size(); ++i) {
8874 unsigned int word = spirv[i];
8875 out.write((const char*)&word, 4);
8876 }
8877 out.close();
8878}
8879
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008880// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008881void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008882{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008883#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008884 std::ofstream out;
8885 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008886 if (out.fail())
8887 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008888 out << "\t// " <<
8889 GetSpirvGeneratorVersion() <<
8890 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8891 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008892 if (varName != nullptr) {
8893 out << "\t #pragma once" << std::endl;
8894 out << "const uint32_t " << varName << "[] = {" << std::endl;
8895 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008896 const int WORDS_PER_LINE = 8;
8897 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8898 out << "\t";
8899 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8900 const unsigned int word = spirv[i + j];
8901 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8902 if (i + j + 1 < (int)spirv.size()) {
8903 out << ",";
8904 }
8905 }
8906 out << std::endl;
8907 }
Flavio15017db2017-02-15 14:29:33 -08008908 if (varName != nullptr) {
8909 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008910 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008911 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008912 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008913#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008914}
8915
John Kessenich140f3df2015-06-26 16:58:36 -06008916//
8917// Set up the glslang traversal
8918//
John Kessenich4e11b612018-08-30 16:56:59 -06008919void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008920{
Lei Zhang17535f72016-05-04 15:55:59 -04008921 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008922 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008923}
8924
John Kessenich4e11b612018-08-30 16:56:59 -06008925void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008926 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008927{
John Kessenich140f3df2015-06-26 16:58:36 -06008928 TIntermNode* root = intermediate.getTreeRoot();
8929
8930 if (root == 0)
8931 return;
8932
John Kessenich4e11b612018-08-30 16:56:59 -06008933 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008934 if (options == nullptr)
8935 options = &defaultOptions;
8936
John Kessenich4e11b612018-08-30 16:56:59 -06008937 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008938
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008939 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008940 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008941 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008942 it.dumpSpv(spirv);
8943
GregFfb03a552018-03-29 11:49:14 -06008944#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008945 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8946 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008947 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008948 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8949 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008950 prelegalization = false;
8951 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008952 else if (options->stripDebugInfo) {
8953 // Strip debug info even if optimization is disabled.
8954 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8955 }
John Kessenich717c80a2018-08-23 15:17:10 -06008956
John Kessenich4e11b612018-08-30 16:56:59 -06008957 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008958 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008959
John Kessenich717c80a2018-08-23 15:17:10 -06008960 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008961 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008962
GregFcd1f1692017-09-21 18:40:22 -06008963#endif
8964
John Kessenich4e11b612018-08-30 16:56:59 -06008965 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008966}
8967
8968}; // end namespace glslang