blob: 4a07323409bb5bc3dbda6901ca7da4515de66009 [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 Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051}
John Kessenich140f3df2015-06-26 16:58:36 -060052
53// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020054#include "../glslang/MachineIndependent/localintermediate.h"
55#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060056#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050057#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060058
John Kessenich140f3df2015-06-26 16:58:36 -060059#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050060#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040061#include <list>
62#include <map>
63#include <stack>
64#include <string>
65#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060066
67namespace {
68
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
John Kessenichead86222018-03-28 18:01:20 -060088
89struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060090 public:
91 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
92 precision(precision)
93#ifndef GLSLANG_WEB
94 ,
95 noContraction(noContraction),
96 nonUniform(nonUniform)
97#endif
98 { }
99
John Kessenichead86222018-03-28 18:01:20 -0600100 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600101
102#ifdef GLSLANG_WEB
103 void addNoContraction(spv::Builder&, spv::Id) const { };
104 void addNonUniform(spv::Builder&, spv::Id) const { };
105#else
106 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); };
107 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); };
108 protected:
109 spv::Decoration noContraction;
110 spv::Decoration nonUniform;
111#endif
112
John Kessenichead86222018-03-28 18:01:20 -0600113};
114
115} // namespace
qining4c912612016-04-01 10:35:16 -0400116
John Kessenich140f3df2015-06-26 16:58:36 -0600117//
118// The main holder of information for translating glslang to SPIR-V.
119//
120// Derives from the AST walking base class.
121//
122class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
123public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700124 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
125 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700126 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
129 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
130 void visitConstantUnion(glslang::TIntermConstantUnion*);
131 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
132 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
133 void visitSymbol(glslang::TIntermSymbol* symbol);
134 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
135 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
136 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
137
John Kessenichfca82622016-11-26 13:23:20 -0700138 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700139 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
141protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700142 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
143 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
144
Rex Xu17ff3432016-10-14 17:41:45 +0800145 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800146 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500148 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
149 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
150 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100152 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700153 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700154 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
155 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700156 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600157 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600158 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600159 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600160 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600161 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
162 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
163 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600164 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600167 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600168 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
169 glslang::TLayoutPacking, const glslang::TQualifier&);
170 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
171 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700172 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700173 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800174 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600175 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700176 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700177 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
178 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700179 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
180 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100181 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich6fccb3c2016-09-19 16:01:41 -0600183 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600184 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600185 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 void makeFunctions(const glslang::TIntermSequence&);
187 void makeGlobalInitializers(const glslang::TIntermSequence&);
188 void visitFunctions(const glslang::TIntermSequence&);
189 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500190 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600191 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
192 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600193 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
194
John Kessenichead86222018-03-28 18:01:20 -0600195 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
196 glslang::TBasicType typeProxy, bool reduceComparison = true);
197 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
198 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500199 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
201 glslang::TBasicType typeProxy);
202 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
203 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600204 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600205 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500206 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800207 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800208 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700209 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600210 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800211 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700213 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400214 spv::Id createSpvConstant(const glslang::TIntermTyped&);
215 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600216 bool isTrivialLeaf(const glslang::TIntermTyped* node);
217 bool isTrivial(const glslang::TIntermTyped* node);
218 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800219 spv::Id getExtBuiltins(const char* name);
John Kessenich66011cb2018-03-06 16:12:04 -0700220 void addPre13Extension(const char* ext)
221 {
222 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
223 builder.addExtension(ext);
224 }
John Kessenich9c14f772019-06-17 08:38:35 -0600225 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
226 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500227 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600228
John Kessenich121853f2017-05-31 17:11:16 -0600229 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600231 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700232 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 int sequenceDepth;
234
Lei Zhang17535f72016-05-04 15:55:59 -0400235 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400236
John Kessenich140f3df2015-06-26 16:58:36 -0600237 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
238 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700239 bool inEntryPoint;
240 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700241 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700242 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600243 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600244 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600245 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800246 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600247
John Kessenich2f273362015-07-18 22:34:27 -0600248 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600249 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600250 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700251 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700252 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
253 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600254 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700255 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600256 // Map pointee types for EbtReference to their forward pointers
257 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600258 // Type forcing, for when SPIR-V wants a different type than the AST,
259 // requiring local translation to and from SPIR-V type on every access.
260 // Maps <builtin-variable-id -> AST-required-type-id>
261 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600262};
263
264//
265// Helper functions for translating glslang representations to SPIR-V enumerants.
266//
267
268// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700269spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenich155d3512019-08-08 23:29:20 -0600271#ifdef GLSLANG_WEB
272 return spv::SourceLanguageESSL;
273#endif
274
John Kessenich66e2faf2016-03-12 18:34:36 -0700275 switch (source) {
276 case glslang::EShSourceGlsl:
277 switch (profile) {
278 case ENoProfile:
279 case ECoreProfile:
280 case ECompatibilityProfile:
281 return spv::SourceLanguageGLSL;
282 case EEsProfile:
283 return spv::SourceLanguageESSL;
284 default:
285 return spv::SourceLanguageUnknown;
286 }
287 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600288 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
290 return spv::SourceLanguageUnknown;
291 }
292}
293
294// Translate glslang language (stage) to SPIR-V execution model.
295spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
296{
297 switch (stage) {
298 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600299 case EShLangFragment: return spv::ExecutionModelFragment;
300#ifndef GLSLANG_WEB
301 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
303 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
304 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700305 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
306 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
307 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
308 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
309 case EShLangMissNV: return spv::ExecutionModelMissNV;
310 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700311 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
312 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
313#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600314 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700315 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600316 return spv::ExecutionModelFragment;
317 }
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang sampler type to SPIR-V dimensionality.
321spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
322{
323 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700324 case glslang::Esd1D: return spv::Dim1D;
325 case glslang::Esd2D: return spv::Dim2D;
326 case glslang::Esd3D: return spv::Dim3D;
327 case glslang::EsdCube: return spv::DimCube;
328 case glslang::EsdRect: return spv::DimRect;
329 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700330 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600331 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700332 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600333 return spv::Dim2D;
334 }
335}
336
John Kessenichf6640762016-08-01 19:44:00 -0600337// Translate glslang precision to SPIR-V precision decorations.
338spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600339{
John Kessenichf6640762016-08-01 19:44:00 -0600340 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700341 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600342 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 default:
344 return spv::NoPrecision;
345 }
346}
347
John Kessenichf6640762016-08-01 19:44:00 -0600348// Translate glslang type to SPIR-V precision decorations.
349spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
350{
351 return TranslatePrecisionDecoration(type.getQualifier().precision);
352}
353
John Kessenich140f3df2015-06-26 16:58:36 -0600354// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600355spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600356{
357 if (type.getBasicType() == glslang::EbtBlock) {
358 switch (type.getQualifier().storage) {
359 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600360 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 case glslang::EvqVaryingIn: return spv::DecorationBlock;
362 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600363#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700364 case glslang::EvqPayloadNV: return spv::DecorationBlock;
365 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
366 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700367 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
368 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700369#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600370 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700371 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600372 break;
373 }
374 }
375
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377}
378
Rex Xu1da878f2016-02-21 20:59:01 +0800379// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500380void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800381{
John Kessenichb9197c82019-08-11 07:41:45 -0600382#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500383 if (!useVulkanMemoryModel) {
384 if (qualifier.coherent)
385 memory.push_back(spv::DecorationCoherent);
386 if (qualifier.volatil) {
387 memory.push_back(spv::DecorationVolatile);
388 memory.push_back(spv::DecorationCoherent);
389 }
John Kessenich14b85d32018-06-04 15:36:03 -0600390 }
Rex Xu1da878f2016-02-21 20:59:01 +0800391 if (qualifier.restrict)
392 memory.push_back(spv::DecorationRestrict);
393 if (qualifier.readonly)
394 memory.push_back(spv::DecorationNonWritable);
395 if (qualifier.writeonly)
396 memory.push_back(spv::DecorationNonReadable);
John Kessenichb9197c82019-08-11 07:41:45 -0600397#endif
Rex Xu1da878f2016-02-21 20:59:01 +0800398}
399
John Kessenich140f3df2015-06-26 16:58:36 -0600400// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700401spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600402{
403 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700404 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600405 case glslang::ElmRowMajor:
406 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700407 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700409 default:
410 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600412 }
413 } else {
414 switch (type.getBasicType()) {
415 default:
John Kessenich4016e382016-07-15 11:53:56 -0600416 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600417 break;
418 case glslang::EbtBlock:
419 switch (type.getQualifier().storage) {
420 case glslang::EvqUniform:
421 case glslang::EvqBuffer:
422 switch (type.getQualifier().layoutPacking) {
423 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600424 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
425 default:
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 }
428 case glslang::EvqVaryingIn:
429 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700430 if (type.getQualifier().isTaskMemory()) {
431 switch (type.getQualifier().layoutPacking) {
432 case glslang::ElpShared: return spv::DecorationGLSLShared;
433 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
434 default: break;
435 }
436 } else {
437 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
438 }
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600440#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700441 case glslang::EvqPayloadNV:
442 case glslang::EvqPayloadInNV:
443 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700444 case glslang::EvqCallableDataNV:
445 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700446 return spv::DecorationMax;
447#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600448 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700449 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600450 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600451 }
452 }
453 }
454}
455
456// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600457// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700458// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800459spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600460{
Rex Xubbceed72016-05-21 09:40:44 +0800461 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700462 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600464 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700465 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700466 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600467 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600468 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800469 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800470 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800471 }
Rex Xubbceed72016-05-21 09:40:44 +0800472 else
John Kessenich4016e382016-07-15 11:53:56 -0600473 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800474}
475
476// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600477// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800478// should be applied.
479spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
480{
John Kessenichb9197c82019-08-11 07:41:45 -0600481 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600482 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600483#ifndef GLSLANG_WEB
484 else if (qualifier.patch)
485 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700486 else if (qualifier.sample) {
487 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600489 }
490#endif
491
492 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600493}
494
John Kessenich92187592016-02-01 13:45:25 -0700495// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700496spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600497{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700498 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600499 return spv::DecorationInvariant;
500 else
John Kessenich4016e382016-07-15 11:53:56 -0600501 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600502}
503
qining9220dbb2016-05-04 17:34:38 -0400504// If glslang type is noContraction, return SPIR-V NoContraction decoration.
505spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
506{
John Kessenichb9197c82019-08-11 07:41:45 -0600507#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600508 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400509 return spv::DecorationNoContraction;
510 else
John Kessenichb9197c82019-08-11 07:41:45 -0600511#endif
John Kessenich4016e382016-07-15 11:53:56 -0600512 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400513}
514
John Kessenich5611c6d2018-04-05 11:25:02 -0600515// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
516spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
517{
John Kessenichb9197c82019-08-11 07:41:45 -0600518#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600519 if (qualifier.isNonUniform()) {
520 builder.addExtension("SPV_EXT_descriptor_indexing");
521 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
522 return spv::DecorationNonUniformEXT;
523 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600524#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600525 return spv::DecorationMax;
526}
527
John Kessenichb9197c82019-08-11 07:41:45 -0600528spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
529 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500530{
Jeff Bolz36831c92018-09-05 10:11:41 -0500531 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600532
533#ifndef GLSLANG_WEB
534 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
535 return mask;
536
Jeff Bolz36831c92018-09-05 10:11:41 -0500537 if (coherentFlags.volatil ||
538 coherentFlags.coherent ||
539 coherentFlags.devicecoherent ||
540 coherentFlags.queuefamilycoherent ||
541 coherentFlags.workgroupcoherent ||
542 coherentFlags.subgroupcoherent) {
543 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
544 spv::MemoryAccessMakePointerVisibleKHRMask;
545 }
546 if (coherentFlags.nonprivate) {
547 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
548 }
549 if (coherentFlags.volatil) {
550 mask = mask | spv::MemoryAccessVolatileMask;
551 }
552 if (mask != spv::MemoryAccessMaskNone) {
553 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
554 }
John Kessenichb9197c82019-08-11 07:41:45 -0600555#endif
556
Jeff Bolz36831c92018-09-05 10:11:41 -0500557 return mask;
558}
559
John Kessenichb9197c82019-08-11 07:41:45 -0600560spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
561 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500562{
Jeff Bolz36831c92018-09-05 10:11:41 -0500563 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600564
565#ifndef GLSLANG_WEB
566 if (!glslangIntermediate->usingVulkanMemoryModel())
567 return mask;
568
Jeff Bolz36831c92018-09-05 10:11:41 -0500569 if (coherentFlags.volatil ||
570 coherentFlags.coherent ||
571 coherentFlags.devicecoherent ||
572 coherentFlags.queuefamilycoherent ||
573 coherentFlags.workgroupcoherent ||
574 coherentFlags.subgroupcoherent) {
575 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
576 spv::ImageOperandsMakeTexelVisibleKHRMask;
577 }
578 if (coherentFlags.nonprivate) {
579 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
580 }
581 if (coherentFlags.volatil) {
582 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
583 }
584 if (mask != spv::ImageOperandsMaskNone) {
585 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
586 }
John Kessenichb9197c82019-08-11 07:41:45 -0600587#endif
588
Jeff Bolz36831c92018-09-05 10:11:41 -0500589 return mask;
590}
591
592spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
593{
John Kessenichb9197c82019-08-11 07:41:45 -0600594 spv::Builder::AccessChain::CoherentFlags flags = {};
595#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500596 flags.coherent = type.getQualifier().coherent;
597 flags.devicecoherent = type.getQualifier().devicecoherent;
598 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
599 // shared variables are implicitly workgroupcoherent in GLSL.
600 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
601 type.getQualifier().storage == glslang::EvqShared;
602 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600603 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500604 // *coherent variables are implicitly nonprivate in GLSL
605 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500606 flags.subgroupcoherent ||
607 flags.workgroupcoherent ||
608 flags.queuefamilycoherent ||
609 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.coherent ||
611 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500612 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600613#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500614 return flags;
615}
616
John Kessenichb9197c82019-08-11 07:41:45 -0600617spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
618 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500619{
John Kessenichb9197c82019-08-11 07:41:45 -0600620 spv::Scope scope = spv::ScopeMax;
621
622#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600623 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500624 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
625 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
626 } else if (coherentFlags.devicecoherent) {
627 scope = spv::ScopeDevice;
628 } else if (coherentFlags.queuefamilycoherent) {
629 scope = spv::ScopeQueueFamilyKHR;
630 } else if (coherentFlags.workgroupcoherent) {
631 scope = spv::ScopeWorkgroup;
632 } else if (coherentFlags.subgroupcoherent) {
633 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500634 }
635 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
636 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
637 }
John Kessenichb9197c82019-08-11 07:41:45 -0600638#endif
639
Jeff Bolz36831c92018-09-05 10:11:41 -0500640 return scope;
641}
642
David Netoa901ffe2016-06-08 14:11:40 +0100643// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
644// associated capabilities when required. For some built-in variables, a capability
645// is generated only when using the variable in an executable instruction, but not when
646// just declaring a struct member variable with it. This is true for PointSize,
647// ClipDistance, and CullDistance.
648spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600649{
650 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700651 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600652#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600653 // Defer adding the capability until the built-in is actually used.
654 if (! memberDeclaration) {
655 switch (glslangIntermediate->getStage()) {
656 case EShLangGeometry:
657 builder.addCapability(spv::CapabilityGeometryPointSize);
658 break;
659 case EShLangTessControl:
660 case EShLangTessEvaluation:
661 builder.addCapability(spv::CapabilityTessellationPointSize);
662 break;
663 default:
664 break;
665 }
John Kessenich92187592016-02-01 13:45:25 -0700666 }
John Kessenich155d3512019-08-08 23:29:20 -0600667#endif
John Kessenich92187592016-02-01 13:45:25 -0700668 return spv::BuiltInPointSize;
669
John Kessenicha28f7a72019-08-06 07:00:58 -0600670 case glslang::EbvPosition: return spv::BuiltInPosition;
671 case glslang::EbvVertexId: return spv::BuiltInVertexId;
672 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
673 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
674 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
675
676 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
677 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
678 case glslang::EbvFace: return spv::BuiltInFrontFacing;
679 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
680
681#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600682 // These *Distance capabilities logically belong here, but if the member is declared and
683 // then never used, consumers of SPIR-V prefer the capability not be declared.
684 // They are now generated when used, rather than here when declared.
685 // Potentially, the specification should be more clear what the minimum
686 // use needed is to trigger the capability.
687 //
John Kessenich92187592016-02-01 13:45:25 -0700688 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100689 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800690 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700691 return spv::BuiltInClipDistance;
692
693 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100694 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800695 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700696 return spv::BuiltInCullDistance;
697
698 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600699 builder.addCapability(spv::CapabilityMultiViewport);
700 if (glslangIntermediate->getStage() == EShLangVertex ||
701 glslangIntermediate->getStage() == EShLangTessControl ||
702 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800703
John Kessenichba6a3c22017-09-13 13:22:50 -0600704 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
705 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800706 }
John Kessenich92187592016-02-01 13:45:25 -0700707 return spv::BuiltInViewportIndex;
708
John Kessenich5e801132016-02-15 11:09:46 -0700709 case glslang::EbvSampleId:
710 builder.addCapability(spv::CapabilitySampleRateShading);
711 return spv::BuiltInSampleId;
712
713 case glslang::EbvSamplePosition:
714 builder.addCapability(spv::CapabilitySampleRateShading);
715 return spv::BuiltInSamplePosition;
716
717 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700718 return spv::BuiltInSampleMask;
719
John Kessenich78a45572016-07-08 14:05:15 -0600720 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700721 if (glslangIntermediate->getStage() == EShLangMeshNV) {
722 return spv::BuiltInLayer;
723 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600724 builder.addCapability(spv::CapabilityGeometry);
725 if (glslangIntermediate->getStage() == EShLangVertex ||
726 glslangIntermediate->getStage() == EShLangTessControl ||
727 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800728
John Kessenichba6a3c22017-09-13 13:22:50 -0600729 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
730 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800731 }
John Kessenich78a45572016-07-08 14:05:15 -0600732 return spv::BuiltInLayer;
733
John Kessenichda581a22015-10-14 14:10:30 -0600734 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700735 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800736 builder.addCapability(spv::CapabilityDrawParameters);
737 return spv::BuiltInBaseVertex;
738
John Kessenichda581a22015-10-14 14:10:30 -0600739 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700740 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800741 builder.addCapability(spv::CapabilityDrawParameters);
742 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200743
John Kessenichda581a22015-10-14 14:10:30 -0600744 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700745 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800746 builder.addCapability(spv::CapabilityDrawParameters);
747 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200748
749 case glslang::EbvPrimitiveId:
750 if (glslangIntermediate->getStage() == EShLangFragment)
751 builder.addCapability(spv::CapabilityGeometry);
752 return spv::BuiltInPrimitiveId;
753
Rex Xu37cdcee2017-06-29 17:46:34 +0800754 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800755 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
756 builder.addCapability(spv::CapabilityStencilExportEXT);
757 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800758
John Kessenich140f3df2015-06-26 16:58:36 -0600759 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600760 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
761 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
762 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
763 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600764 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
765 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
766 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
767 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
768 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
769 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
770 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800771
Rex Xu574ab042016-04-14 16:53:07 +0800772 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800773 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800774 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
775 return spv::BuiltInSubgroupSize;
776
Rex Xu574ab042016-04-14 16:53:07 +0800777 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800778 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800779 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
780 return spv::BuiltInSubgroupLocalInvocationId;
781
Rex Xu574ab042016-04-14 16:53:07 +0800782 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800783 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
784 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600785 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800786
Rex Xu574ab042016-04-14 16:53:07 +0800787 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800788 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
789 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600790 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800791
Rex Xu574ab042016-04-14 16:53:07 +0800792 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800793 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
794 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600795 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800796
Rex Xu574ab042016-04-14 16:53:07 +0800797 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800798 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
799 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600800 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800801
Rex Xu574ab042016-04-14 16:53:07 +0800802 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800803 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
804 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600805 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800806
John Kessenich66011cb2018-03-06 16:12:04 -0700807 case glslang::EbvNumSubgroups:
808 builder.addCapability(spv::CapabilityGroupNonUniform);
809 return spv::BuiltInNumSubgroups;
810
811 case glslang::EbvSubgroupID:
812 builder.addCapability(spv::CapabilityGroupNonUniform);
813 return spv::BuiltInSubgroupId;
814
815 case glslang::EbvSubgroupSize2:
816 builder.addCapability(spv::CapabilityGroupNonUniform);
817 return spv::BuiltInSubgroupSize;
818
819 case glslang::EbvSubgroupInvocation2:
820 builder.addCapability(spv::CapabilityGroupNonUniform);
821 return spv::BuiltInSubgroupLocalInvocationId;
822
823 case glslang::EbvSubgroupEqMask2:
824 builder.addCapability(spv::CapabilityGroupNonUniform);
825 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
826 return spv::BuiltInSubgroupEqMask;
827
828 case glslang::EbvSubgroupGeMask2:
829 builder.addCapability(spv::CapabilityGroupNonUniform);
830 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
831 return spv::BuiltInSubgroupGeMask;
832
833 case glslang::EbvSubgroupGtMask2:
834 builder.addCapability(spv::CapabilityGroupNonUniform);
835 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
836 return spv::BuiltInSubgroupGtMask;
837
838 case glslang::EbvSubgroupLeMask2:
839 builder.addCapability(spv::CapabilityGroupNonUniform);
840 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
841 return spv::BuiltInSubgroupLeMask;
842
843 case glslang::EbvSubgroupLtMask2:
844 builder.addCapability(spv::CapabilityGroupNonUniform);
845 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
846 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600847
Rex Xu17ff3432016-10-14 17:41:45 +0800848 case glslang::EbvBaryCoordNoPersp:
849 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
850 return spv::BuiltInBaryCoordNoPerspAMD;
851
852 case glslang::EbvBaryCoordNoPerspCentroid:
853 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
854 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
855
856 case glslang::EbvBaryCoordNoPerspSample:
857 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
858 return spv::BuiltInBaryCoordNoPerspSampleAMD;
859
860 case glslang::EbvBaryCoordSmooth:
861 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
862 return spv::BuiltInBaryCoordSmoothAMD;
863
864 case glslang::EbvBaryCoordSmoothCentroid:
865 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
866 return spv::BuiltInBaryCoordSmoothCentroidAMD;
867
868 case glslang::EbvBaryCoordSmoothSample:
869 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
870 return spv::BuiltInBaryCoordSmoothSampleAMD;
871
872 case glslang::EbvBaryCoordPullModel:
873 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
874 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800875
John Kessenich6c8aaac2017-02-27 01:20:51 -0700876 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700877 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700878 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700879 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700880
881 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700882 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700884 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700885
Daniel Koch5154db52018-11-26 10:01:58 -0500886 case glslang::EbvFragSizeEXT:
887 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
888 builder.addCapability(spv::CapabilityFragmentDensityEXT);
889 return spv::BuiltInFragSizeEXT;
890
891 case glslang::EbvFragInvocationCountEXT:
892 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
893 builder.addCapability(spv::CapabilityFragmentDensityEXT);
894 return spv::BuiltInFragInvocationCountEXT;
895
chaoc771d89f2017-01-13 01:10:53 -0800896 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800897 if (!memberDeclaration) {
898 builder.addExtension(spv::E_SPV_NV_viewport_array2);
899 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
900 }
chaoc771d89f2017-01-13 01:10:53 -0800901 return spv::BuiltInViewportMaskNV;
902 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800903 if (!memberDeclaration) {
904 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
905 builder.addCapability(spv::CapabilityShaderStereoViewNV);
906 }
chaoc771d89f2017-01-13 01:10:53 -0800907 return spv::BuiltInSecondaryPositionNV;
908 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800909 if (!memberDeclaration) {
910 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
911 builder.addCapability(spv::CapabilityShaderStereoViewNV);
912 }
chaoc771d89f2017-01-13 01:10:53 -0800913 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800914 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800915 if (!memberDeclaration) {
916 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
917 builder.addCapability(spv::CapabilityPerViewAttributesNV);
918 }
chaocdf3956c2017-02-14 14:52:34 -0800919 return spv::BuiltInPositionPerViewNV;
920 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800921 if (!memberDeclaration) {
922 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
923 builder.addCapability(spv::CapabilityPerViewAttributesNV);
924 }
chaocdf3956c2017-02-14 14:52:34 -0800925 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700926 case glslang::EbvFragFullyCoveredNV:
927 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
928 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
929 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700930 case glslang::EbvFragmentSizeNV:
931 builder.addExtension(spv::E_SPV_NV_shading_rate);
932 builder.addCapability(spv::CapabilityShadingRateNV);
933 return spv::BuiltInFragmentSizeNV;
934 case glslang::EbvInvocationsPerPixelNV:
935 builder.addExtension(spv::E_SPV_NV_shading_rate);
936 builder.addCapability(spv::CapabilityShadingRateNV);
937 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700938
Daniel Koch593a4e02019-05-27 16:46:31 -0400939 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700940 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700941 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700942 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700943 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700944 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700945 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700946 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700947 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700948 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700949 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700950 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700951 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700952 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700953 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700954 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700955 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700956 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700957 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700958 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700959 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700960 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700961 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700962 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700963 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700964 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700965 return spv::BuiltInWorldToObjectNV;
966 case glslang::EbvIncomingRayFlagsNV:
967 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400968
969 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700970 case glslang::EbvBaryCoordNV:
971 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
972 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
973 return spv::BuiltInBaryCoordNV;
974 case glslang::EbvBaryCoordNoPerspNV:
975 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
976 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
977 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400978
979 // mesh shaders
980 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700981 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400982 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700983 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400984 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700985 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400986 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700987 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400988 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700989 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400990 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700991 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400992 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700993 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400994 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700995 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400996
997 // sm builtins
998 case glslang::EbvWarpsPerSM:
999 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1000 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1001 return spv::BuiltInWarpsPerSMNV;
1002 case glslang::EbvSMCount:
1003 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1004 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1005 return spv::BuiltInSMCountNV;
1006 case glslang::EbvWarpID:
1007 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1008 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1009 return spv::BuiltInWarpIDNV;
1010 case glslang::EbvSMID:
1011 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1012 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1013 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001014#endif
1015
Rex Xu3e783f92017-02-22 16:44:48 +08001016 default:
1017 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001018 }
1019}
1020
Rex Xufc618912015-09-09 16:42:49 +08001021// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001022spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001023{
1024 assert(type.getBasicType() == glslang::EbtSampler);
1025
John Kessenichb9197c82019-08-11 07:41:45 -06001026#ifdef GLSLANG_WEB
1027 return spv::ImageFormatUnknown;
1028#endif
1029
John Kessenich5d0fa972016-02-15 11:57:00 -07001030 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001031 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001032 case glslang::ElfRg32f:
1033 case glslang::ElfRg16f:
1034 case glslang::ElfR11fG11fB10f:
1035 case glslang::ElfR16f:
1036 case glslang::ElfRgba16:
1037 case glslang::ElfRgb10A2:
1038 case glslang::ElfRg16:
1039 case glslang::ElfRg8:
1040 case glslang::ElfR16:
1041 case glslang::ElfR8:
1042 case glslang::ElfRgba16Snorm:
1043 case glslang::ElfRg16Snorm:
1044 case glslang::ElfRg8Snorm:
1045 case glslang::ElfR16Snorm:
1046 case glslang::ElfR8Snorm:
1047
1048 case glslang::ElfRg32i:
1049 case glslang::ElfRg16i:
1050 case glslang::ElfRg8i:
1051 case glslang::ElfR16i:
1052 case glslang::ElfR8i:
1053
1054 case glslang::ElfRgb10a2ui:
1055 case glslang::ElfRg32ui:
1056 case glslang::ElfRg16ui:
1057 case glslang::ElfRg8ui:
1058 case glslang::ElfR16ui:
1059 case glslang::ElfR8ui:
1060 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1061 break;
1062
1063 default:
1064 break;
1065 }
1066
1067 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001068 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001069 case glslang::ElfNone: return spv::ImageFormatUnknown;
1070 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1071 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1072 case glslang::ElfR32f: return spv::ImageFormatR32f;
1073 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1074 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1075 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1076 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1077 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1078 case glslang::ElfR16f: return spv::ImageFormatR16f;
1079 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1080 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1081 case glslang::ElfRg16: return spv::ImageFormatRg16;
1082 case glslang::ElfRg8: return spv::ImageFormatRg8;
1083 case glslang::ElfR16: return spv::ImageFormatR16;
1084 case glslang::ElfR8: return spv::ImageFormatR8;
1085 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1086 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1087 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1088 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1089 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1090 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1091 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1092 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1093 case glslang::ElfR32i: return spv::ImageFormatR32i;
1094 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1095 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1096 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1097 case glslang::ElfR16i: return spv::ImageFormatR16i;
1098 case glslang::ElfR8i: return spv::ImageFormatR8i;
1099 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1100 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1101 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1102 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1103 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1104 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1105 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1106 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1107 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1108 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001109 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001110 }
1111}
1112
John Kesseniche18fd202018-01-30 11:01:39 -07001113spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001114{
John Kesseniche18fd202018-01-30 11:01:39 -07001115 if (selectionNode.getFlatten())
1116 return spv::SelectionControlFlattenMask;
1117 if (selectionNode.getDontFlatten())
1118 return spv::SelectionControlDontFlattenMask;
1119 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001120}
1121
John Kesseniche18fd202018-01-30 11:01:39 -07001122spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001123{
John Kesseniche18fd202018-01-30 11:01:39 -07001124 if (switchNode.getFlatten())
1125 return spv::SelectionControlFlattenMask;
1126 if (switchNode.getDontFlatten())
1127 return spv::SelectionControlDontFlattenMask;
1128 return spv::SelectionControlMaskNone;
1129}
1130
John Kessenicha2858d92018-01-31 08:11:18 -07001131// return a non-0 dependency if the dependency argument must be set
1132spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001133 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001134{
1135 spv::LoopControlMask control = spv::LoopControlMaskNone;
1136
1137 if (loopNode.getDontUnroll())
1138 control = control | spv::LoopControlDontUnrollMask;
1139 if (loopNode.getUnroll())
1140 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001141 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001142 control = control | spv::LoopControlDependencyInfiniteMask;
1143 else if (loopNode.getLoopDependency() > 0) {
1144 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001145 operands.push_back((unsigned int)loopNode.getLoopDependency());
1146 }
1147 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1148 if (loopNode.getMinIterations() > 0) {
1149 control = control | spv::LoopControlMinIterationsMask;
1150 operands.push_back(loopNode.getMinIterations());
1151 }
1152 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1153 control = control | spv::LoopControlMaxIterationsMask;
1154 operands.push_back(loopNode.getMaxIterations());
1155 }
1156 if (loopNode.getIterationMultiple() > 1) {
1157 control = control | spv::LoopControlIterationMultipleMask;
1158 operands.push_back(loopNode.getIterationMultiple());
1159 }
1160 if (loopNode.getPeelCount() > 0) {
1161 control = control | spv::LoopControlPeelCountMask;
1162 operands.push_back(loopNode.getPeelCount());
1163 }
1164 if (loopNode.getPartialCount() > 0) {
1165 control = control | spv::LoopControlPartialCountMask;
1166 operands.push_back(loopNode.getPartialCount());
1167 }
John Kessenicha2858d92018-01-31 08:11:18 -07001168 }
John Kesseniche18fd202018-01-30 11:01:39 -07001169
1170 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001171}
1172
John Kessenicha5c5fb62017-05-05 05:09:58 -06001173// Translate glslang type to SPIR-V storage class.
1174spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1175{
1176 if (type.getQualifier().isPipeInput())
1177 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001178 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001179 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001180
1181 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001182 type.getQualifier().storage == glslang::EvqUniform) {
1183#ifndef GLSLANG_WEB
John Kessenichbed4e4f2017-09-08 02:38:07 -06001184 if (type.getBasicType() == glslang::EbtAtomicUint)
1185 return spv::StorageClassAtomicCounter;
John Kessenicha28f7a72019-08-06 07:00:58 -06001186#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001187 if (type.containsOpaque())
1188 return spv::StorageClassUniformConstant;
1189 }
1190
John Kessenicha28f7a72019-08-06 07:00:58 -06001191#ifndef GLSLANG_WEB
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001192 if (type.getQualifier().isUniformOrBuffer() &&
1193 type.getQualifier().layoutShaderRecordNV) {
1194 return spv::StorageClassShaderRecordBufferNV;
1195 }
1196#endif
1197
John Kessenichbed4e4f2017-09-08 02:38:07 -06001198 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001199 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001200 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001201 }
1202
1203 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha28f7a72019-08-06 07:00:58 -06001204#ifndef GLSLANG_WEB
John Kessenich7015bd62019-08-01 03:28:08 -06001205 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001206 return spv::StorageClassPushConstant;
John Kessenicha28f7a72019-08-06 07:00:58 -06001207#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001208 if (type.getBasicType() == glslang::EbtBlock)
1209 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001210 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001211 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001212
1213 switch (type.getQualifier().storage) {
John Kessenichbed4e4f2017-09-08 02:38:07 -06001214 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1215 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1216 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenicha28f7a72019-08-06 07:00:58 -06001217#ifndef GLSLANG_WEB
1218 case glslang::EvqShared: return spv::StorageClassWorkgroup;
Ashwin Leleff1783d2018-10-22 16:41:44 -07001219 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1220 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1221 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1222 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1223 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001224#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001225 default:
1226 assert(0);
1227 break;
1228 }
1229
1230 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001231}
1232
John Kessenich5611c6d2018-04-05 11:25:02 -06001233// Add capabilities pertaining to how an array is indexed.
1234void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1235 const glslang::TType& indexType)
1236{
John Kessenichb9197c82019-08-11 07:41:45 -06001237#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001238 if (indexType.getQualifier().isNonUniform()) {
1239 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001240 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001241 if (baseType.getBasicType() == glslang::EbtSampler) {
1242 if (baseType.getQualifier().hasAttachment())
1243 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001244 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001245 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001246 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001247 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1248 else if (baseType.isImage())
1249 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1250 else if (baseType.isTexture())
1251 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1252 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1253 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1254 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1255 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1256 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1257 }
1258 } else {
1259 // assume a dynamically uniform index
1260 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001261 if (baseType.getQualifier().hasAttachment()) {
1262 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001263 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001264 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001265 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001266 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001267 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001268 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001269 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001270 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 }
1272 }
John Kessenichb9197c82019-08-11 07:41:45 -06001273#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001274}
1275
qining25262b32016-05-06 17:25:16 -04001276// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001277// descriptor set.
1278bool IsDescriptorResource(const glslang::TType& type)
1279{
John Kessenichf7497e22016-03-08 21:36:22 -07001280 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001281 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001282 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001283 ! type.getQualifier().isShaderRecordNV() &&
1284 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001285
1286 // non block...
1287 // basically samplerXXX/subpass/sampler/texture are all included
1288 // if they are the global-scope-class, not the function parameter
1289 // (or local, if they ever exist) class.
1290 if (type.getBasicType() == glslang::EbtSampler)
1291 return type.getQualifier().isUniformOrBuffer();
1292
1293 // None of the above.
1294 return false;
1295}
1296
John Kesseniche0b6cad2015-12-24 10:30:13 -07001297void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1298{
1299 if (child.layoutMatrix == glslang::ElmNone)
1300 child.layoutMatrix = parent.layoutMatrix;
1301
1302 if (parent.invariant)
1303 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001304 if (parent.flat)
1305 child.flat = true;
1306 if (parent.centroid)
1307 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001308#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001309 if (parent.nopersp)
1310 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001311 if (parent.explicitInterp)
1312 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001313 if (parent.perPrimitiveNV)
1314 child.perPrimitiveNV = true;
1315 if (parent.perViewNV)
1316 child.perViewNV = true;
1317 if (parent.perTaskNV)
1318 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001319 if (parent.patch)
1320 child.patch = true;
1321 if (parent.sample)
1322 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001323 if (parent.coherent)
1324 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001325 if (parent.devicecoherent)
1326 child.devicecoherent = true;
1327 if (parent.queuefamilycoherent)
1328 child.queuefamilycoherent = true;
1329 if (parent.workgroupcoherent)
1330 child.workgroupcoherent = true;
1331 if (parent.subgroupcoherent)
1332 child.subgroupcoherent = true;
1333 if (parent.nonprivate)
1334 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001335 if (parent.volatil)
1336 child.volatil = true;
1337 if (parent.restrict)
1338 child.restrict = true;
1339 if (parent.readonly)
1340 child.readonly = true;
1341 if (parent.writeonly)
1342 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001343#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001344}
1345
John Kessenichf2b7f332016-09-01 17:05:23 -06001346bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001347{
John Kessenich7b9fa252016-01-21 18:56:57 -07001348 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001349 // - struct members might inherit from a struct declaration
1350 // (note that non-block structs don't explicitly inherit,
1351 // only implicitly, meaning no decoration involved)
1352 // - affect decorations on the struct members
1353 // (note smooth does not, and expecting something like volatile
1354 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001355 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001357}
1358
John Kessenich140f3df2015-06-26 16:58:36 -06001359//
1360// Implement the TGlslangToSpvTraverser class.
1361//
1362
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001363TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001364 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1365 : TIntermTraverser(true, false, true),
1366 options(options),
1367 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001368 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001369 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001370 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001371 glslangIntermediate(glslangIntermediate),
1372 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001373{
1374 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1375
1376 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001377 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1378 glslangIntermediate->getVersion());
1379
John Kessenich121853f2017-05-31 17:11:16 -06001380 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001381 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001382 builder.setSourceFile(glslangIntermediate->getSourceFile());
1383
1384 // Set the source shader's text. If for SPV version 1.0, include
1385 // a preamble in comments stating the OpModuleProcessed instructions.
1386 // Otherwise, emit those as actual instructions.
1387 std::string text;
1388 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1389 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001390 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001391 text.append("// OpModuleProcessed ");
1392 text.append(processes[p]);
1393 text.append("\n");
1394 } else
1395 builder.addModuleProcessed(processes[p]);
1396 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001397 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001398 text.append("#line 1\n");
1399 text.append(glslangIntermediate->getSourceText());
1400 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001401 // Pass name and text for all included files
1402 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1403 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1404 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001405 }
John Kessenich140f3df2015-06-26 16:58:36 -06001406 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001407
1408 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1409 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1410
1411 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1412 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1413 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1414 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1415 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001416 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001417 memoryModel = spv::MemoryModelVulkanKHR;
1418 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001419 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001420 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001421 builder.setMemoryModel(addressingModel, memoryModel);
1422
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001423 if (glslangIntermediate->usingVariablePointers()) {
1424 builder.addCapability(spv::CapabilityVariablePointers);
1425 }
1426
John Kessenicheee9d532016-09-19 18:09:30 -06001427 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1428 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001429
1430 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001431 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1432 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001433 builder.addSourceExtension(it->c_str());
1434
1435 // Add the top-level modes for this shader.
1436
John Kessenich92187592016-02-01 13:45:25 -07001437 if (glslangIntermediate->getXfbMode()) {
1438 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001439 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001440 }
John Kessenich140f3df2015-06-26 16:58:36 -06001441
1442 unsigned int mode;
1443 switch (glslangIntermediate->getStage()) {
1444 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001445 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 break;
1447
John Kessenicha28f7a72019-08-06 07:00:58 -06001448 case EShLangFragment:
1449 builder.addCapability(spv::CapabilityShader);
1450 if (glslangIntermediate->getPixelCenterInteger())
1451 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1452
1453 if (glslangIntermediate->getOriginUpperLeft())
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1455 else
1456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1457
1458 if (glslangIntermediate->getEarlyFragmentTests())
1459 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1460
1461 if (glslangIntermediate->getPostDepthCoverage()) {
1462 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1464 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1465 }
1466
John Kessenichb9197c82019-08-11 07:41:45 -06001467 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1469
1470#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001471 switch(glslangIntermediate->getDepth()) {
1472 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1473 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1474 default: mode = spv::ExecutionModeMax; break;
1475 }
1476 if (mode != spv::ExecutionModeMax)
1477 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001478 switch (glslangIntermediate->getInterlockOrdering()) {
1479 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1480 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1481 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1482 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1483 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1484 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1485 default: mode = spv::ExecutionModeMax; break;
1486 }
1487 if (mode != spv::ExecutionModeMax) {
1488 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1489 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1490 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1491 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1492 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1493 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1494 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1495 } else {
1496 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1497 }
1498 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1499 }
John Kessenichb9197c82019-08-11 07:41:45 -06001500#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001501 break;
1502
1503#ifndef GLSLANG_WEB
1504 case EShLangCompute:
1505 builder.addCapability(spv::CapabilityShader);
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1507 glslangIntermediate->getLocalSize(1),
1508 glslangIntermediate->getLocalSize(2));
1509 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1510 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1511 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1512 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1513 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1514 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1515 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1516 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1517 }
1518 break;
steve-lunarge7412492017-03-23 11:56:07 -06001519 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001520 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001521 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001522
steve-lunarge7412492017-03-23 11:56:07 -06001523 glslang::TLayoutGeometry primitive;
1524
1525 if (glslangIntermediate->getStage() == EShLangTessControl) {
1526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1527 primitive = glslangIntermediate->getOutputPrimitive();
1528 } else {
1529 primitive = glslangIntermediate->getInputPrimitive();
1530 }
1531
1532 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001533 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1534 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1535 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001536 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001537 }
John Kessenich4016e382016-07-15 11:53:56 -06001538 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001539 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1540
John Kesseniche6903322015-10-13 16:29:02 -06001541 switch (glslangIntermediate->getVertexSpacing()) {
1542 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1543 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1544 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001545 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001546 }
John Kessenich4016e382016-07-15 11:53:56 -06001547 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001548 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1549
1550 switch (glslangIntermediate->getVertexOrder()) {
1551 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1552 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001553 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001554 }
John Kessenich4016e382016-07-15 11:53:56 -06001555 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001556 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1557
1558 if (glslangIntermediate->getPointMode())
1559 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001560 break;
1561
1562 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001563 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001564 switch (glslangIntermediate->getInputPrimitive()) {
1565 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1566 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1567 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001568 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001569 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001570 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001571 }
John Kessenich4016e382016-07-15 11:53:56 -06001572 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001573 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001574
John Kessenich140f3df2015-06-26 16:58:36 -06001575 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1576
1577 switch (glslangIntermediate->getOutputPrimitive()) {
1578 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1579 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1580 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001581 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001582 }
John Kessenich4016e382016-07-15 11:53:56 -06001583 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001584 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1585 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1586 break;
1587
Chao Chenb50c02e2018-09-19 11:42:24 -07001588 case EShLangRayGenNV:
1589 case EShLangIntersectNV:
1590 case EShLangAnyHitNV:
1591 case EShLangClosestHitNV:
1592 case EShLangMissNV:
1593 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001594 builder.addCapability(spv::CapabilityRayTracingNV);
1595 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001596 break;
Chao Chen3c366992018-09-19 11:41:59 -07001597 case EShLangTaskNV:
1598 case EShLangMeshNV:
1599 builder.addCapability(spv::CapabilityMeshShadingNV);
1600 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1601 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1602 glslangIntermediate->getLocalSize(1),
1603 glslangIntermediate->getLocalSize(2));
1604 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1605 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1606 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1607
1608 switch (glslangIntermediate->getOutputPrimitive()) {
1609 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1610 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1611 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1612 default: mode = spv::ExecutionModeMax; break;
1613 }
1614 if (mode != spv::ExecutionModeMax)
1615 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1616 }
1617 break;
1618#endif
1619
John Kessenich140f3df2015-06-26 16:58:36 -06001620 default:
1621 break;
1622 }
John Kessenich140f3df2015-06-26 16:58:36 -06001623}
1624
John Kessenichfca82622016-11-26 13:23:20 -07001625// Finish creating SPV, after the traversal is complete.
1626void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001627{
John Kessenichf04c51b2018-08-03 15:56:12 -06001628 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001629 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001630 builder.setBuildPoint(shaderEntry->getLastBlock());
1631 builder.leaveFunction();
1632 }
1633
John Kessenich7ba63412015-12-20 17:37:07 -07001634 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001635 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1636 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001637
John Kessenich23d27752019-07-28 02:12:10 -06001638#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001639 // Add capabilities, extensions, remove unneeded decorations, etc.,
1640 // based on the resulting SPIR-V.
1641 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001642#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001643}
1644
John Kessenichfca82622016-11-26 13:23:20 -07001645// Write the SPV into 'out'.
1646void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001647{
John Kessenichfca82622016-11-26 13:23:20 -07001648 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001649}
1650
1651//
1652// Implement the traversal functions.
1653//
1654// Return true from interior nodes to have the external traversal
1655// continue on to children. Return false if children were
1656// already processed.
1657//
1658
1659//
qining25262b32016-05-06 17:25:16 -04001660// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001661// - uniform/input reads
1662// - output writes
1663// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1664// - something simple that degenerates into the last bullet
1665//
1666void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1667{
qining75d1d802016-04-06 14:42:01 -04001668 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1669 if (symbol->getType().getQualifier().isSpecConstant())
1670 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1671
John Kessenich140f3df2015-06-26 16:58:36 -06001672 // getSymbolId() will set up all the IO decorations on the first call.
1673 // Formal function parameters were mapped during makeFunctions().
1674 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001675
John Kessenich7ba63412015-12-20 17:37:07 -07001676 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001677 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001678 // Consider adding to the OpEntryPoint interface list.
1679 // Only looking at structures if they have at least one member.
1680 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1681 spv::StorageClass sc = builder.getStorageClass(id);
1682 // Before SPIR-V 1.4, we only want to include Input and Output.
1683 // Starting with SPIR-V 1.4, we want all globals.
1684 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1685 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001686 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001687 }
John Kessenich5f77d862017-09-19 11:09:59 -06001688 }
John Kessenich9c14f772019-06-17 08:38:35 -06001689
1690 // If the SPIR-V type is required to be different than the AST type,
1691 // translate now from the SPIR-V type to the AST type, for the consuming
1692 // operation.
1693 // Note this turns it from an l-value to an r-value.
1694 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1695 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1696 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001697 }
1698
1699 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001700 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001701 // Prepare to generate code for the access
1702
1703 // L-value chains will be computed left to right. We're on the symbol now,
1704 // which is the left-most part of the access chain, so now is "clear" time,
1705 // followed by setting the base.
1706 builder.clearAccessChain();
1707
1708 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001709 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001710 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001711 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001712 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001713 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001714 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001715 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001716 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1717 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001718 builder.setAccessChainRValue(id);
1719 else
1720 builder.setAccessChainLValue(id);
1721 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001722
John Kessenichb9197c82019-08-11 07:41:45 -06001723#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001724 // Process linkage-only nodes for any special additional interface work.
1725 if (linkageOnly) {
1726 if (glslangIntermediate->getHlslFunctionality1()) {
1727 // Map implicit counter buffers to their originating buffers, which should have been
1728 // seen by now, given earlier pruning of unused counters, and preservation of order
1729 // of declaration.
1730 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1731 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1732 // Save possible originating buffers for counter buffers, keyed by
1733 // making the potential counter-buffer name.
1734 std::string keyName = symbol->getName().c_str();
1735 keyName = glslangIntermediate->addCounterBufferName(keyName);
1736 counterOriginator[keyName] = symbol;
1737 } else {
1738 // Handle a counter buffer, by finding the saved originating buffer.
1739 std::string keyName = symbol->getName().c_str();
1740 auto it = counterOriginator.find(keyName);
1741 if (it != counterOriginator.end()) {
1742 id = getSymbolId(it->second);
1743 if (id != spv::NoResult) {
1744 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001745 if (counterId != spv::NoResult) {
1746 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001747 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001748 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001749 }
1750 }
1751 }
1752 }
1753 }
1754 }
John Kessenich155d3512019-08-08 23:29:20 -06001755#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001756}
1757
1758bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1759{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001760 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001761
qining40887662016-04-03 22:20:42 -04001762 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1763 if (node->getType().getQualifier().isSpecConstant())
1764 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1765
John Kessenich140f3df2015-06-26 16:58:36 -06001766 // First, handle special cases
1767 switch (node->getOp()) {
1768 case glslang::EOpAssign:
1769 case glslang::EOpAddAssign:
1770 case glslang::EOpSubAssign:
1771 case glslang::EOpMulAssign:
1772 case glslang::EOpVectorTimesMatrixAssign:
1773 case glslang::EOpVectorTimesScalarAssign:
1774 case glslang::EOpMatrixTimesScalarAssign:
1775 case glslang::EOpMatrixTimesMatrixAssign:
1776 case glslang::EOpDivAssign:
1777 case glslang::EOpModAssign:
1778 case glslang::EOpAndAssign:
1779 case glslang::EOpInclusiveOrAssign:
1780 case glslang::EOpExclusiveOrAssign:
1781 case glslang::EOpLeftShiftAssign:
1782 case glslang::EOpRightShiftAssign:
1783 // A bin-op assign "a += b" means the same thing as "a = a + b"
1784 // where a is evaluated before b. For a simple assignment, GLSL
1785 // says to evaluate the left before the right. So, always, left
1786 // node then right node.
1787 {
1788 // get the left l-value, save it away
1789 builder.clearAccessChain();
1790 node->getLeft()->traverse(this);
1791 spv::Builder::AccessChain lValue = builder.getAccessChain();
1792
1793 // evaluate the right
1794 builder.clearAccessChain();
1795 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001796 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001797
1798 if (node->getOp() != glslang::EOpAssign) {
1799 // the left is also an r-value
1800 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001801 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001802
1803 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001804 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001805 TranslateNoContractionDecoration(node->getType().getQualifier()),
1806 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001807 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001808 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1809 node->getType().getBasicType());
1810
1811 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001812 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001813 }
1814
1815 // store the result
1816 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001817 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001818
1819 // assignments are expressions having an rValue after they are evaluated...
1820 builder.clearAccessChain();
1821 builder.setAccessChainRValue(rValue);
1822 }
1823 return false;
1824 case glslang::EOpIndexDirect:
1825 case glslang::EOpIndexDirectStruct:
1826 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001827 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001828 // Get the left part of the access chain.
1829 node->getLeft()->traverse(this);
1830
1831 // Add the next element in the chain
1832
David Netoa901ffe2016-06-08 14:11:40 +01001833 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001834 if (! node->getLeft()->getType().isArray() &&
1835 node->getLeft()->getType().isVector() &&
1836 node->getOp() == glslang::EOpIndexDirect) {
1837 // This is essentially a hard-coded vector swizzle of size 1,
1838 // so short circuit the access-chain stuff with a swizzle.
1839 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001840 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001841 int dummySize;
1842 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1843 TranslateCoherent(node->getLeft()->getType()),
1844 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001845 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001846
1847 // Load through a block reference is performed with a dot operator that
1848 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1849 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001850 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001851 !node->getLeft()->getType().isArray() &&
1852 node->getOp() == glslang::EOpIndexDirectStruct)
1853 {
1854 spv::Id left = accessChainLoad(node->getLeft()->getType());
1855 builder.clearAccessChain();
1856 builder.setAccessChainLValue(left);
1857 }
1858
David Netoa901ffe2016-06-08 14:11:40 +01001859 int spvIndex = glslangIndex;
1860 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1861 node->getOp() == glslang::EOpIndexDirectStruct)
1862 {
1863 // This may be, e.g., an anonymous block-member selection, which generally need
1864 // index remapping due to hidden members in anonymous blocks.
1865 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1866 assert(remapper.size() > 0);
1867 spvIndex = remapper[glslangIndex];
1868 }
John Kessenichebb50532016-05-16 19:22:05 -06001869
David Netoa901ffe2016-06-08 14:11:40 +01001870 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001871 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001872
1873 // Add capabilities here for accessing PointSize and clip/cull distance.
1874 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001875 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001876 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001877 }
1878 }
1879 return false;
1880 case glslang::EOpIndexIndirect:
1881 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001882 // Array, matrix, or vector indirection with variable index.
1883 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001884 // matrices are arrays of vectors, so will also work for a matrix.
1885 // Will use the access chain's 'component' for variable index into a vector.
1886
1887 // This adapter is building access chains left to right.
1888 // Set up the access chain to the left.
1889 node->getLeft()->traverse(this);
1890
1891 // save it so that computing the right side doesn't trash it
1892 spv::Builder::AccessChain partial = builder.getAccessChain();
1893
1894 // compute the next index in the chain
1895 builder.clearAccessChain();
1896 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001897 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001898
John Kessenich5611c6d2018-04-05 11:25:02 -06001899 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1900
John Kessenich140f3df2015-06-26 16:58:36 -06001901 // restore the saved access chain
1902 builder.setAccessChain(partial);
1903
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001904 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1905 int dummySize;
1906 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1907 TranslateCoherent(node->getLeft()->getType()),
1908 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1909 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001910 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001911 }
1912 return false;
1913 case glslang::EOpVectorSwizzle:
1914 {
1915 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001916 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001917 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001918 int dummySize;
1919 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1920 TranslateCoherent(node->getLeft()->getType()),
1921 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001922 }
1923 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001924 case glslang::EOpMatrixSwizzle:
1925 logger->missingFunctionality("matrix swizzle");
1926 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001927 case glslang::EOpLogicalOr:
1928 case glslang::EOpLogicalAnd:
1929 {
1930
1931 // These may require short circuiting, but can sometimes be done as straight
1932 // binary operations. The right operand must be short circuited if it has
1933 // side effects, and should probably be if it is complex.
1934 if (isTrivial(node->getRight()->getAsTyped()))
1935 break; // handle below as a normal binary operation
1936 // otherwise, we need to do dynamic short circuiting on the right operand
1937 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1938 builder.clearAccessChain();
1939 builder.setAccessChainRValue(result);
1940 }
1941 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001942 default:
1943 break;
1944 }
1945
1946 // Assume generic binary op...
1947
John Kessenich32cfd492016-02-02 12:37:46 -07001948 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001949 builder.clearAccessChain();
1950 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001951 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001952
John Kessenich32cfd492016-02-02 12:37:46 -07001953 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001954 builder.clearAccessChain();
1955 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001956 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001957
John Kessenich32cfd492016-02-02 12:37:46 -07001958 // get result
John Kessenichead86222018-03-28 18:01:20 -06001959 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001960 TranslateNoContractionDecoration(node->getType().getQualifier()),
1961 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001962 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001963 convertGlslangToSpvType(node->getType()), left, right,
1964 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001965
John Kessenich50e57562015-12-21 21:21:11 -07001966 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001967 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001968 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001969 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001970 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001971 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001972 return false;
1973 }
John Kessenich140f3df2015-06-26 16:58:36 -06001974}
1975
John Kessenich9c14f772019-06-17 08:38:35 -06001976// Figure out what, if any, type changes are needed when accessing a specific built-in.
1977// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1978// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1979std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1980 const glslang::TType& glslangType)
1981{
1982 switch(builtIn)
1983 {
1984 case spv::BuiltInSubgroupEqMask:
1985 case spv::BuiltInSubgroupGeMask:
1986 case spv::BuiltInSubgroupGtMask:
1987 case spv::BuiltInSubgroupLeMask:
1988 case spv::BuiltInSubgroupLtMask: {
1989 // these require changing a 64-bit scaler -> a vector of 32-bit components
1990 if (glslangType.isVector())
1991 break;
1992 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1993 builder.makeUintType(64));
1994 return ret;
1995 }
1996 default:
1997 break;
1998 }
1999
2000 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2001 return ret;
2002}
2003
2004// For an object previously identified (see getForcedType() and forceType)
2005// as needing type translations, do the translation needed for a load, turning
2006// an L-value into in R-value.
2007spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2008{
2009 const auto forceIt = forceType.find(object);
2010 if (forceIt == forceType.end())
2011 return object;
2012
2013 spv::Id desiredTypeId = forceIt->second;
2014 spv::Id objectTypeId = builder.getTypeId(object);
2015 assert(builder.isPointerType(objectTypeId));
2016 objectTypeId = builder.getContainedTypeId(objectTypeId);
2017 if (builder.isVectorType(objectTypeId) &&
2018 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2019 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2020 // handle 32-bit v.xy* -> 64-bit
2021 builder.clearAccessChain();
2022 builder.setAccessChainLValue(object);
2023 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2024 std::vector<spv::Id> components;
2025 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2026 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2027
2028 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2029 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2030 builder.createCompositeConstruct(vecType, components));
2031 } else {
2032 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2033 }
2034 } else {
2035 logger->missingFunctionality("forcing non 32-bit vector type");
2036 }
2037
2038 return object;
2039}
2040
John Kessenich140f3df2015-06-26 16:58:36 -06002041bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2042{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002043 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002044
qining40887662016-04-03 22:20:42 -04002045 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2046 if (node->getType().getQualifier().isSpecConstant())
2047 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2048
John Kessenichfc51d282015-08-19 13:34:18 -06002049 spv::Id result = spv::NoResult;
2050
2051 // try texturing first
2052 result = createImageTextureFunctionCall(node);
2053 if (result != spv::NoResult) {
2054 builder.clearAccessChain();
2055 builder.setAccessChainRValue(result);
2056
2057 return false; // done with this node
2058 }
2059
2060 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002061
2062 if (node->getOp() == glslang::EOpArrayLength) {
2063 // Quite special; won't want to evaluate the operand.
2064
John Kessenich5611c6d2018-04-05 11:25:02 -06002065 // Currently, the front-end does not allow .length() on an array until it is sized,
2066 // except for the last block membeor of an SSBO.
2067 // TODO: If this changes, link-time sized arrays might show up here, and need their
2068 // size extracted.
2069
John Kessenichc9a80832015-09-12 12:17:44 -06002070 // Normal .length() would have been constant folded by the front-end.
2071 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002072 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002073
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002074 spv::Id length;
2075 if (node->getOperand()->getType().isCoopMat()) {
2076 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2077
2078 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2079 assert(builder.isCooperativeMatrixType(typeId));
2080
2081 length = builder.createCooperativeMatrixLength(typeId);
2082 } else {
2083 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2084 block->traverse(this);
2085 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2086 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2087 }
John Kessenichc9a80832015-09-12 12:17:44 -06002088
John Kessenich8c869672018-11-28 07:01:37 -07002089 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2090 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2091 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002092 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2093 if (builder.isInSpecConstCodeGenMode()) {
2094 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2095 } else {
2096 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2097 }
2098 }
John Kessenich8c869672018-11-28 07:01:37 -07002099
John Kessenichc9a80832015-09-12 12:17:44 -06002100 builder.clearAccessChain();
2101 builder.setAccessChainRValue(length);
2102
2103 return false;
2104 }
2105
John Kessenichfc51d282015-08-19 13:34:18 -06002106 // Start by evaluating the operand
2107
John Kessenich8c8505c2016-07-26 12:50:38 -06002108 // Does it need a swizzle inversion? If so, evaluation is inverted;
2109 // operate first on the swizzle base, then apply the swizzle.
2110 spv::Id invertedType = spv::NoType;
2111 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2112 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2113 invertedType = getInvertedSwizzleType(*node->getOperand());
2114
John Kessenich140f3df2015-06-26 16:58:36 -06002115 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002116 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002117 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002118 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002119 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002120 operandNode = node->getOperand();
2121
2122 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002123
Rex Xufc618912015-09-09 16:42:49 +08002124 spv::Id operand = spv::NoResult;
2125
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002126 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2127
John Kessenichfb4f2332019-08-09 03:49:15 -06002128#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002129 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2130 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002131 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002132 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002133 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002134 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2135 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2136 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002137#endif
2138 {
John Kessenich32cfd492016-02-02 12:37:46 -07002139 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002140 }
John Kessenich140f3df2015-06-26 16:58:36 -06002141
John Kessenichead86222018-03-28 18:01:20 -06002142 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002143 TranslateNoContractionDecoration(node->getType().getQualifier()),
2144 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002145
2146 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002147 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002148 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002149
2150 // if not, then possibly an operation
2151 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002152 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002153
2154 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002155 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002156 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002157 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002158 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002159
John Kessenich140f3df2015-06-26 16:58:36 -06002160 builder.clearAccessChain();
2161 builder.setAccessChainRValue(result);
2162
2163 return false; // done with this node
2164 }
2165
2166 // it must be a special case, check...
2167 switch (node->getOp()) {
2168 case glslang::EOpPostIncrement:
2169 case glslang::EOpPostDecrement:
2170 case glslang::EOpPreIncrement:
2171 case glslang::EOpPreDecrement:
2172 {
2173 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002174 spv::Id one = 0;
2175 if (node->getBasicType() == glslang::EbtFloat)
2176 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002177#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002178 else if (node->getBasicType() == glslang::EbtDouble)
2179 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002180 else if (node->getBasicType() == glslang::EbtFloat16)
2181 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002182 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2183 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002184 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2185 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002186 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2187 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002188#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002189 else
2190 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002191 glslang::TOperator op;
2192 if (node->getOp() == glslang::EOpPreIncrement ||
2193 node->getOp() == glslang::EOpPostIncrement)
2194 op = glslang::EOpAdd;
2195 else
2196 op = glslang::EOpSub;
2197
John Kessenichead86222018-03-28 18:01:20 -06002198 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002199 convertGlslangToSpvType(node->getType()), operand, one,
2200 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002201 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002202
2203 // The result of operation is always stored, but conditionally the
2204 // consumed result. The consumed result is always an r-value.
2205 builder.accessChainStore(result);
2206 builder.clearAccessChain();
2207 if (node->getOp() == glslang::EOpPreIncrement ||
2208 node->getOp() == glslang::EOpPreDecrement)
2209 builder.setAccessChainRValue(result);
2210 else
2211 builder.setAccessChainRValue(operand);
2212 }
2213
2214 return false;
2215
John Kessenich155d3512019-08-08 23:29:20 -06002216#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002217 case glslang::EOpEmitStreamVertex:
2218 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2219 return false;
2220 case glslang::EOpEndStreamPrimitive:
2221 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2222 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002223#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002224
2225 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002226 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002227 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002228 }
John Kessenich140f3df2015-06-26 16:58:36 -06002229}
2230
Jeff Bolz53134492019-06-25 13:31:10 -05002231// Construct a composite object, recursively copying members if their types don't match
2232spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2233{
2234 for (int c = 0; c < (int)constituents.size(); ++c) {
2235 spv::Id& constituent = constituents[c];
2236 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2237 spv::Id rType = builder.getTypeId(constituent);
2238 if (lType != rType) {
2239 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2240 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2241 } else if (builder.isStructType(rType)) {
2242 std::vector<spv::Id> rTypeConstituents;
2243 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2244 for (int i = 0; i < numrTypeConstituents; ++i) {
2245 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2246 }
2247 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2248 } else {
2249 assert(builder.isArrayType(rType));
2250 std::vector<spv::Id> rTypeConstituents;
2251 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2252
2253 spv::Id elementRType = builder.getContainedTypeId(rType);
2254 for (int i = 0; i < numrTypeConstituents; ++i) {
2255 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2256 }
2257 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2258 }
2259 }
2260 }
2261 return builder.createCompositeConstruct(resultTypeId, constituents);
2262}
2263
John Kessenich140f3df2015-06-26 16:58:36 -06002264bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2265{
qining27e04a02016-04-14 16:40:20 -04002266 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2267 if (node->getType().getQualifier().isSpecConstant())
2268 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2269
John Kessenichfc51d282015-08-19 13:34:18 -06002270 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002271 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2272 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002273
2274 // try texturing
2275 result = createImageTextureFunctionCall(node);
2276 if (result != spv::NoResult) {
2277 builder.clearAccessChain();
2278 builder.setAccessChainRValue(result);
2279
2280 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002281 }
2282#ifndef GLSLANG_WEB
2283 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002284 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002285 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002286 // "imageStore" is a special case, which has no result
2287 return false;
2288 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002289#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002290
John Kessenich140f3df2015-06-26 16:58:36 -06002291 glslang::TOperator binOp = glslang::EOpNull;
2292 bool reduceComparison = true;
2293 bool isMatrix = false;
2294 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002295 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002296
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002297 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2298
John Kessenich140f3df2015-06-26 16:58:36 -06002299 assert(node->getOp());
2300
John Kessenichf6640762016-08-01 19:44:00 -06002301 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002302
2303 switch (node->getOp()) {
2304 case glslang::EOpSequence:
2305 {
2306 if (preVisit)
2307 ++sequenceDepth;
2308 else
2309 --sequenceDepth;
2310
2311 if (sequenceDepth == 1) {
2312 // If this is the parent node of all the functions, we want to see them
2313 // early, so all call points have actual SPIR-V functions to reference.
2314 // In all cases, still let the traverser visit the children for us.
2315 makeFunctions(node->getAsAggregate()->getSequence());
2316
John Kessenich6fccb3c2016-09-19 16:01:41 -06002317 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002318 // anything else gets there, so visit out of order, doing them all now.
2319 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2320
John Kessenich6a60c2f2016-12-08 21:01:59 -07002321 // 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 -06002322 // so do them manually.
2323 visitFunctions(node->getAsAggregate()->getSequence());
2324
2325 return false;
2326 }
2327
2328 return true;
2329 }
2330 case glslang::EOpLinkerObjects:
2331 {
2332 if (visit == glslang::EvPreVisit)
2333 linkageOnly = true;
2334 else
2335 linkageOnly = false;
2336
2337 return true;
2338 }
2339 case glslang::EOpComma:
2340 {
2341 // processing from left to right naturally leaves the right-most
2342 // lying around in the access chain
2343 glslang::TIntermSequence& glslangOperands = node->getSequence();
2344 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2345 glslangOperands[i]->traverse(this);
2346
2347 return false;
2348 }
2349 case glslang::EOpFunction:
2350 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002351 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002352 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002353 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002354 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002355 } else {
2356 handleFunctionEntry(node);
2357 }
2358 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002359 if (inEntryPoint)
2360 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002361 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002362 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002363 }
2364
2365 return true;
2366 case glslang::EOpParameters:
2367 // Parameters will have been consumed by EOpFunction processing, but not
2368 // the body, so we still visited the function node's children, making this
2369 // child redundant.
2370 return false;
2371 case glslang::EOpFunctionCall:
2372 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002373 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002374 if (node->isUserDefined())
2375 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002376 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002377 if (result) {
2378 builder.clearAccessChain();
2379 builder.setAccessChainRValue(result);
2380 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002381 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002382
2383 return false;
2384 }
2385 case glslang::EOpConstructMat2x2:
2386 case glslang::EOpConstructMat2x3:
2387 case glslang::EOpConstructMat2x4:
2388 case glslang::EOpConstructMat3x2:
2389 case glslang::EOpConstructMat3x3:
2390 case glslang::EOpConstructMat3x4:
2391 case glslang::EOpConstructMat4x2:
2392 case glslang::EOpConstructMat4x3:
2393 case glslang::EOpConstructMat4x4:
2394 case glslang::EOpConstructDMat2x2:
2395 case glslang::EOpConstructDMat2x3:
2396 case glslang::EOpConstructDMat2x4:
2397 case glslang::EOpConstructDMat3x2:
2398 case glslang::EOpConstructDMat3x3:
2399 case glslang::EOpConstructDMat3x4:
2400 case glslang::EOpConstructDMat4x2:
2401 case glslang::EOpConstructDMat4x3:
2402 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002403 case glslang::EOpConstructIMat2x2:
2404 case glslang::EOpConstructIMat2x3:
2405 case glslang::EOpConstructIMat2x4:
2406 case glslang::EOpConstructIMat3x2:
2407 case glslang::EOpConstructIMat3x3:
2408 case glslang::EOpConstructIMat3x4:
2409 case glslang::EOpConstructIMat4x2:
2410 case glslang::EOpConstructIMat4x3:
2411 case glslang::EOpConstructIMat4x4:
2412 case glslang::EOpConstructUMat2x2:
2413 case glslang::EOpConstructUMat2x3:
2414 case glslang::EOpConstructUMat2x4:
2415 case glslang::EOpConstructUMat3x2:
2416 case glslang::EOpConstructUMat3x3:
2417 case glslang::EOpConstructUMat3x4:
2418 case glslang::EOpConstructUMat4x2:
2419 case glslang::EOpConstructUMat4x3:
2420 case glslang::EOpConstructUMat4x4:
2421 case glslang::EOpConstructBMat2x2:
2422 case glslang::EOpConstructBMat2x3:
2423 case glslang::EOpConstructBMat2x4:
2424 case glslang::EOpConstructBMat3x2:
2425 case glslang::EOpConstructBMat3x3:
2426 case glslang::EOpConstructBMat3x4:
2427 case glslang::EOpConstructBMat4x2:
2428 case glslang::EOpConstructBMat4x3:
2429 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002430 case glslang::EOpConstructF16Mat2x2:
2431 case glslang::EOpConstructF16Mat2x3:
2432 case glslang::EOpConstructF16Mat2x4:
2433 case glslang::EOpConstructF16Mat3x2:
2434 case glslang::EOpConstructF16Mat3x3:
2435 case glslang::EOpConstructF16Mat3x4:
2436 case glslang::EOpConstructF16Mat4x2:
2437 case glslang::EOpConstructF16Mat4x3:
2438 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002439 isMatrix = true;
2440 // fall through
2441 case glslang::EOpConstructFloat:
2442 case glslang::EOpConstructVec2:
2443 case glslang::EOpConstructVec3:
2444 case glslang::EOpConstructVec4:
2445 case glslang::EOpConstructDouble:
2446 case glslang::EOpConstructDVec2:
2447 case glslang::EOpConstructDVec3:
2448 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002449 case glslang::EOpConstructFloat16:
2450 case glslang::EOpConstructF16Vec2:
2451 case glslang::EOpConstructF16Vec3:
2452 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002453 case glslang::EOpConstructBool:
2454 case glslang::EOpConstructBVec2:
2455 case glslang::EOpConstructBVec3:
2456 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002457 case glslang::EOpConstructInt8:
2458 case glslang::EOpConstructI8Vec2:
2459 case glslang::EOpConstructI8Vec3:
2460 case glslang::EOpConstructI8Vec4:
2461 case glslang::EOpConstructUint8:
2462 case glslang::EOpConstructU8Vec2:
2463 case glslang::EOpConstructU8Vec3:
2464 case glslang::EOpConstructU8Vec4:
2465 case glslang::EOpConstructInt16:
2466 case glslang::EOpConstructI16Vec2:
2467 case glslang::EOpConstructI16Vec3:
2468 case glslang::EOpConstructI16Vec4:
2469 case glslang::EOpConstructUint16:
2470 case glslang::EOpConstructU16Vec2:
2471 case glslang::EOpConstructU16Vec3:
2472 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002473 case glslang::EOpConstructInt:
2474 case glslang::EOpConstructIVec2:
2475 case glslang::EOpConstructIVec3:
2476 case glslang::EOpConstructIVec4:
2477 case glslang::EOpConstructUint:
2478 case glslang::EOpConstructUVec2:
2479 case glslang::EOpConstructUVec3:
2480 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002481 case glslang::EOpConstructInt64:
2482 case glslang::EOpConstructI64Vec2:
2483 case glslang::EOpConstructI64Vec3:
2484 case glslang::EOpConstructI64Vec4:
2485 case glslang::EOpConstructUint64:
2486 case glslang::EOpConstructU64Vec2:
2487 case glslang::EOpConstructU64Vec3:
2488 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002489 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002490 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002491 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002492 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002493 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002494 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002495 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002496 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002497 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002498 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002499 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002500 else if (node->getOp() == glslang::EOpConstructStruct ||
2501 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2502 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002503 std::vector<spv::Id> constituents;
2504 for (int c = 0; c < (int)arguments.size(); ++c)
2505 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002506 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002507 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002508 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002509 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002510 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002511
2512 builder.clearAccessChain();
2513 builder.setAccessChainRValue(constructed);
2514
2515 return false;
2516 }
2517
2518 // These six are component-wise compares with component-wise results.
2519 // Forward on to createBinaryOperation(), requesting a vector result.
2520 case glslang::EOpLessThan:
2521 case glslang::EOpGreaterThan:
2522 case glslang::EOpLessThanEqual:
2523 case glslang::EOpGreaterThanEqual:
2524 case glslang::EOpVectorEqual:
2525 case glslang::EOpVectorNotEqual:
2526 {
2527 // Map the operation to a binary
2528 binOp = node->getOp();
2529 reduceComparison = false;
2530 switch (node->getOp()) {
2531 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2532 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2533 default: binOp = node->getOp(); break;
2534 }
2535
2536 break;
2537 }
2538 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002539 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002540 binOp = glslang::EOpMul;
2541 break;
2542 case glslang::EOpOuterProduct:
2543 // two vectors multiplied to make a matrix
2544 binOp = glslang::EOpOuterProduct;
2545 break;
2546 case glslang::EOpDot:
2547 {
qining25262b32016-05-06 17:25:16 -04002548 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002549 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002550 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002551 binOp = glslang::EOpMul;
2552 break;
2553 }
2554 case glslang::EOpMod:
2555 // when an aggregate, this is the floating-point mod built-in function,
2556 // which can be emitted by the one in createBinaryOperation()
2557 binOp = glslang::EOpMod;
2558 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002559
2560#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002561 case glslang::EOpEmitVertex:
2562 case glslang::EOpEndPrimitive:
2563 case glslang::EOpBarrier:
2564 case glslang::EOpMemoryBarrier:
2565 case glslang::EOpMemoryBarrierAtomicCounter:
2566 case glslang::EOpMemoryBarrierBuffer:
2567 case glslang::EOpMemoryBarrierImage:
2568 case glslang::EOpMemoryBarrierShared:
2569 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002570 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002571 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002572 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002573 case glslang::EOpWorkgroupMemoryBarrier:
2574 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002575 case glslang::EOpSubgroupBarrier:
2576 case glslang::EOpSubgroupMemoryBarrier:
2577 case glslang::EOpSubgroupMemoryBarrierBuffer:
2578 case glslang::EOpSubgroupMemoryBarrierImage:
2579 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002580 noReturnValue = true;
2581 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2582 break;
2583
Jeff Bolz36831c92018-09-05 10:11:41 -05002584 case glslang::EOpAtomicStore:
2585 noReturnValue = true;
2586 // fallthrough
2587 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002588 case glslang::EOpAtomicAdd:
2589 case glslang::EOpAtomicMin:
2590 case glslang::EOpAtomicMax:
2591 case glslang::EOpAtomicAnd:
2592 case glslang::EOpAtomicOr:
2593 case glslang::EOpAtomicXor:
2594 case glslang::EOpAtomicExchange:
2595 case glslang::EOpAtomicCompSwap:
2596 atomic = true;
2597 break;
2598
John Kessenich0d0c6d32017-07-23 16:08:26 -06002599 case glslang::EOpAtomicCounterAdd:
2600 case glslang::EOpAtomicCounterSubtract:
2601 case glslang::EOpAtomicCounterMin:
2602 case glslang::EOpAtomicCounterMax:
2603 case glslang::EOpAtomicCounterAnd:
2604 case glslang::EOpAtomicCounterOr:
2605 case glslang::EOpAtomicCounterXor:
2606 case glslang::EOpAtomicCounterExchange:
2607 case glslang::EOpAtomicCounterCompSwap:
2608 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2609 builder.addCapability(spv::CapabilityAtomicStorageOps);
2610 atomic = true;
2611 break;
2612
Chao Chenb50c02e2018-09-19 11:42:24 -07002613 case glslang::EOpIgnoreIntersectionNV:
2614 case glslang::EOpTerminateRayNV:
2615 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002616 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002617 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2618 noReturnValue = true;
2619 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002620 case glslang::EOpCooperativeMatrixLoad:
2621 case glslang::EOpCooperativeMatrixStore:
2622 noReturnValue = true;
2623 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002624 case glslang::EOpBeginInvocationInterlock:
2625 case glslang::EOpEndInvocationInterlock:
2626 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2627 noReturnValue = true;
2628 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002629#endif
Chao Chen3c366992018-09-19 11:41:59 -07002630
John Kessenich140f3df2015-06-26 16:58:36 -06002631 default:
2632 break;
2633 }
2634
2635 //
2636 // See if it maps to a regular operation.
2637 //
John Kessenich140f3df2015-06-26 16:58:36 -06002638 if (binOp != glslang::EOpNull) {
2639 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2640 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2641 assert(left && right);
2642
2643 builder.clearAccessChain();
2644 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002645 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002646
2647 builder.clearAccessChain();
2648 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002649 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002650
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002651 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002652 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002653 TranslateNoContractionDecoration(node->getType().getQualifier()),
2654 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002655 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002656 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002657 left->getType().getBasicType(), reduceComparison);
2658
2659 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002660 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002661 builder.clearAccessChain();
2662 builder.setAccessChainRValue(result);
2663
2664 return false;
2665 }
2666
John Kessenich426394d2015-07-23 10:22:48 -06002667 //
2668 // Create the list of operands.
2669 //
John Kessenich140f3df2015-06-26 16:58:36 -06002670 glslang::TIntermSequence& glslangOperands = node->getSequence();
2671 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002672 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002673 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002674 // special case l-value operands; there are just a few
2675 bool lvalue = false;
2676 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002677 case glslang::EOpModf:
2678 if (arg == 1)
2679 lvalue = true;
2680 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002681#ifndef GLSLANG_WEB
2682 case glslang::EOpFrexp:
2683 if (arg == 1)
2684 lvalue = true;
2685 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002686 case glslang::EOpInterpolateAtSample:
2687 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002688 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002689 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002690 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002691
2692 // Does it need a swizzle inversion? If so, evaluation is inverted;
2693 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002694 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002695 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2696 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2697 }
Rex Xu7a26c172015-12-08 17:12:09 +08002698 break;
Rex Xud4782c12015-09-06 16:30:11 +08002699 case glslang::EOpAtomicAdd:
2700 case glslang::EOpAtomicMin:
2701 case glslang::EOpAtomicMax:
2702 case glslang::EOpAtomicAnd:
2703 case glslang::EOpAtomicOr:
2704 case glslang::EOpAtomicXor:
2705 case glslang::EOpAtomicExchange:
2706 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002707 case glslang::EOpAtomicLoad:
2708 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002709 case glslang::EOpAtomicCounterAdd:
2710 case glslang::EOpAtomicCounterSubtract:
2711 case glslang::EOpAtomicCounterMin:
2712 case glslang::EOpAtomicCounterMax:
2713 case glslang::EOpAtomicCounterAnd:
2714 case glslang::EOpAtomicCounterOr:
2715 case glslang::EOpAtomicCounterXor:
2716 case glslang::EOpAtomicCounterExchange:
2717 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002718 if (arg == 0)
2719 lvalue = true;
2720 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002721 case glslang::EOpAddCarry:
2722 case glslang::EOpSubBorrow:
2723 if (arg == 2)
2724 lvalue = true;
2725 break;
2726 case glslang::EOpUMulExtended:
2727 case glslang::EOpIMulExtended:
2728 if (arg >= 2)
2729 lvalue = true;
2730 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002731 case glslang::EOpCooperativeMatrixLoad:
2732 if (arg == 0 || arg == 1)
2733 lvalue = true;
2734 break;
2735 case glslang::EOpCooperativeMatrixStore:
2736 if (arg == 1)
2737 lvalue = true;
2738 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002739#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002740 default:
2741 break;
2742 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002743 builder.clearAccessChain();
2744 if (invertedType != spv::NoType && arg == 0)
2745 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2746 else
2747 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002748
John Kessenichb9197c82019-08-11 07:41:45 -06002749#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002750 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2751 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2752
2753 if (arg == 1) {
2754 // fold "element" parameter into the access chain
2755 spv::Builder::AccessChain save = builder.getAccessChain();
2756 builder.clearAccessChain();
2757 glslangOperands[2]->traverse(this);
2758
2759 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2760
2761 builder.setAccessChain(save);
2762
2763 // Point to the first element of the array.
2764 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002765 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002766
2767 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2768 unsigned int alignment = builder.getAccessChain().alignment;
2769
2770 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2771 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2772 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2773 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2774 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2775 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2776 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2777 }
2778
2779 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2780
2781 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2782 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2783 }
2784
2785 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2786 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2787 }
2788 } else if (arg == 2) {
2789 continue;
2790 }
2791 }
John Kessenichb9197c82019-08-11 07:41:45 -06002792#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002793
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002794 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002795 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002796 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2797 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2798 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002799 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002800 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002801 }
John Kessenich140f3df2015-06-26 16:58:36 -06002802 }
John Kessenich426394d2015-07-23 10:22:48 -06002803
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002804 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002805#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002806 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2807 std::vector<spv::IdImmediate> idImmOps;
2808
2809 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2810 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2811 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2812 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2813 // get the pointee type
2814 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2815 assert(builder.isCooperativeMatrixType(typeId));
2816 // do the op
2817 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2818 // store the result to the pointer (out param 'm')
2819 builder.createStore(result, operands[0]);
2820 result = 0;
2821 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2822 std::vector<spv::IdImmediate> idImmOps;
2823
2824 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2825 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2826 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2827 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2828 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2829
2830 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2831 result = 0;
2832 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002833 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002834 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenichb9197c82019-08-11 07:41:45 -06002835 } else
2836#endif
2837 {
John Kessenich426394d2015-07-23 10:22:48 -06002838 // Pass through to generic operations.
2839 switch (glslangOperands.size()) {
2840 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002841 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002842 break;
2843 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002844 {
2845 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002846 TranslateNoContractionDecoration(node->getType().getQualifier()),
2847 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002848 result = createUnaryOperation(
2849 node->getOp(), decorations,
2850 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002851 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002852 }
John Kessenich426394d2015-07-23 10:22:48 -06002853 break;
2854 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002855 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002856 break;
2857 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002858 if (invertedType)
2859 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002860 }
2861
2862 if (noReturnValue)
2863 return false;
2864
2865 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002866 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002867 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002868 } else {
2869 builder.clearAccessChain();
2870 builder.setAccessChainRValue(result);
2871 return false;
2872 }
2873}
2874
John Kessenich433e9ff2017-01-26 20:31:11 -07002875// This path handles both if-then-else and ?:
2876// The if-then-else has a node type of void, while
2877// ?: has either a void or a non-void node type
2878//
2879// Leaving the result, when not void:
2880// GLSL only has r-values as the result of a :?, but
2881// if we have an l-value, that can be more efficient if it will
2882// become the base of a complex r-value expression, because the
2883// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002884bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2885{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002886 // see if OpSelect can handle it
2887 const auto isOpSelectable = [&]() {
2888 if (node->getBasicType() == glslang::EbtVoid)
2889 return false;
2890 // OpSelect can do all other types starting with SPV 1.4
2891 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2892 // pre-1.4, only scalars and vectors can be handled
2893 if ((!node->getType().isScalar() && !node->getType().isVector()))
2894 return false;
2895 }
2896 return true;
2897 };
2898
John Kessenich4bee5312018-02-20 21:29:05 -07002899 // See if it simple and safe, or required, to execute both sides.
2900 // Crucially, side effects must be either semantically required or avoided,
2901 // and there are performance trade-offs.
2902 // Return true if required or a good idea (and safe) to execute both sides,
2903 // false otherwise.
2904 const auto bothSidesPolicy = [&]() -> bool {
2905 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002906 if (node->getTrueBlock() == nullptr ||
2907 node->getFalseBlock() == nullptr)
2908 return false;
2909
John Kessenich4bee5312018-02-20 21:29:05 -07002910 // required? (unless we write additional code to look for side effects
2911 // and make performance trade-offs if none are present)
2912 if (!node->getShortCircuit())
2913 return true;
2914
2915 // if not required to execute both, decide based on performance/practicality...
2916
John Kessenich0c1e71a2019-01-10 18:23:06 +07002917 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002918 return false;
2919
John Kessenich433e9ff2017-01-26 20:31:11 -07002920 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2921 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2922
2923 // return true if a single operand to ? : is okay for OpSelect
2924 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002925 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002926 };
2927
2928 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2929 operandOkay(node->getFalseBlock()->getAsTyped());
2930 };
2931
John Kessenich4bee5312018-02-20 21:29:05 -07002932 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2933 // emit the condition before doing anything with selection
2934 node->getCondition()->traverse(this);
2935 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2936
2937 // Find a way of executing both sides and selecting the right result.
2938 const auto executeBothSides = [&]() -> void {
2939 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002940 node->getTrueBlock()->traverse(this);
2941 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2942 node->getFalseBlock()->traverse(this);
2943 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2944
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002945 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002946
John Kessenich4bee5312018-02-20 21:29:05 -07002947 // done if void
2948 if (node->getBasicType() == glslang::EbtVoid)
2949 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002950
John Kessenich4bee5312018-02-20 21:29:05 -07002951 // emit code to select between trueValue and falseValue
2952
2953 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002954 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002955 // Emit OpSelect for this selection.
2956
2957 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002958 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2959 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002960 condition = builder.smearScalar(spv::NoPrecision, condition,
2961 builder.makeVectorType(builder.makeBoolType(),
2962 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002963 }
John Kessenich4bee5312018-02-20 21:29:05 -07002964
2965 // OpSelect
2966 result = builder.createTriOp(spv::OpSelect,
2967 convertGlslangToSpvType(node->getType()), condition,
2968 trueValue, falseValue);
2969
2970 builder.clearAccessChain();
2971 builder.setAccessChainRValue(result);
2972 } else {
2973 // We need control flow to select the result.
2974 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2975 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2976
2977 // Selection control:
2978 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2979
2980 // make an "if" based on the value created by the condition
2981 spv::Builder::If ifBuilder(condition, control, builder);
2982
2983 // emit the "then" statement
2984 builder.createStore(trueValue, result);
2985 ifBuilder.makeBeginElse();
2986 // emit the "else" statement
2987 builder.createStore(falseValue, result);
2988
2989 // finish off the control flow
2990 ifBuilder.makeEndIf();
2991
2992 builder.clearAccessChain();
2993 builder.setAccessChainLValue(result);
2994 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002995 };
2996
John Kessenich4bee5312018-02-20 21:29:05 -07002997 // Execute the one side needed, as per the condition
2998 const auto executeOneSide = [&]() {
2999 // Always emit control flow.
3000 if (node->getBasicType() != glslang::EbtVoid)
3001 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003002
John Kessenich4bee5312018-02-20 21:29:05 -07003003 // Selection control:
3004 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3005
3006 // make an "if" based on the value created by the condition
3007 spv::Builder::If ifBuilder(condition, control, builder);
3008
3009 // emit the "then" statement
3010 if (node->getTrueBlock() != nullptr) {
3011 node->getTrueBlock()->traverse(this);
3012 if (result != spv::NoResult)
3013 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3014 }
3015
3016 if (node->getFalseBlock() != nullptr) {
3017 ifBuilder.makeBeginElse();
3018 // emit the "else" statement
3019 node->getFalseBlock()->traverse(this);
3020 if (result != spv::NoResult)
3021 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3022 }
3023
3024 // finish off the control flow
3025 ifBuilder.makeEndIf();
3026
3027 if (result != spv::NoResult) {
3028 builder.clearAccessChain();
3029 builder.setAccessChainLValue(result);
3030 }
3031 };
3032
3033 // Try for OpSelect (or a requirement to execute both sides)
3034 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003035 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3036 if (node->getType().getQualifier().isSpecConstant())
3037 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003038 executeBothSides();
3039 } else
3040 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003041
3042 return false;
3043}
3044
3045bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3046{
3047 // emit and get the condition before doing anything with switch
3048 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003049 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003050
Rex Xu57e65922017-07-04 23:23:40 +08003051 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003052 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003053
John Kessenich140f3df2015-06-26 16:58:36 -06003054 // browse the children to sort out code segments
3055 int defaultSegment = -1;
3056 std::vector<TIntermNode*> codeSegments;
3057 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3058 std::vector<int> caseValues;
3059 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3060 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3061 TIntermNode* child = *c;
3062 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003063 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003064 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003065 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003066 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3067 } else
3068 codeSegments.push_back(child);
3069 }
3070
qining25262b32016-05-06 17:25:16 -04003071 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003072 // statements between the last case and the end of the switch statement
3073 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3074 (int)codeSegments.size() == defaultSegment)
3075 codeSegments.push_back(nullptr);
3076
3077 // make the switch statement
3078 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003079 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003080
3081 // emit all the code in the segments
3082 breakForLoop.push(false);
3083 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3084 builder.nextSwitchSegment(segmentBlocks, s);
3085 if (codeSegments[s])
3086 codeSegments[s]->traverse(this);
3087 else
3088 builder.addSwitchBreak();
3089 }
3090 breakForLoop.pop();
3091
3092 builder.endSwitch(segmentBlocks);
3093
3094 return false;
3095}
3096
3097void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3098{
3099 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003100 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003101
3102 builder.clearAccessChain();
3103 builder.setAccessChainRValue(constant);
3104}
3105
3106bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3107{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003108 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003109 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003110
3111 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003112 std::vector<unsigned int> operands;
3113 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003114
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003115 // Spec requires back edges to target header blocks, and every header block
3116 // must dominate its merge block. Make a header block first to ensure these
3117 // conditions are met. By definition, it will contain OpLoopMerge, followed
3118 // by a block-ending branch. But we don't want to put any other body/test
3119 // instructions in it, since the body/test may have arbitrary instructions,
3120 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003121 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003122 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003123 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003124 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003125 spv::Block& test = builder.makeNewBlock();
3126 builder.createBranch(&test);
3127
3128 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003129 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003130 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003131 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3132
3133 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003134 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003135 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003136 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003137 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003138 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003139
3140 builder.setBuildPoint(&blocks.continue_target);
3141 if (node->getTerminal())
3142 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003143 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003144 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003145 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003146 builder.createBranch(&blocks.body);
3147
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003148 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003149 builder.setBuildPoint(&blocks.body);
3150 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003151 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003152 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003153 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003154
3155 builder.setBuildPoint(&blocks.continue_target);
3156 if (node->getTerminal())
3157 node->getTerminal()->traverse(this);
3158 if (node->getTest()) {
3159 node->getTest()->traverse(this);
3160 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003161 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003162 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003163 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003164 // TODO: unless there was a break/return/discard instruction
3165 // somewhere in the body, this is an infinite loop, so we should
3166 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003167 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003168 }
John Kessenich140f3df2015-06-26 16:58:36 -06003169 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003170 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003171 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003172 return false;
3173}
3174
3175bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3176{
3177 if (node->getExpression())
3178 node->getExpression()->traverse(this);
3179
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003180 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003181
John Kessenich140f3df2015-06-26 16:58:36 -06003182 switch (node->getFlowOp()) {
3183 case glslang::EOpKill:
3184 builder.makeDiscard();
3185 break;
3186 case glslang::EOpBreak:
3187 if (breakForLoop.top())
3188 builder.createLoopExit();
3189 else
3190 builder.addSwitchBreak();
3191 break;
3192 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003193 builder.createLoopContinue();
3194 break;
3195 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003196 if (node->getExpression()) {
3197 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3198 spv::Id returnId = accessChainLoad(glslangReturnType);
3199 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3200 builder.clearAccessChain();
3201 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3202 builder.setAccessChainLValue(copyId);
3203 multiTypeStore(glslangReturnType, returnId);
3204 returnId = builder.createLoad(copyId);
3205 }
3206 builder.makeReturn(false, returnId);
3207 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003208 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003209
3210 builder.clearAccessChain();
3211 break;
3212
John Kessenichb9197c82019-08-11 07:41:45 -06003213#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003214 case glslang::EOpDemote:
3215 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3216 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3217 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3218 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003219#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003220
John Kessenich140f3df2015-06-26 16:58:36 -06003221 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003223 break;
3224 }
3225
3226 return false;
3227}
3228
John Kessenich9c14f772019-06-17 08:38:35 -06003229spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003230{
qining25262b32016-05-06 17:25:16 -04003231 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003232 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003233 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003234 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003235 spv::Id result = createSpvConstant(*node);
3236 if (result != spv::NoResult)
3237 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003238 }
3239
3240 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003241 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003242 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3243 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003244
John Kessenichb9197c82019-08-11 07:41:45 -06003245 const bool contains16BitType = node->getType().contains16BitFloat() ||
3246 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003247 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003248 switch (storageClass) {
3249 case spv::StorageClassInput:
3250 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003251 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003252 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003253 break;
John Kessenich18310872018-05-14 22:08:53 -06003254 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003255 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003256 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3257 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003258 else
3259 builder.addCapability(spv::CapabilityStorageUniform16);
3260 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003261#ifndef GLSLANG_WEB
3262 case spv::StorageClassPushConstant:
3263 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3264 builder.addCapability(spv::CapabilityStoragePushConstant16);
3265 break;
John Kessenich18310872018-05-14 22:08:53 -06003266 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003267 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003268 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3269 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3270 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003271#endif
John Kessenich18310872018-05-14 22:08:53 -06003272 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003273 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003274 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003275 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003276 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003277 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003278 }
3279 }
Rex Xuf89ad982017-04-07 23:22:33 +08003280
John Kessenichb9197c82019-08-11 07:41:45 -06003281 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003282 if (storageClass == spv::StorageClassPushConstant) {
3283 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3284 builder.addCapability(spv::CapabilityStoragePushConstant8);
3285 } else if (storageClass == spv::StorageClassUniform) {
3286 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3287 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003288 } else if (storageClass == spv::StorageClassStorageBuffer) {
3289 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3290 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003291 } else {
3292 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003293 }
3294 }
3295
John Kessenich140f3df2015-06-26 16:58:36 -06003296 const char* name = node->getName().c_str();
3297 if (glslang::IsAnonymous(name))
3298 name = "";
3299
3300 return builder.createVariable(storageClass, spvType, name);
3301}
3302
3303// Return type Id of the sampled type.
3304spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3305{
3306 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003307 case glslang::EbtInt: return builder.makeIntType(32);
3308 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003309 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003310#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003311 case glslang::EbtFloat16:
3312 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3313 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3314 return builder.makeFloatType(16);
3315#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003316 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003318 return builder.makeFloatType(32);
3319 }
3320}
3321
John Kessenich8c8505c2016-07-26 12:50:38 -06003322// If node is a swizzle operation, return the type that should be used if
3323// the swizzle base is first consumed by another operation, before the swizzle
3324// is applied.
3325spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3326{
John Kessenichecba76f2017-01-06 00:34:48 -07003327 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003328 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3329 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3330 else
3331 return spv::NoType;
3332}
3333
3334// When inverting a swizzle with a parent op, this function
3335// will apply the swizzle operation to a completed parent operation.
3336spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3337{
3338 std::vector<unsigned> swizzle;
3339 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3340 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3341}
3342
John Kessenich8c8505c2016-07-26 12:50:38 -06003343// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3344void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3345{
3346 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3347 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3348 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3349}
3350
John Kessenich3ac051e2015-12-20 11:29:16 -07003351// Convert from a glslang type to an SPV type, by calling into a
3352// recursive version of this function. This establishes the inherited
3353// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003354spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003355{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003356 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003357}
3358
3359// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003360// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003361// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003362spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003363 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3364 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003365{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003366 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003367
3368 switch (type.getBasicType()) {
3369 case glslang::EbtVoid:
3370 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003371 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003374 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3375 // a 32-bit int where non-0 means true.
3376 if (explicitLayout != glslang::ElpNone)
3377 spvType = builder.makeUintType(32);
3378 else
3379 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003380 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003381 case glslang::EbtInt:
3382 spvType = builder.makeIntType(32);
3383 break;
3384 case glslang::EbtUint:
3385 spvType = builder.makeUintType(32);
3386 break;
3387 case glslang::EbtFloat:
3388 spvType = builder.makeFloatType(32);
3389 break;
3390#ifndef GLSLANG_WEB
3391 case glslang::EbtDouble:
3392 spvType = builder.makeFloatType(64);
3393 break;
3394 case glslang::EbtFloat16:
3395 spvType = builder.makeFloatType(16);
3396 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003397 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003398 spvType = builder.makeIntType(8);
3399 break;
3400 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003401 spvType = builder.makeUintType(8);
3402 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003403 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003404 spvType = builder.makeIntType(16);
3405 break;
3406 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003407 spvType = builder.makeUintType(16);
3408 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003409 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003410 spvType = builder.makeIntType(64);
3411 break;
3412 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003413 spvType = builder.makeUintType(64);
3414 break;
John Kessenich426394d2015-07-23 10:22:48 -06003415 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003416 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003417 spvType = builder.makeUintType(32);
3418 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003419 case glslang::EbtAccStructNV:
3420 spvType = builder.makeAccelerationStructureNVType();
3421 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003422 case glslang::EbtReference:
3423 {
3424 // Make the forward pointer, then recurse to convert the structure type, then
3425 // patch up the forward pointer with a real pointer type.
3426 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3427 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3428 forwardPointers[type.getReferentType()] = forwardId;
3429 }
3430 spvType = forwardPointers[type.getReferentType()];
3431 if (!forwardReferenceOnly) {
3432 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3433 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3434 forwardPointers[type.getReferentType()],
3435 referentType);
3436 }
3437 }
3438 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003439#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003440 case glslang::EbtSampler:
3441 {
3442 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003443 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003444 spvType = builder.makeSamplerType();
3445 } else {
3446 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003447 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3448 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3449 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3450 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003451 // already has both image and sampler, make the combined type
3452 spvType = builder.makeSampledImageType(spvType);
3453 }
John Kessenich55e7d112015-11-15 21:33:39 -07003454 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003455 }
John Kessenich140f3df2015-06-26 16:58:36 -06003456 break;
3457 case glslang::EbtStruct:
3458 case glslang::EbtBlock:
3459 {
3460 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003461 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003462
3463 // Try to share structs for different layouts, but not yet for other
3464 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003465 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003466 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003467 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003468 break;
3469
3470 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003471 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003472 memberRemapper[glslangMembers].resize(glslangMembers->size());
3473 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003474 }
3475 break;
3476 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003477 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003478 break;
3479 }
3480
3481 if (type.isMatrix())
3482 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3483 else {
3484 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3485 if (type.getVectorSize() > 1)
3486 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3487 }
3488
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003489 if (type.isCoopMat()) {
3490 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3491 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3492 if (type.getBasicType() == glslang::EbtFloat16)
3493 builder.addCapability(spv::CapabilityFloat16);
3494
3495 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3496 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3497 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3498
3499 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3500 }
3501
John Kessenich140f3df2015-06-26 16:58:36 -06003502 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003503 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3504
John Kessenichc9a80832015-09-12 12:17:44 -06003505 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003506 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003507 // We need to decorate array strides for types needing explicit layout, except blocks.
3508 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003509 // Use a dummy glslang type for querying internal strides of
3510 // arrays of arrays, but using just a one-dimensional array.
3511 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003512 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3513 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003514
3515 // Will compute the higher-order strides here, rather than making a whole
3516 // pile of types and doing repetitive recursion on their contents.
3517 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3518 }
John Kessenichf8842e52016-01-04 19:22:56 -07003519
3520 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003521 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003522 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003523 if (stride > 0)
3524 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003525 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003526 }
3527 } else {
3528 // single-dimensional array, and don't yet have stride
3529
John Kessenichf8842e52016-01-04 19:22:56 -07003530 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003531 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3532 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003533 }
John Kessenich31ed4832015-09-09 17:51:38 -06003534
John Kessenichead86222018-03-28 18:01:20 -06003535 // Do the outer dimension, which might not be known for a runtime-sized array.
3536 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3537 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003538 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003539 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003540#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003541 if (!lastBufferBlockMember) {
3542 builder.addExtension("SPV_EXT_descriptor_indexing");
3543 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3544 }
John Kessenichead86222018-03-28 18:01:20 -06003545 spvType = builder.makeRuntimeArray(spvType);
John Kessenichb9197c82019-08-11 07:41:45 -06003546#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06003547 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003548 if (stride > 0)
3549 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003550 }
3551
3552 return spvType;
3553}
3554
John Kessenich0e737842017-03-24 18:38:16 -06003555// TODO: this functionality should exist at a higher level, in creating the AST
3556//
3557// Identify interface members that don't have their required extension turned on.
3558//
3559bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3560{
John Kessenicha28f7a72019-08-06 07:00:58 -06003561#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003562 auto& extensions = glslangIntermediate->getRequestedExtensions();
3563
Rex Xubcf291a2017-03-29 23:01:36 +08003564 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3565 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3566 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003567 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3568 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3569 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003570
3571 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3572 if (member.getFieldName() == "gl_ViewportMask" &&
3573 extensions.find("GL_NV_viewport_array2") == extensions.end())
3574 return true;
3575 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3576 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3577 return true;
3578 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3579 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3580 return true;
3581 }
3582#endif
John Kessenich0e737842017-03-24 18:38:16 -06003583
3584 return false;
3585};
3586
John Kessenich6090df02016-06-30 21:18:02 -06003587// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3588// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3589// Mutually recursive with convertGlslangToSpvType().
3590spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3591 const glslang::TTypeList* glslangMembers,
3592 glslang::TLayoutPacking explicitLayout,
3593 const glslang::TQualifier& qualifier)
3594{
3595 // Create a vector of struct types for SPIR-V to consume
3596 std::vector<spv::Id> spvMembers;
3597 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003598 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003599 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3600 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3601 if (glslangMember.hiddenMember()) {
3602 ++memberDelta;
3603 if (type.getBasicType() == glslang::EbtBlock)
3604 memberRemapper[glslangMembers][i] = -1;
3605 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003606 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003607 if (filterMember(glslangMember)) {
3608 memberDelta++;
3609 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003610 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003611 }
3612 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003613 }
John Kessenich6090df02016-06-30 21:18:02 -06003614 // modify just this child's view of the qualifier
3615 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3616 InheritQualifiers(memberQualifier, qualifier);
3617
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003618 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003619 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003620 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003621
3622 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003623 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3624 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003625
3626 // Make forward pointers for any pointer members, and create a list of members to
3627 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003628 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003629 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3630 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3631 }
3632 spvMembers.push_back(
3633 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3634 } else {
3635 spvMembers.push_back(
3636 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3637 }
John Kessenich6090df02016-06-30 21:18:02 -06003638 }
3639 }
3640
3641 // Make the SPIR-V type
3642 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003643 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003644 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3645
3646 // Decorate it
3647 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3648
John Kessenichd72f4882019-01-16 14:55:37 +07003649 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003650 auto it = deferredForwardPointers[i];
3651 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3652 }
3653
John Kessenich6090df02016-06-30 21:18:02 -06003654 return spvType;
3655}
3656
3657void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3658 const glslang::TTypeList* glslangMembers,
3659 glslang::TLayoutPacking explicitLayout,
3660 const glslang::TQualifier& qualifier,
3661 spv::Id spvType)
3662{
3663 // Name and decorate the non-hidden members
3664 int offset = -1;
3665 int locationOffset = 0; // for use within the members of this struct
3666 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3667 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3668 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003669 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003670 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003671 if (filterMember(glslangMember))
3672 continue;
3673 }
John Kessenich6090df02016-06-30 21:18:02 -06003674
3675 // modify just this child's view of the qualifier
3676 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3677 InheritQualifiers(memberQualifier, qualifier);
3678
3679 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003680 if (member < 0)
3681 continue;
3682
3683 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3684 builder.addMemberDecoration(spvType, member,
3685 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3686 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3687 // Add interpolation and auxiliary storage decorations only to
3688 // top-level members of Input and Output storage classes
3689 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3690 type.getQualifier().storage == glslang::EvqVaryingOut) {
3691 if (type.getBasicType() == glslang::EbtBlock ||
3692 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3693 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3694 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003695#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003696 addMeshNVDecoration(spvType, member, memberQualifier);
3697#endif
John Kessenich6090df02016-06-30 21:18:02 -06003698 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003699 }
3700 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003701
John Kessenichb9197c82019-08-11 07:41:45 -06003702#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003703 if (type.getBasicType() == glslang::EbtBlock &&
3704 qualifier.storage == glslang::EvqBuffer) {
3705 // Add memory decorations only to top-level members of shader storage block
3706 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003707 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003708 for (unsigned int i = 0; i < memory.size(); ++i)
3709 builder.addMemberDecoration(spvType, member, memory[i]);
3710 }
John Kessenichb9197c82019-08-11 07:41:45 -06003711#endif
John Kessenich6090df02016-06-30 21:18:02 -06003712
John Kessenich5d610ee2018-03-07 18:05:55 -07003713 // Location assignment was already completed correctly by the front end,
3714 // just track whether a member needs to be decorated.
3715 // Ignore member locations if the container is an array, as that's
3716 // ill-specified and decisions have been made to not allow this.
3717 if (! type.isArray() && memberQualifier.hasLocation())
3718 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003719
John Kessenich5d610ee2018-03-07 18:05:55 -07003720 if (qualifier.hasLocation()) // track for upcoming inheritance
3721 locationOffset += glslangIntermediate->computeTypeLocationSize(
3722 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003723
John Kessenich5d610ee2018-03-07 18:05:55 -07003724 // component, XFB, others
3725 if (glslangMember.getQualifier().hasComponent())
3726 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3727 glslangMember.getQualifier().layoutComponent);
3728 if (glslangMember.getQualifier().hasXfbOffset())
3729 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3730 glslangMember.getQualifier().layoutXfbOffset);
3731 else if (explicitLayout != glslang::ElpNone) {
3732 // figure out what to do with offset, which is accumulating
3733 int nextOffset;
3734 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3735 if (offset >= 0)
3736 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3737 offset = nextOffset;
3738 }
John Kessenich6090df02016-06-30 21:18:02 -06003739
John Kessenich5d610ee2018-03-07 18:05:55 -07003740 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3741 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3742 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003743
John Kessenich5d610ee2018-03-07 18:05:55 -07003744 // built-in variable decorations
3745 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3746 if (builtIn != spv::BuiltInMax)
3747 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003748
John Kessenichb9197c82019-08-11 07:41:45 -06003749#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003750 // nonuniform
3751 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3752
John Kessenichead86222018-03-28 18:01:20 -06003753 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3754 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3755 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3756 memberQualifier.semanticName);
3757 }
3758
John Kessenich5d610ee2018-03-07 18:05:55 -07003759 if (builtIn == spv::BuiltInLayer) {
3760 // SPV_NV_viewport_array2 extension
3761 if (glslangMember.getQualifier().layoutViewportRelative){
3762 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3763 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3764 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003765 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003766 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3767 builder.addMemberDecoration(spvType, member,
3768 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3769 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3770 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3771 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003772 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003773 }
3774 if (glslangMember.getQualifier().layoutPassthrough) {
3775 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3776 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3777 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3778 }
chaoc771d89f2017-01-13 01:10:53 -08003779#endif
John Kessenich6090df02016-06-30 21:18:02 -06003780 }
3781
3782 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003783 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3784 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003785}
3786
John Kessenich6c292d32016-02-15 20:58:50 -07003787// Turn the expression forming the array size into an id.
3788// This is not quite trivial, because of specialization constants.
3789// Sometimes, a raw constant is turned into an Id, and sometimes
3790// a specialization constant expression is.
3791spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3792{
3793 // First, see if this is sized with a node, meaning a specialization constant:
3794 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3795 if (specNode != nullptr) {
3796 builder.clearAccessChain();
3797 specNode->traverse(this);
3798 return accessChainLoad(specNode->getAsTyped()->getType());
3799 }
qining25262b32016-05-06 17:25:16 -04003800
John Kessenich6c292d32016-02-15 20:58:50 -07003801 // Otherwise, need a compile-time (front end) size, get it:
3802 int size = arraySizes.getDimSize(dim);
3803 assert(size > 0);
3804 return builder.makeUintConstant(size);
3805}
3806
John Kessenich103bef92016-02-08 21:38:15 -07003807// Wrap the builder's accessChainLoad to:
3808// - localize handling of RelaxedPrecision
3809// - use the SPIR-V inferred type instead of another conversion of the glslang type
3810// (avoids unnecessary work and possible type punning for structures)
3811// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003812spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3813{
John Kessenich103bef92016-02-08 21:38:15 -07003814 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003815
3816 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3817 coherentFlags |= TranslateCoherent(type);
3818
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003819 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003820 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003821
John Kessenich5611c6d2018-04-05 11:25:02 -06003822 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003823 TranslateNonUniformDecoration(type.getQualifier()),
3824 nominalTypeId,
3825 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003826 TranslateMemoryScope(coherentFlags),
3827 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003828
3829 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003830 if (type.getBasicType() == glslang::EbtBool) {
3831 if (builder.isScalarType(nominalTypeId)) {
3832 // Conversion for bool
3833 spv::Id boolType = builder.makeBoolType();
3834 if (nominalTypeId != boolType)
3835 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3836 } else if (builder.isVectorType(nominalTypeId)) {
3837 // Conversion for bvec
3838 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3839 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3840 if (nominalTypeId != bvecType)
3841 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3842 }
3843 }
John Kessenich103bef92016-02-08 21:38:15 -07003844
3845 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003846}
3847
Rex Xu27253232016-02-23 17:51:09 +08003848// Wrap the builder's accessChainStore to:
3849// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003850//
3851// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003852void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3853{
3854 // Need to convert to abstract types when necessary
3855 if (type.getBasicType() == glslang::EbtBool) {
3856 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3857
3858 if (builder.isScalarType(nominalTypeId)) {
3859 // Conversion for bool
3860 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003861 if (nominalTypeId != boolType) {
3862 // keep these outside arguments, for determinant order-of-evaluation
3863 spv::Id one = builder.makeUintConstant(1);
3864 spv::Id zero = builder.makeUintConstant(0);
3865 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3866 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003867 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003868 } else if (builder.isVectorType(nominalTypeId)) {
3869 // Conversion for bvec
3870 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3871 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003872 if (nominalTypeId != bvecType) {
3873 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003874 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3875 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3876 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003877 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003878 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3879 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003880 }
3881 }
3882
Jeff Bolz36831c92018-09-05 10:11:41 -05003883 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3884 coherentFlags |= TranslateCoherent(type);
3885
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003886 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003887 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003888
Jeff Bolz36831c92018-09-05 10:11:41 -05003889 builder.accessChainStore(rvalue,
3890 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003891 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003892}
3893
John Kessenich4bf71552016-09-02 11:20:21 -06003894// For storing when types match at the glslang level, but not might match at the
3895// SPIR-V level.
3896//
3897// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003898// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003899// as in a member-decorated way.
3900//
3901// NOTE: This function can handle any store request; if it's not special it
3902// simplifies to a simple OpStore.
3903//
3904// Implicitly uses the existing builder.accessChain as the storage target.
3905void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3906{
John Kessenichb3e24e42016-09-11 12:33:43 -06003907 // we only do the complex path here if it's an aggregate
3908 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003909 accessChainStore(type, rValue);
3910 return;
3911 }
3912
John Kessenichb3e24e42016-09-11 12:33:43 -06003913 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003914 spv::Id rType = builder.getTypeId(rValue);
3915 spv::Id lValue = builder.accessChainGetLValue();
3916 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3917 if (lType == rType) {
3918 accessChainStore(type, rValue);
3919 return;
3920 }
3921
John Kessenichb3e24e42016-09-11 12:33:43 -06003922 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003923 // where the two types were the same type in GLSL. This requires member
3924 // by member copy, recursively.
3925
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003926 // SPIR-V 1.4 added an instruction to do help do this.
3927 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3928 // However, bool in uniform space is changed to int, so
3929 // OpCopyLogical does not work for that.
3930 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3931 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3932 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3933 if (lBool == rBool) {
3934 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3935 accessChainStore(type, logicalCopy);
3936 return;
3937 }
3938 }
3939
John Kessenichb3e24e42016-09-11 12:33:43 -06003940 // If an array, copy element by element.
3941 if (type.isArray()) {
3942 glslang::TType glslangElementType(type, 0);
3943 spv::Id elementRType = builder.getContainedTypeId(rType);
3944 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3945 // get the source member
3946 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003947
John Kessenichb3e24e42016-09-11 12:33:43 -06003948 // set up the target storage
3949 builder.clearAccessChain();
3950 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003951 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003952
John Kessenichb3e24e42016-09-11 12:33:43 -06003953 // store the member
3954 multiTypeStore(glslangElementType, elementRValue);
3955 }
3956 } else {
3957 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003958
John Kessenichb3e24e42016-09-11 12:33:43 -06003959 // loop over structure members
3960 const glslang::TTypeList& members = *type.getStruct();
3961 for (int m = 0; m < (int)members.size(); ++m) {
3962 const glslang::TType& glslangMemberType = *members[m].type;
3963
3964 // get the source member
3965 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3966 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3967
3968 // set up the target storage
3969 builder.clearAccessChain();
3970 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003971 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003972
3973 // store the member
3974 multiTypeStore(glslangMemberType, memberRValue);
3975 }
John Kessenich4bf71552016-09-02 11:20:21 -06003976 }
3977}
3978
John Kessenichf85e8062015-12-19 13:57:10 -07003979// Decide whether or not this type should be
3980// decorated with offsets and strides, and if so
3981// whether std140 or std430 rules should be applied.
3982glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003983{
John Kessenichf85e8062015-12-19 13:57:10 -07003984 // has to be a block
3985 if (type.getBasicType() != glslang::EbtBlock)
3986 return glslang::ElpNone;
3987
Chao Chen3c366992018-09-19 11:41:59 -07003988 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003989 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003990 type.getQualifier().storage != glslang::EvqBuffer &&
3991 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003992 return glslang::ElpNone;
3993
3994 // return the layout to use
3995 switch (type.getQualifier().layoutPacking) {
3996 case glslang::ElpStd140:
3997 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003998 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003999 return type.getQualifier().layoutPacking;
4000 default:
4001 return glslang::ElpNone;
4002 }
John Kessenich31ed4832015-09-09 17:51:38 -06004003}
4004
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004005// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004006int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004007{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004008 int size;
John Kessenich49987892015-12-29 17:11:44 -07004009 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004010 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004011
4012 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004013}
4014
John Kessenich49987892015-12-29 17:11:44 -07004015// 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 -07004016// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004017int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004018{
John Kessenich49987892015-12-29 17:11:44 -07004019 glslang::TType elementType;
4020 elementType.shallowCopy(matrixType);
4021 elementType.clearArraySizes();
4022
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004023 int size;
John Kessenich49987892015-12-29 17:11:44 -07004024 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004025 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004026
4027 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004028}
4029
John Kessenich5e4b1242015-08-06 22:53:06 -06004030// Given a member type of a struct, realign the current offset for it, and compute
4031// the next (not yet aligned) offset for the next member, which will get aligned
4032// on the next call.
4033// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4034// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4035// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004036void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004037 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004038{
4039 // this will get a positive value when deemed necessary
4040 nextOffset = -1;
4041
John Kessenich5e4b1242015-08-06 22:53:06 -06004042 // override anything in currentOffset with user-set offset
4043 if (memberType.getQualifier().hasOffset())
4044 currentOffset = memberType.getQualifier().layoutOffset;
4045
4046 // It could be that current linker usage in glslang updated all the layoutOffset,
4047 // in which case the following code does not matter. But, that's not quite right
4048 // once cross-compilation unit GLSL validation is done, as the original user
4049 // settings are needed in layoutOffset, and then the following will come into play.
4050
John Kessenichf85e8062015-12-19 13:57:10 -07004051 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 if (! memberType.getQualifier().hasOffset())
4053 currentOffset = -1;
4054
4055 return;
4056 }
4057
John Kessenichf85e8062015-12-19 13:57:10 -07004058 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 if (currentOffset < 0)
4060 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004061
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4063 // but possibly not yet correctly aligned.
4064
4065 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004066 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004067 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004068
4069 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004070 // TODO: make this consistent in early phases of code:
4071 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4072 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4073 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004074 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004075 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004076 int dummySize;
4077 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4078 if (componentAlignment <= 4)
4079 memberAlignment = componentAlignment;
4080 }
4081
4082 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004083 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004084
4085 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004086 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004087 glslang::RoundToPow2(currentOffset, 16);
4088
John Kessenich5e4b1242015-08-06 22:53:06 -06004089 nextOffset = currentOffset + memberSize;
4090}
4091
David Netoa901ffe2016-06-08 14:11:40 +01004092void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004093{
David Netoa901ffe2016-06-08 14:11:40 +01004094 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4095 switch (glslangBuiltIn)
4096 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004097 case glslang::EbvPointSize:
4098#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004099 case glslang::EbvClipDistance:
4100 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004101 case glslang::EbvViewportMaskNV:
4102 case glslang::EbvSecondaryPositionNV:
4103 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004104 case glslang::EbvPositionPerViewNV:
4105 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004106 case glslang::EbvTaskCountNV:
4107 case glslang::EbvPrimitiveCountNV:
4108 case glslang::EbvPrimitiveIndicesNV:
4109 case glslang::EbvClipDistancePerViewNV:
4110 case glslang::EbvCullDistancePerViewNV:
4111 case glslang::EbvLayerPerViewNV:
4112 case glslang::EbvMeshViewCountNV:
4113 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004114#endif
David Netoa901ffe2016-06-08 14:11:40 +01004115 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4116 // Alternately, we could just call this for any glslang built-in, since the
4117 // capability already guards against duplicates.
4118 TranslateBuiltInDecoration(glslangBuiltIn, false);
4119 break;
4120 default:
4121 // Capabilities were already generated when the struct was declared.
4122 break;
4123 }
John Kessenichebb50532016-05-16 19:22:05 -06004124}
4125
John Kessenich6fccb3c2016-09-19 16:01:41 -06004126bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004127{
John Kessenicheee9d532016-09-19 18:09:30 -06004128 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004129}
4130
John Kessenichd41993d2017-09-10 15:21:05 -06004131// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004132// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4133// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004134bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004135{
John Kessenich6a14f782017-12-04 02:48:10 -07004136 assert(qualifier == glslang::EvqIn ||
4137 qualifier == glslang::EvqOut ||
4138 qualifier == glslang::EvqInOut ||
4139 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004140 return qualifier != glslang::EvqConstReadOnly;
4141}
4142
4143// Is parameter pass-by-original?
4144bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4145 bool implicitThisParam)
4146{
4147 if (implicitThisParam) // implicit this
4148 return true;
4149 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004150 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004151 return paramType.containsOpaque() || // sampler, etc.
4152 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4153}
4154
John Kessenich140f3df2015-06-26 16:58:36 -06004155// Make all the functions, skeletally, without actually visiting their bodies.
4156void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4157{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004158 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004159 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4160 if (paramPrecision != spv::NoPrecision)
4161 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004162 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004163 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004164 // Original and non-writable params pass the pointer directly and
4165 // use restrict/aliased, others are stored to a pointer in Function
4166 // memory and use RestrictPointer/AliasedPointer.
4167 if (originalParam(type.getQualifier().storage, type, false) ||
4168 !writableParam(type.getQualifier().storage)) {
4169 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4170 } else {
4171 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4172 }
4173 }
John Kessenichfad62972017-07-18 02:35:46 -06004174 };
4175
John Kessenich140f3df2015-06-26 16:58:36 -06004176 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4177 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004178 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004179 continue;
4180
4181 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004182 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004183 //
qining25262b32016-05-06 17:25:16 -04004184 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004185 // function. What it is an address of varies:
4186 //
John Kessenich4bf71552016-09-02 11:20:21 -06004187 // - "in" parameters not marked as "const" can be written to without modifying the calling
4188 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004189 //
4190 // - "const in" parameters can just be the r-value, as no writes need occur.
4191 //
John Kessenich4bf71552016-09-02 11:20:21 -06004192 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4193 // 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 -06004194
4195 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004196 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004197 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4198
John Kessenich155d3512019-08-08 23:29:20 -06004199#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004200 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4201 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004202#else
4203 bool implicitThis = false;
4204#endif
John Kessenich37789792017-03-21 23:56:40 -06004205
John Kessenichfad62972017-07-18 02:35:46 -06004206 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004207 for (int p = 0; p < (int)parameters.size(); ++p) {
4208 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4209 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004210 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004211 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004212 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004213 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4214 else
John Kessenich4bf71552016-09-02 11:20:21 -06004215 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004216 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004217 paramTypes.push_back(typeId);
4218 }
4219
4220 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004221 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4222 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004223 glslFunction->getName().c_str(), paramTypes,
4224 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004225 if (implicitThis)
4226 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004227
4228 // Track function to emit/call later
4229 functionMap[glslFunction->getName().c_str()] = function;
4230
4231 // Set the parameter id's
4232 for (int p = 0; p < (int)parameters.size(); ++p) {
4233 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4234 // give a name too
4235 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004236
4237 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004238 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004239 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004240 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004241 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004242 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004243 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004244 }
4245 }
4246}
4247
4248// Process all the initializers, while skipping the functions and link objects
4249void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4250{
4251 builder.setBuildPoint(shaderEntry->getLastBlock());
4252 for (int i = 0; i < (int)initializers.size(); ++i) {
4253 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4254 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4255
4256 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004257 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004258 initializer->traverse(this);
4259 }
4260 }
4261}
4262
4263// Process all the functions, while skipping initializers.
4264void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4265{
4266 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4267 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004268 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004269 node->traverse(this);
4270 }
4271}
4272
4273void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4274{
qining25262b32016-05-06 17:25:16 -04004275 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004276 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004277 currentFunction = functionMap[node->getName().c_str()];
4278 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004279 builder.setBuildPoint(functionBlock);
4280}
4281
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004282void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004283{
Rex Xufc618912015-09-09 16:42:49 +08004284 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004285
4286 glslang::TSampler sampler = {};
4287 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004288#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004289 bool f16ShadowCompare = false;
4290#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004291 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004292 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4293 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004294#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004295 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4296#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004297 }
4298
John Kessenich140f3df2015-06-26 16:58:36 -06004299 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4300 builder.clearAccessChain();
4301 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004302
John Kessenicha28f7a72019-08-06 07:00:58 -06004303#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004304 // Special case l-value operands
4305 bool lvalue = false;
4306 switch (node.getOp()) {
4307 case glslang::EOpImageAtomicAdd:
4308 case glslang::EOpImageAtomicMin:
4309 case glslang::EOpImageAtomicMax:
4310 case glslang::EOpImageAtomicAnd:
4311 case glslang::EOpImageAtomicOr:
4312 case glslang::EOpImageAtomicXor:
4313 case glslang::EOpImageAtomicExchange:
4314 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004315 case glslang::EOpImageAtomicLoad:
4316 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004317 if (i == 0)
4318 lvalue = true;
4319 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004320 case glslang::EOpSparseImageLoad:
4321 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4322 lvalue = true;
4323 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004324 case glslang::EOpSparseTexture:
4325 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4326 lvalue = true;
4327 break;
4328 case glslang::EOpSparseTextureClamp:
4329 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4330 lvalue = true;
4331 break;
4332 case glslang::EOpSparseTextureLod:
4333 case glslang::EOpSparseTextureOffset:
4334 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4335 lvalue = true;
4336 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004337 case glslang::EOpSparseTextureFetch:
4338 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4339 lvalue = true;
4340 break;
4341 case glslang::EOpSparseTextureFetchOffset:
4342 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4343 lvalue = true;
4344 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004345 case glslang::EOpSparseTextureLodOffset:
4346 case glslang::EOpSparseTextureGrad:
4347 case glslang::EOpSparseTextureOffsetClamp:
4348 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4349 lvalue = true;
4350 break;
4351 case glslang::EOpSparseTextureGradOffset:
4352 case glslang::EOpSparseTextureGradClamp:
4353 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4354 lvalue = true;
4355 break;
4356 case glslang::EOpSparseTextureGradOffsetClamp:
4357 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4358 lvalue = true;
4359 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004360 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004361 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4362 lvalue = true;
4363 break;
4364 case glslang::EOpSparseTextureGatherOffset:
4365 case glslang::EOpSparseTextureGatherOffsets:
4366 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4367 lvalue = true;
4368 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004369 case glslang::EOpSparseTextureGatherLod:
4370 if (i == 3)
4371 lvalue = true;
4372 break;
4373 case glslang::EOpSparseTextureGatherLodOffset:
4374 case glslang::EOpSparseTextureGatherLodOffsets:
4375 if (i == 4)
4376 lvalue = true;
4377 break;
Rex Xu129799a2017-07-05 17:23:28 +08004378 case glslang::EOpSparseImageLoadLod:
4379 if (i == 3)
4380 lvalue = true;
4381 break;
Chao Chen3a137962018-09-19 11:41:27 -07004382 case glslang::EOpImageSampleFootprintNV:
4383 if (i == 4)
4384 lvalue = true;
4385 break;
4386 case glslang::EOpImageSampleFootprintClampNV:
4387 case glslang::EOpImageSampleFootprintLodNV:
4388 if (i == 5)
4389 lvalue = true;
4390 break;
4391 case glslang::EOpImageSampleFootprintGradNV:
4392 if (i == 6)
4393 lvalue = true;
4394 break;
4395 case glslang::EOpImageSampleFootprintGradClampNV:
4396 if (i == 7)
4397 lvalue = true;
4398 break;
Rex Xufc618912015-09-09 16:42:49 +08004399 default:
4400 break;
4401 }
4402
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004403 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004404 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004405 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4406 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4407 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004408#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004409 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004410 }
4411}
4412
John Kessenichfc51d282015-08-19 13:34:18 -06004413void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004414{
John Kessenichfc51d282015-08-19 13:34:18 -06004415 builder.clearAccessChain();
4416 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004417 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004418}
John Kessenich140f3df2015-06-26 16:58:36 -06004419
John Kessenichfc51d282015-08-19 13:34:18 -06004420spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4421{
John Kesseniche485c7a2017-05-31 18:50:53 -06004422 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004423 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004424
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004425 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004426
John Kessenichfc51d282015-08-19 13:34:18 -06004427 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004428
John Kessenichf43c7392019-03-31 10:51:57 -06004429 const glslang::TType &imageType = node->getAsAggregate()
4430 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4431 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004432 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004433#ifdef GLSLANG_WEB
4434 const bool f16ShadowCompare = false;
4435#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004436 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004437 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4438 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004439#endif
4440
John Kessenichf43c7392019-03-31 10:51:57 -06004441 const auto signExtensionMask = [&]() {
4442 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4443 if (sampler.type == glslang::EbtUint)
4444 return spv::ImageOperandsZeroExtendMask;
4445 else if (sampler.type == glslang::EbtInt)
4446 return spv::ImageOperandsSignExtendMask;
4447 }
4448 return spv::ImageOperandsMaskNone;
4449 };
4450
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004451 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4452
John Kessenichfc51d282015-08-19 13:34:18 -06004453 std::vector<spv::Id> arguments;
4454 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004455 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004456 else
4457 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004458 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004459
4460 spv::Builder::TextureParameters params = { };
4461 params.sampler = arguments[0];
4462
Rex Xu04db3f52015-09-16 11:44:02 +08004463 glslang::TCrackedTextureOp cracked;
4464 node->crackTexture(sampler, cracked);
4465
amhagan05506bb2017-06-13 16:53:02 -04004466 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004467
John Kessenichfc51d282015-08-19 13:34:18 -06004468 // Check for queries
4469 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004470 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4471 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004472 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004473
John Kessenichfc51d282015-08-19 13:34:18 -06004474 switch (node->getOp()) {
4475 case glslang::EOpImageQuerySize:
4476 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004477 if (arguments.size() > 1) {
4478 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004479 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004480 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004481 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004482#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004483 case glslang::EOpImageQuerySamples:
4484 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004485 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004486 case glslang::EOpTextureQueryLod:
4487 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004488 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004489 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004490 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004491 case glslang::EOpSparseTexelsResident:
4492 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004493#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004494 default:
4495 assert(0);
4496 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004497 }
John Kessenich140f3df2015-06-26 16:58:36 -06004498 }
4499
LoopDawg4425f242018-02-18 11:40:01 -07004500 int components = node->getType().getVectorSize();
4501
4502 if (node->getOp() == glslang::EOpTextureFetch) {
4503 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4504 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4505 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4506 // here around e.g. which ones return scalars or other types.
4507 components = 4;
4508 }
4509
4510 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4511
4512 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4513
Rex Xufc618912015-09-09 16:42:49 +08004514 // Check for image functions other than queries
4515 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004516 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004517 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004518 spv::IdImmediate image = { true, *(opIt++) };
4519 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004520
4521 // Handle subpass operations
4522 // TODO: GLSL should change to have the "MS" only on the type rather than the
4523 // built-in function.
4524 if (cracked.subpass) {
4525 // add on the (0,0) coordinate
4526 spv::Id zero = builder.makeIntConstant(0);
4527 std::vector<spv::Id> comps;
4528 comps.push_back(zero);
4529 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004530 spv::IdImmediate coord = { true,
4531 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4532 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004533 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4534 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004535 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004536 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4537 }
4538 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004539 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004540 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004541 spv::IdImmediate imageOperand = { true, *(opIt++) };
4542 operands.push_back(imageOperand);
4543 }
John Kessenich6c292d32016-02-15 20:58:50 -07004544 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004545 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4546 builder.setPrecision(result, precision);
4547 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004548 }
4549
John Kessenich149afc32018-08-14 13:31:43 -06004550 spv::IdImmediate coord = { true, *(opIt++) };
4551 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004552 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004553 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004554 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004555 mask = mask | spv::ImageOperandsSampleMask;
4556 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004557 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004558 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4559 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004560 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004561 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004562 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4563 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004564 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004565 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004566 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4567 operands.push_back(imageOperands);
4568 }
4569 if (mask & spv::ImageOperandsSampleMask) {
4570 spv::IdImmediate imageOperand = { true, *opIt++ };
4571 operands.push_back(imageOperand);
4572 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004573 if (mask & spv::ImageOperandsLodMask) {
4574 spv::IdImmediate imageOperand = { true, *opIt++ };
4575 operands.push_back(imageOperand);
4576 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004577 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004578 spv::IdImmediate imageOperand = { true,
4579 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004580 operands.push_back(imageOperand);
4581 }
4582
John Kessenich149afc32018-08-14 13:31:43 -06004583 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004584 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004585
John Kessenich149afc32018-08-14 13:31:43 -06004586 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004587 builder.setPrecision(result[0], precision);
4588
4589 // If needed, add a conversion constructor to the proper size.
4590 if (components != node->getType().getVectorSize())
4591 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4592
4593 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004594 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004595
Jeff Bolz36831c92018-09-05 10:11:41 -05004596 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004597 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004598 spv::IdImmediate texel = { true, *(opIt + 1) };
4599 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004600 } else {
4601 spv::IdImmediate texel = { true, *opIt };
4602 operands.push_back(texel);
4603 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004604
4605 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004606 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004607 mask = mask | spv::ImageOperandsSampleMask;
4608 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 if (cracked.lod) {
4610 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4611 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4612 mask = mask | spv::ImageOperandsLodMask;
4613 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004614 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4615 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004616 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004617 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004618 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4619 operands.push_back(imageOperands);
4620 }
4621 if (mask & spv::ImageOperandsSampleMask) {
4622 spv::IdImmediate imageOperand = { true, *opIt++ };
4623 operands.push_back(imageOperand);
4624 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004625 if (mask & spv::ImageOperandsLodMask) {
4626 spv::IdImmediate imageOperand = { true, *opIt++ };
4627 operands.push_back(imageOperand);
4628 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004629 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004630 spv::IdImmediate imageOperand = { true,
4631 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004632 operands.push_back(imageOperand);
4633 }
4634
John Kessenich56bab042015-09-16 10:54:31 -06004635 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004636 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004637 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004638 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004639 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4640 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004641 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004642 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004643 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4644
Jeff Bolz36831c92018-09-05 10:11:41 -05004645 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004646 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004647 mask = mask | spv::ImageOperandsSampleMask;
4648 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004649 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004650 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4651 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4652
Jeff Bolz36831c92018-09-05 10:11:41 -05004653 mask = mask | spv::ImageOperandsLodMask;
4654 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004655 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4656 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004657 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004658 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004659 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004660 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004661 }
4662 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004663 spv::IdImmediate imageOperand = { true, *opIt++ };
4664 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004665 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004666 if (mask & spv::ImageOperandsLodMask) {
4667 spv::IdImmediate imageOperand = { true, *opIt++ };
4668 operands.push_back(imageOperand);
4669 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004670 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4671 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4672 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004673 }
4674
4675 // Create the return type that was a special structure
4676 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004677 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004678 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4679 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4680
4681 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4682
4683 // Decode the return type
4684 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4685 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004686 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004687 // Process image atomic operations
4688
4689 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4690 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004691 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004692 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004693 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004694
Jeff Bolz36831c92018-09-05 10:11:41 -05004695 spv::Id resultTypeId;
4696 // imageAtomicStore has a void return type so base the pointer type on
4697 // the type of the value operand.
4698 if (node->getOp() == glslang::EOpImageAtomicStore) {
4699 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4700 } else {
4701 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4702 }
John Kessenich56bab042015-09-16 10:54:31 -06004703 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004704
4705 std::vector<spv::Id> operands;
4706 operands.push_back(pointer);
4707 for (; opIt != arguments.end(); ++opIt)
4708 operands.push_back(*opIt);
4709
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004710 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004711 }
4712 }
4713
John Kessenicha28f7a72019-08-06 07:00:58 -06004714#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004715 // Check for fragment mask functions other than queries
4716 if (cracked.fragMask) {
4717 assert(sampler.ms);
4718
4719 auto opIt = arguments.begin();
4720 std::vector<spv::Id> operands;
4721
4722 // Extract the image if necessary
4723 if (builder.isSampledImage(params.sampler))
4724 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4725
4726 operands.push_back(params.sampler);
4727 ++opIt;
4728
4729 if (sampler.isSubpass()) {
4730 // add on the (0,0) coordinate
4731 spv::Id zero = builder.makeIntConstant(0);
4732 std::vector<spv::Id> comps;
4733 comps.push_back(zero);
4734 comps.push_back(zero);
4735 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4736 }
4737
4738 for (; opIt != arguments.end(); ++opIt)
4739 operands.push_back(*opIt);
4740
4741 spv::Op fragMaskOp = spv::OpNop;
4742 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4743 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4744 else if (node->getOp() == glslang::EOpFragmentFetch)
4745 fragMaskOp = spv::OpFragmentFetchAMD;
4746
4747 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4748 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4749 return builder.createOp(fragMaskOp, resultType(), operands);
4750 }
4751#endif
4752
Rex Xufc618912015-09-09 16:42:49 +08004753 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004754 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004755 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004756 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004757
John Kessenichfc51d282015-08-19 13:34:18 -06004758 // check for bias argument
4759 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004760 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004761 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004762 if (cracked.gather)
4763 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004764
4765 if (f16ShadowCompare)
4766 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004767 if (cracked.offset)
4768 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004769 else if (cracked.offsets)
4770 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004771 if (cracked.grad)
4772 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004773 if (cracked.lodClamp)
4774 ++nonBiasArgCount;
4775 if (sparse)
4776 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004777 if (imageFootprint)
4778 //Following three extra arguments
4779 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4780 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004781 if ((int)arguments.size() > nonBiasArgCount)
4782 bias = true;
4783 }
4784
John Kessenicha5c33d62016-06-02 23:45:21 -06004785 // See if the sampler param should really be just the SPV image part
4786 if (cracked.fetch) {
4787 // a fetch needs to have the image extracted first
4788 if (builder.isSampledImage(params.sampler))
4789 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4790 }
4791
John Kessenicha28f7a72019-08-06 07:00:58 -06004792#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004793 if (cracked.gather) {
4794 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4795 if (bias || cracked.lod ||
4796 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4797 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004798 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004799 }
4800 }
4801#endif
4802
John Kessenichfc51d282015-08-19 13:34:18 -06004803 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004804
John Kessenichfc51d282015-08-19 13:34:18 -06004805 params.coords = arguments[1];
4806 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004807 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004808
4809 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004810 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004811 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004812 ++extraArgs;
4813 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004814 params.Dref = arguments[2];
4815 ++extraArgs;
4816 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004817 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004818 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004819 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004820 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004821 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004822 dRefComp = builder.getNumComponents(params.coords) - 1;
4823 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004824 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4825 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004826
4827 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004828 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004829 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004830 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004831 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4832 !(glslangIntermediate->getStage() == EShLangCompute &&
4833 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004834 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4835 noImplicitLod = true;
4836 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004837
4838 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004839 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004840 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004841 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004842 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004843
4844 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004845 if (cracked.grad) {
4846 params.gradX = arguments[2 + extraArgs];
4847 params.gradY = arguments[3 + extraArgs];
4848 extraArgs += 2;
4849 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004850
4851 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004852 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004853 params.offset = arguments[2 + extraArgs];
4854 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004855 } else if (cracked.offsets) {
4856 params.offsets = arguments[2 + extraArgs];
4857 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004858 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004859
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004860#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004861 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004862 if (cracked.lodClamp) {
4863 params.lodClamp = arguments[2 + extraArgs];
4864 ++extraArgs;
4865 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004866 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004867 if (sparse) {
4868 params.texelOut = arguments[2 + extraArgs];
4869 ++extraArgs;
4870 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004871 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004872 if (cracked.gather && ! sampler.shadow) {
4873 // default component is 0, if missing, otherwise an argument
4874 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004875 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004876 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004877 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004878 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004879 }
Chao Chen3a137962018-09-19 11:41:27 -07004880 spv::Id resultStruct = spv::NoResult;
4881 if (imageFootprint) {
4882 //Following three extra arguments
4883 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4884 params.granularity = arguments[2 + extraArgs];
4885 params.coarse = arguments[3 + extraArgs];
4886 resultStruct = arguments[4 + extraArgs];
4887 extraArgs += 3;
4888 }
4889#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004890 // bias
4891 if (bias) {
4892 params.bias = arguments[2 + extraArgs];
4893 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004894 }
John Kessenichfc51d282015-08-19 13:34:18 -06004895
John Kessenicha28f7a72019-08-06 07:00:58 -06004896#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004897 if (imageFootprint) {
4898 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4899 builder.addCapability(spv::CapabilityImageFootprintNV);
4900
4901
4902 //resultStructType(OpenGL type) contains 5 elements:
4903 //struct gl_TextureFootprint2DNV {
4904 // uvec2 anchor;
4905 // uvec2 offset;
4906 // uvec2 mask;
4907 // uint lod;
4908 // uint granularity;
4909 //};
4910 //or
4911 //struct gl_TextureFootprint3DNV {
4912 // uvec3 anchor;
4913 // uvec3 offset;
4914 // uvec2 mask;
4915 // uint lod;
4916 // uint granularity;
4917 //};
4918 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4919 assert(builder.isStructType(resultStructType));
4920
4921 //resType (SPIR-V type) contains 6 elements:
4922 //Member 0 must be a Boolean type scalar(LOD),
4923 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4924 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4925 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4926 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4927 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4928 std::vector<spv::Id> members;
4929 members.push_back(resultType());
4930 for (int i = 0; i < 5; i++) {
4931 members.push_back(builder.getContainedTypeId(resultStructType, i));
4932 }
4933 spv::Id resType = builder.makeStructType(members, "ResType");
4934
4935 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004936 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4937 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004938
4939 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4940 for (int i = 0; i < 5; i++) {
4941 builder.clearAccessChain();
4942 builder.setAccessChainLValue(resultStruct);
4943
4944 //Accessing to a struct we created, no coherent flag is set
4945 spv::Builder::AccessChain::CoherentFlags flags;
4946 flags.clear();
4947
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004948 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004949 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4950 }
4951 return builder.createCompositeExtract(res, resultType(), 0);
4952 }
4953#endif
4954
John Kessenich65336482016-06-16 14:06:26 -06004955 // projective component (might not to move)
4956 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4957 // are divided by the last component of P."
4958 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4959 // unused components will appear after all used components."
4960 if (cracked.proj) {
4961 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4962 int projTargetComp;
4963 switch (sampler.dim) {
4964 case glslang::Esd1D: projTargetComp = 1; break;
4965 case glslang::Esd2D: projTargetComp = 2; break;
4966 case glslang::EsdRect: projTargetComp = 2; break;
4967 default: projTargetComp = projSourceComp; break;
4968 }
4969 // copy the projective coordinate if we have to
4970 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004971 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004972 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4973 projSourceComp);
4974 params.coords = builder.createCompositeInsert(projComp, params.coords,
4975 builder.getTypeId(params.coords), projTargetComp);
4976 }
4977 }
4978
Jeff Bolz36831c92018-09-05 10:11:41 -05004979 // nonprivate
4980 if (imageType.getQualifier().nonprivate) {
4981 params.nonprivate = true;
4982 }
4983
4984 // volatile
4985 if (imageType.getQualifier().volatil) {
4986 params.volatil = true;
4987 }
4988
St0fFa1184dd2018-04-09 21:08:14 +02004989 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004990 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4991 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004992 );
LoopDawg4425f242018-02-18 11:40:01 -07004993
4994 if (components != node->getType().getVectorSize())
4995 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4996
4997 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004998}
4999
5000spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5001{
5002 // Grab the function's pointer from the previously created function
5003 spv::Function* function = functionMap[node->getName().c_str()];
5004 if (! function)
5005 return 0;
5006
5007 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5008 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5009
5010 // See comments in makeFunctions() for details about the semantics for parameter passing.
5011 //
5012 // These imply we need a four step process:
5013 // 1. Evaluate the arguments
5014 // 2. Allocate and make copies of in, out, and inout arguments
5015 // 3. Make the call
5016 // 4. Copy back the results
5017
John Kessenichd3ed90b2018-05-04 11:43:03 -06005018 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005019 std::vector<spv::Builder::AccessChain> lValues;
5020 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005021 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005022 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005023 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005024 // build l-value
5025 builder.clearAccessChain();
5026 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005027 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005028 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005029 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005030 // save l-value
5031 lValues.push_back(builder.getAccessChain());
5032 } else {
5033 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005034 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005035 }
5036 }
5037
5038 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5039 // copy the original into that space.
5040 //
5041 // Also, build up the list of actual arguments to pass in for the call
5042 int lValueCount = 0;
5043 int rValueCount = 0;
5044 std::vector<spv::Id> spvArgs;
5045 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5046 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005047 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005048 builder.setAccessChain(lValues[lValueCount]);
5049 arg = builder.accessChainGetLValue();
5050 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005051 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005052 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005053 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005054 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5055 // need to copy the input into output space
5056 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005057 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005058 builder.clearAccessChain();
5059 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005060 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005061 }
5062 ++lValueCount;
5063 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005064 // process r-value, which involves a copy for a type mismatch
5065 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5066 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5067 builder.clearAccessChain();
5068 builder.setAccessChainLValue(argCopy);
5069 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5070 arg = builder.createLoad(argCopy);
5071 } else
5072 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005073 ++rValueCount;
5074 }
5075 spvArgs.push_back(arg);
5076 }
5077
5078 // 3. Make the call.
5079 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005080 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005081
5082 // 4. Copy back out an "out" arguments.
5083 lValueCount = 0;
5084 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005085 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005086 ++lValueCount;
5087 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005088 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5089 spv::Id copy = builder.createLoad(spvArgs[a]);
5090 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005091 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005092 }
5093 ++lValueCount;
5094 }
5095 }
5096
5097 return result;
5098}
5099
5100// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005101spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005102 spv::Id typeId, spv::Id left, spv::Id right,
5103 glslang::TBasicType typeProxy, bool reduceComparison)
5104{
John Kessenich66011cb2018-03-06 16:12:04 -07005105 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5106 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005107 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005108
5109 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005110 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005111 bool comparison = false;
5112
5113 switch (op) {
5114 case glslang::EOpAdd:
5115 case glslang::EOpAddAssign:
5116 if (isFloat)
5117 binOp = spv::OpFAdd;
5118 else
5119 binOp = spv::OpIAdd;
5120 break;
5121 case glslang::EOpSub:
5122 case glslang::EOpSubAssign:
5123 if (isFloat)
5124 binOp = spv::OpFSub;
5125 else
5126 binOp = spv::OpISub;
5127 break;
5128 case glslang::EOpMul:
5129 case glslang::EOpMulAssign:
5130 if (isFloat)
5131 binOp = spv::OpFMul;
5132 else
5133 binOp = spv::OpIMul;
5134 break;
5135 case glslang::EOpVectorTimesScalar:
5136 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005137 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005138 if (builder.isVector(right))
5139 std::swap(left, right);
5140 assert(builder.isScalar(right));
5141 needMatchingVectors = false;
5142 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005143 } else if (isFloat)
5144 binOp = spv::OpFMul;
5145 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005146 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005147 break;
5148 case glslang::EOpVectorTimesMatrix:
5149 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005150 binOp = spv::OpVectorTimesMatrix;
5151 break;
5152 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005153 binOp = spv::OpMatrixTimesVector;
5154 break;
5155 case glslang::EOpMatrixTimesScalar:
5156 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005157 binOp = spv::OpMatrixTimesScalar;
5158 break;
5159 case glslang::EOpMatrixTimesMatrix:
5160 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005161 binOp = spv::OpMatrixTimesMatrix;
5162 break;
5163 case glslang::EOpOuterProduct:
5164 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005165 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005166 break;
5167
5168 case glslang::EOpDiv:
5169 case glslang::EOpDivAssign:
5170 if (isFloat)
5171 binOp = spv::OpFDiv;
5172 else if (isUnsigned)
5173 binOp = spv::OpUDiv;
5174 else
5175 binOp = spv::OpSDiv;
5176 break;
5177 case glslang::EOpMod:
5178 case glslang::EOpModAssign:
5179 if (isFloat)
5180 binOp = spv::OpFMod;
5181 else if (isUnsigned)
5182 binOp = spv::OpUMod;
5183 else
5184 binOp = spv::OpSMod;
5185 break;
5186 case glslang::EOpRightShift:
5187 case glslang::EOpRightShiftAssign:
5188 if (isUnsigned)
5189 binOp = spv::OpShiftRightLogical;
5190 else
5191 binOp = spv::OpShiftRightArithmetic;
5192 break;
5193 case glslang::EOpLeftShift:
5194 case glslang::EOpLeftShiftAssign:
5195 binOp = spv::OpShiftLeftLogical;
5196 break;
5197 case glslang::EOpAnd:
5198 case glslang::EOpAndAssign:
5199 binOp = spv::OpBitwiseAnd;
5200 break;
5201 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005202 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005203 binOp = spv::OpLogicalAnd;
5204 break;
5205 case glslang::EOpInclusiveOr:
5206 case glslang::EOpInclusiveOrAssign:
5207 binOp = spv::OpBitwiseOr;
5208 break;
5209 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005210 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005211 binOp = spv::OpLogicalOr;
5212 break;
5213 case glslang::EOpExclusiveOr:
5214 case glslang::EOpExclusiveOrAssign:
5215 binOp = spv::OpBitwiseXor;
5216 break;
5217 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005218 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005219 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005220 break;
5221
5222 case glslang::EOpLessThan:
5223 case glslang::EOpGreaterThan:
5224 case glslang::EOpLessThanEqual:
5225 case glslang::EOpGreaterThanEqual:
5226 case glslang::EOpEqual:
5227 case glslang::EOpNotEqual:
5228 case glslang::EOpVectorEqual:
5229 case glslang::EOpVectorNotEqual:
5230 comparison = true;
5231 break;
5232 default:
5233 break;
5234 }
5235
John Kessenich7c1aa102015-10-15 13:29:11 -06005236 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005237 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005238 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005239 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5240 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005241 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005242
5243 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005244 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005245 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005246
qining25262b32016-05-06 17:25:16 -04005247 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005248 decorations.addNoContraction(builder, result);
5249 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005250 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005251 }
5252
5253 if (! comparison)
5254 return 0;
5255
John Kessenich7c1aa102015-10-15 13:29:11 -06005256 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005257
John Kessenich4583b612016-08-07 19:14:22 -06005258 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005259 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5260 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005261 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005262 return result;
5263 }
John Kessenich140f3df2015-06-26 16:58:36 -06005264
5265 switch (op) {
5266 case glslang::EOpLessThan:
5267 if (isFloat)
5268 binOp = spv::OpFOrdLessThan;
5269 else if (isUnsigned)
5270 binOp = spv::OpULessThan;
5271 else
5272 binOp = spv::OpSLessThan;
5273 break;
5274 case glslang::EOpGreaterThan:
5275 if (isFloat)
5276 binOp = spv::OpFOrdGreaterThan;
5277 else if (isUnsigned)
5278 binOp = spv::OpUGreaterThan;
5279 else
5280 binOp = spv::OpSGreaterThan;
5281 break;
5282 case glslang::EOpLessThanEqual:
5283 if (isFloat)
5284 binOp = spv::OpFOrdLessThanEqual;
5285 else if (isUnsigned)
5286 binOp = spv::OpULessThanEqual;
5287 else
5288 binOp = spv::OpSLessThanEqual;
5289 break;
5290 case glslang::EOpGreaterThanEqual:
5291 if (isFloat)
5292 binOp = spv::OpFOrdGreaterThanEqual;
5293 else if (isUnsigned)
5294 binOp = spv::OpUGreaterThanEqual;
5295 else
5296 binOp = spv::OpSGreaterThanEqual;
5297 break;
5298 case glslang::EOpEqual:
5299 case glslang::EOpVectorEqual:
5300 if (isFloat)
5301 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005302 else if (isBool)
5303 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005304 else
5305 binOp = spv::OpIEqual;
5306 break;
5307 case glslang::EOpNotEqual:
5308 case glslang::EOpVectorNotEqual:
5309 if (isFloat)
5310 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005311 else if (isBool)
5312 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005313 else
5314 binOp = spv::OpINotEqual;
5315 break;
5316 default:
5317 break;
5318 }
5319
qining25262b32016-05-06 17:25:16 -04005320 if (binOp != spv::OpNop) {
5321 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005322 decorations.addNoContraction(builder, result);
5323 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005324 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005325 }
John Kessenich140f3df2015-06-26 16:58:36 -06005326
5327 return 0;
5328}
5329
John Kessenich04bb8a02015-12-12 12:28:14 -07005330//
5331// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5332// These can be any of:
5333//
5334// matrix * scalar
5335// scalar * matrix
5336// matrix * matrix linear algebraic
5337// matrix * vector
5338// vector * matrix
5339// matrix * matrix componentwise
5340// matrix op matrix op in {+, -, /}
5341// matrix op scalar op in {+, -, /}
5342// scalar op matrix op in {+, -, /}
5343//
John Kessenichead86222018-03-28 18:01:20 -06005344spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5345 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005346{
5347 bool firstClass = true;
5348
5349 // First, handle first-class matrix operations (* and matrix/scalar)
5350 switch (op) {
5351 case spv::OpFDiv:
5352 if (builder.isMatrix(left) && builder.isScalar(right)) {
5353 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005354 spv::Id resultType = builder.getTypeId(right);
5355 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005356 op = spv::OpMatrixTimesScalar;
5357 } else
5358 firstClass = false;
5359 break;
5360 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005361 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005362 std::swap(left, right);
5363 assert(builder.isScalar(right));
5364 break;
5365 case spv::OpVectorTimesMatrix:
5366 assert(builder.isVector(left));
5367 assert(builder.isMatrix(right));
5368 break;
5369 case spv::OpMatrixTimesVector:
5370 assert(builder.isMatrix(left));
5371 assert(builder.isVector(right));
5372 break;
5373 case spv::OpMatrixTimesMatrix:
5374 assert(builder.isMatrix(left));
5375 assert(builder.isMatrix(right));
5376 break;
5377 default:
5378 firstClass = false;
5379 break;
5380 }
5381
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005382 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5383 firstClass = true;
5384
qining25262b32016-05-06 17:25:16 -04005385 if (firstClass) {
5386 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005387 decorations.addNoContraction(builder, result);
5388 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005389 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005390 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005391
LoopDawg592860c2016-06-09 08:57:35 -06005392 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005393 // The result type of all of them is the same type as the (a) matrix operand.
5394 // The algorithm is to:
5395 // - break the matrix(es) into vectors
5396 // - smear any scalar to a vector
5397 // - do vector operations
5398 // - make a matrix out the vector results
5399 switch (op) {
5400 case spv::OpFAdd:
5401 case spv::OpFSub:
5402 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005403 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005404 case spv::OpFMul:
5405 {
5406 // one time set up...
5407 bool leftMat = builder.isMatrix(left);
5408 bool rightMat = builder.isMatrix(right);
5409 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5410 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5411 spv::Id scalarType = builder.getScalarTypeId(typeId);
5412 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5413 std::vector<spv::Id> results;
5414 spv::Id smearVec = spv::NoResult;
5415 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005416 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005417 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005418 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005419
5420 // do each vector op
5421 for (unsigned int c = 0; c < numCols; ++c) {
5422 std::vector<unsigned int> indexes;
5423 indexes.push_back(c);
5424 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5425 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005426 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005427 decorations.addNoContraction(builder, result);
5428 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005429 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005430 }
5431
5432 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005433 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005434 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005435 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005436 }
5437 default:
5438 assert(0);
5439 return spv::NoResult;
5440 }
5441}
5442
John Kessenichead86222018-03-28 18:01:20 -06005443spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005444 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005445{
5446 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005447 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005448 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005449 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5450 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005451
5452 switch (op) {
5453 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005454 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005455 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005456 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005457 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005458 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005459 unaryOp = spv::OpSNegate;
5460 break;
5461
5462 case glslang::EOpLogicalNot:
5463 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 unaryOp = spv::OpLogicalNot;
5465 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005466 case glslang::EOpBitwiseNot:
5467 unaryOp = spv::OpNot;
5468 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005469
John Kessenich140f3df2015-06-26 16:58:36 -06005470 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005471 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005472 break;
5473 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005474 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005475 break;
5476 case glslang::EOpTranspose:
5477 unaryOp = spv::OpTranspose;
5478 break;
5479
5480 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005481 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005482 break;
5483 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005484 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005485 break;
5486 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005487 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005488 break;
5489 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005490 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005491 break;
5492 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005493 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005494 break;
5495 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005496 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005497 break;
5498 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005499 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005500 break;
5501 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005502 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005503 break;
5504
5505 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005506 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005507 break;
5508 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005509 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 break;
5511 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005512 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005513 break;
5514 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005515 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005516 break;
5517 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005518 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005519 break;
5520 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005521 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 break;
5523
5524 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005525 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005526 break;
5527 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530
5531 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005532 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005535 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005536 break;
5537 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005538 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005539 break;
5540 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005541 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005542 break;
5543 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005544 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005545 break;
5546 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005547 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005548 break;
5549
5550 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005551 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005552 break;
5553 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005554 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005555 break;
5556 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005557 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005558 break;
5559 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005560 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005561 break;
5562 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005563 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005564 break;
5565 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005566 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005567 break;
5568
5569 case glslang::EOpIsNan:
5570 unaryOp = spv::OpIsNan;
5571 break;
5572 case glslang::EOpIsInf:
5573 unaryOp = spv::OpIsInf;
5574 break;
LoopDawg592860c2016-06-09 08:57:35 -06005575 case glslang::EOpIsFinite:
5576 unaryOp = spv::OpIsFinite;
5577 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005578
Rex Xucbc426e2015-12-15 16:03:10 +08005579 case glslang::EOpFloatBitsToInt:
5580 case glslang::EOpFloatBitsToUint:
5581 case glslang::EOpIntBitsToFloat:
5582 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005583 case glslang::EOpDoubleBitsToInt64:
5584 case glslang::EOpDoubleBitsToUint64:
5585 case glslang::EOpInt64BitsToDouble:
5586 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005587 case glslang::EOpFloat16BitsToInt16:
5588 case glslang::EOpFloat16BitsToUint16:
5589 case glslang::EOpInt16BitsToFloat16:
5590 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005591 unaryOp = spv::OpBitcast;
5592 break;
5593
John Kessenich140f3df2015-06-26 16:58:36 -06005594 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005595 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005596 break;
5597 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005598 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005599 break;
5600 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005601 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005602 break;
5603 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005604 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005605 break;
5606 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005607 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005608 break;
5609 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005610 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005611 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005612#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005613 case glslang::EOpPackSnorm4x8:
5614 libCall = spv::GLSLstd450PackSnorm4x8;
5615 break;
5616 case glslang::EOpUnpackSnorm4x8:
5617 libCall = spv::GLSLstd450UnpackSnorm4x8;
5618 break;
5619 case glslang::EOpPackUnorm4x8:
5620 libCall = spv::GLSLstd450PackUnorm4x8;
5621 break;
5622 case glslang::EOpUnpackUnorm4x8:
5623 libCall = spv::GLSLstd450UnpackUnorm4x8;
5624 break;
5625 case glslang::EOpPackDouble2x32:
5626 libCall = spv::GLSLstd450PackDouble2x32;
5627 break;
5628 case glslang::EOpUnpackDouble2x32:
5629 libCall = spv::GLSLstd450UnpackDouble2x32;
5630 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005631#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005632
Rex Xu8ff43de2016-04-22 16:51:45 +08005633 case glslang::EOpPackInt2x32:
5634 case glslang::EOpUnpackInt2x32:
5635 case glslang::EOpPackUint2x32:
5636 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005637 case glslang::EOpPack16:
5638 case glslang::EOpPack32:
5639 case glslang::EOpPack64:
5640 case glslang::EOpUnpack32:
5641 case glslang::EOpUnpack16:
5642 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005643 case glslang::EOpPackInt2x16:
5644 case glslang::EOpUnpackInt2x16:
5645 case glslang::EOpPackUint2x16:
5646 case glslang::EOpUnpackUint2x16:
5647 case glslang::EOpPackInt4x16:
5648 case glslang::EOpUnpackInt4x16:
5649 case glslang::EOpPackUint4x16:
5650 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005651 case glslang::EOpPackFloat2x16:
5652 case glslang::EOpUnpackFloat2x16:
5653 unaryOp = spv::OpBitcast;
5654 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005655
John Kessenich140f3df2015-06-26 16:58:36 -06005656 case glslang::EOpDPdx:
5657 unaryOp = spv::OpDPdx;
5658 break;
5659 case glslang::EOpDPdy:
5660 unaryOp = spv::OpDPdy;
5661 break;
5662 case glslang::EOpFwidth:
5663 unaryOp = spv::OpFwidth;
5664 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005665
John Kessenich140f3df2015-06-26 16:58:36 -06005666 case glslang::EOpAny:
5667 unaryOp = spv::OpAny;
5668 break;
5669 case glslang::EOpAll:
5670 unaryOp = spv::OpAll;
5671 break;
5672
5673 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005674 if (isFloat)
5675 libCall = spv::GLSLstd450FAbs;
5676 else
5677 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005678 break;
5679 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005680 if (isFloat)
5681 libCall = spv::GLSLstd450FSign;
5682 else
5683 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005684 break;
5685
John Kessenicha28f7a72019-08-06 07:00:58 -06005686#ifndef GLSLANG_WEB
5687 case glslang::EOpDPdxFine:
5688 unaryOp = spv::OpDPdxFine;
5689 break;
5690 case glslang::EOpDPdyFine:
5691 unaryOp = spv::OpDPdyFine;
5692 break;
5693 case glslang::EOpFwidthFine:
5694 unaryOp = spv::OpFwidthFine;
5695 break;
5696 case glslang::EOpDPdxCoarse:
5697 unaryOp = spv::OpDPdxCoarse;
5698 break;
5699 case glslang::EOpDPdyCoarse:
5700 unaryOp = spv::OpDPdyCoarse;
5701 break;
5702 case glslang::EOpFwidthCoarse:
5703 unaryOp = spv::OpFwidthCoarse;
5704 break;
5705 case glslang::EOpInterpolateAtCentroid:
5706 if (typeProxy == glslang::EbtFloat16)
5707 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5708 libCall = spv::GLSLstd450InterpolateAtCentroid;
5709 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005710 case glslang::EOpAtomicCounterIncrement:
5711 case glslang::EOpAtomicCounterDecrement:
5712 case glslang::EOpAtomicCounter:
5713 {
5714 // Handle all of the atomics in one place, in createAtomicOperation()
5715 std::vector<spv::Id> operands;
5716 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005717 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005718 }
5719
John Kessenichfc51d282015-08-19 13:34:18 -06005720 case glslang::EOpBitFieldReverse:
5721 unaryOp = spv::OpBitReverse;
5722 break;
5723 case glslang::EOpBitCount:
5724 unaryOp = spv::OpBitCount;
5725 break;
5726 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005727 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005728 break;
5729 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005730 if (isUnsigned)
5731 libCall = spv::GLSLstd450FindUMsb;
5732 else
5733 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005734 break;
5735
Rex Xu574ab042016-04-14 16:53:07 +08005736 case glslang::EOpBallot:
5737 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005738 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005739 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005740 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005741 case glslang::EOpMinInvocations:
5742 case glslang::EOpMaxInvocations:
5743 case glslang::EOpAddInvocations:
5744 case glslang::EOpMinInvocationsNonUniform:
5745 case glslang::EOpMaxInvocationsNonUniform:
5746 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005747 case glslang::EOpMinInvocationsInclusiveScan:
5748 case glslang::EOpMaxInvocationsInclusiveScan:
5749 case glslang::EOpAddInvocationsInclusiveScan:
5750 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5751 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5752 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5753 case glslang::EOpMinInvocationsExclusiveScan:
5754 case glslang::EOpMaxInvocationsExclusiveScan:
5755 case glslang::EOpAddInvocationsExclusiveScan:
5756 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5757 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5758 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005759 {
5760 std::vector<spv::Id> operands;
5761 operands.push_back(operand);
5762 return createInvocationsOperation(op, typeId, operands, typeProxy);
5763 }
John Kessenich66011cb2018-03-06 16:12:04 -07005764 case glslang::EOpSubgroupAll:
5765 case glslang::EOpSubgroupAny:
5766 case glslang::EOpSubgroupAllEqual:
5767 case glslang::EOpSubgroupBroadcastFirst:
5768 case glslang::EOpSubgroupBallot:
5769 case glslang::EOpSubgroupInverseBallot:
5770 case glslang::EOpSubgroupBallotBitCount:
5771 case glslang::EOpSubgroupBallotInclusiveBitCount:
5772 case glslang::EOpSubgroupBallotExclusiveBitCount:
5773 case glslang::EOpSubgroupBallotFindLSB:
5774 case glslang::EOpSubgroupBallotFindMSB:
5775 case glslang::EOpSubgroupAdd:
5776 case glslang::EOpSubgroupMul:
5777 case glslang::EOpSubgroupMin:
5778 case glslang::EOpSubgroupMax:
5779 case glslang::EOpSubgroupAnd:
5780 case glslang::EOpSubgroupOr:
5781 case glslang::EOpSubgroupXor:
5782 case glslang::EOpSubgroupInclusiveAdd:
5783 case glslang::EOpSubgroupInclusiveMul:
5784 case glslang::EOpSubgroupInclusiveMin:
5785 case glslang::EOpSubgroupInclusiveMax:
5786 case glslang::EOpSubgroupInclusiveAnd:
5787 case glslang::EOpSubgroupInclusiveOr:
5788 case glslang::EOpSubgroupInclusiveXor:
5789 case glslang::EOpSubgroupExclusiveAdd:
5790 case glslang::EOpSubgroupExclusiveMul:
5791 case glslang::EOpSubgroupExclusiveMin:
5792 case glslang::EOpSubgroupExclusiveMax:
5793 case glslang::EOpSubgroupExclusiveAnd:
5794 case glslang::EOpSubgroupExclusiveOr:
5795 case glslang::EOpSubgroupExclusiveXor:
5796 case glslang::EOpSubgroupQuadSwapHorizontal:
5797 case glslang::EOpSubgroupQuadSwapVertical:
5798 case glslang::EOpSubgroupQuadSwapDiagonal: {
5799 std::vector<spv::Id> operands;
5800 operands.push_back(operand);
5801 return createSubgroupOperation(op, typeId, operands, typeProxy);
5802 }
Rex Xu9d93a232016-05-05 12:30:44 +08005803 case glslang::EOpMbcnt:
5804 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5805 libCall = spv::MbcntAMD;
5806 break;
5807
5808 case glslang::EOpCubeFaceIndex:
5809 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5810 libCall = spv::CubeFaceIndexAMD;
5811 break;
5812
5813 case glslang::EOpCubeFaceCoord:
5814 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5815 libCall = spv::CubeFaceCoordAMD;
5816 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005817 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005818 unaryOp = spv::OpGroupNonUniformPartitionNV;
5819 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005820 case glslang::EOpConstructReference:
5821 unaryOp = spv::OpBitcast;
5822 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005823#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005824
5825 case glslang::EOpCopyObject:
5826 unaryOp = spv::OpCopyObject;
5827 break;
5828
John Kessenich140f3df2015-06-26 16:58:36 -06005829 default:
5830 return 0;
5831 }
5832
5833 spv::Id id;
5834 if (libCall >= 0) {
5835 std::vector<spv::Id> args;
5836 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005837 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005838 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005839 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005840 }
John Kessenich140f3df2015-06-26 16:58:36 -06005841
John Kessenichb9197c82019-08-11 07:41:45 -06005842 decorations.addNoContraction(builder, id);
5843 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005844 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005845}
5846
John Kessenich7a53f762016-01-20 11:19:27 -07005847// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005848spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5849 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005850{
5851 // Handle unary operations vector by vector.
5852 // The result type is the same type as the original type.
5853 // The algorithm is to:
5854 // - break the matrix into vectors
5855 // - apply the operation to each vector
5856 // - make a matrix out the vector results
5857
5858 // get the types sorted out
5859 int numCols = builder.getNumColumns(operand);
5860 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005861 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5862 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005863 std::vector<spv::Id> results;
5864
5865 // do each vector op
5866 for (int c = 0; c < numCols; ++c) {
5867 std::vector<unsigned int> indexes;
5868 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005869 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5870 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005871 decorations.addNoContraction(builder, destVec);
5872 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005873 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005874 }
5875
5876 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005877 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005878 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005879 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005880}
5881
John Kessenichad7645f2018-06-04 19:11:25 -06005882// For converting integers where both the bitwidth and the signedness could
5883// change, but only do the width change here. The caller is still responsible
5884// for the signedness conversion.
5885spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005886{
John Kessenichad7645f2018-06-04 19:11:25 -06005887 // Get the result type width, based on the type to convert to.
5888 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005889 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005890 case glslang::EOpConvInt16ToUint8:
5891 case glslang::EOpConvIntToUint8:
5892 case glslang::EOpConvInt64ToUint8:
5893 case glslang::EOpConvUint16ToInt8:
5894 case glslang::EOpConvUintToInt8:
5895 case glslang::EOpConvUint64ToInt8:
5896 width = 8;
5897 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005898 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005899 case glslang::EOpConvIntToUint16:
5900 case glslang::EOpConvInt64ToUint16:
5901 case glslang::EOpConvUint8ToInt16:
5902 case glslang::EOpConvUintToInt16:
5903 case glslang::EOpConvUint64ToInt16:
5904 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005905 break;
5906 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005907 case glslang::EOpConvInt16ToUint:
5908 case glslang::EOpConvInt64ToUint:
5909 case glslang::EOpConvUint8ToInt:
5910 case glslang::EOpConvUint16ToInt:
5911 case glslang::EOpConvUint64ToInt:
5912 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005913 break;
5914 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005915 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005916 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005917 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005918 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005919 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005920 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005921 break;
5922
5923 default:
5924 assert(false && "Default missing");
5925 break;
5926 }
5927
John Kessenichad7645f2018-06-04 19:11:25 -06005928 // Get the conversion operation and result type,
5929 // based on the target width, but the source type.
5930 spv::Id type = spv::NoType;
5931 spv::Op convOp = spv::OpNop;
5932 switch(op) {
5933 case glslang::EOpConvInt8ToUint16:
5934 case glslang::EOpConvInt8ToUint:
5935 case glslang::EOpConvInt8ToUint64:
5936 case glslang::EOpConvInt16ToUint8:
5937 case glslang::EOpConvInt16ToUint:
5938 case glslang::EOpConvInt16ToUint64:
5939 case glslang::EOpConvIntToUint8:
5940 case glslang::EOpConvIntToUint16:
5941 case glslang::EOpConvIntToUint64:
5942 case glslang::EOpConvInt64ToUint8:
5943 case glslang::EOpConvInt64ToUint16:
5944 case glslang::EOpConvInt64ToUint:
5945 convOp = spv::OpSConvert;
5946 type = builder.makeIntType(width);
5947 break;
5948 default:
5949 convOp = spv::OpUConvert;
5950 type = builder.makeUintType(width);
5951 break;
5952 }
5953
John Kessenich66011cb2018-03-06 16:12:04 -07005954 if (vectorSize > 0)
5955 type = builder.makeVectorType(type, vectorSize);
5956
John Kessenichad7645f2018-06-04 19:11:25 -06005957 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005958}
5959
John Kessenichead86222018-03-28 18:01:20 -06005960spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5961 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005962{
5963 spv::Op convOp = spv::OpNop;
5964 spv::Id zero = 0;
5965 spv::Id one = 0;
5966
5967 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5968
5969 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005970 case glslang::EOpConvIntToBool:
5971 case glslang::EOpConvUintToBool:
5972 zero = builder.makeUintConstant(0);
5973 zero = makeSmearedConstant(zero, vectorSize);
5974 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005975 case glslang::EOpConvFloatToBool:
5976 zero = builder.makeFloatConstant(0.0F);
5977 zero = makeSmearedConstant(zero, vectorSize);
5978 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005979 case glslang::EOpConvBoolToFloat:
5980 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005981 zero = builder.makeFloatConstant(0.0F);
5982 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005983 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005984
John Kessenich140f3df2015-06-26 16:58:36 -06005985 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005986 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06005987#ifndef GLSLANG_WEB
5988 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08005989 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005990 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005991 } else
5992#endif
5993 {
5994 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005995 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005996 }
Rex Xucabbb782017-03-24 13:41:14 +08005997
John Kessenich140f3df2015-06-26 16:58:36 -06005998 convOp = spv::OpSelect;
5999 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006000
John Kessenich140f3df2015-06-26 16:58:36 -06006001 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006002 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006003#ifndef GLSLANG_WEB
6004 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006005 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006006 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006007 } else
6008#endif
6009 {
6010 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006011 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006012 }
Rex Xucabbb782017-03-24 13:41:14 +08006013
John Kessenich140f3df2015-06-26 16:58:36 -06006014 convOp = spv::OpSelect;
6015 break;
6016
John Kessenich66011cb2018-03-06 16:12:04 -07006017 case glslang::EOpConvInt8ToFloat16:
6018 case glslang::EOpConvInt8ToFloat:
6019 case glslang::EOpConvInt8ToDouble:
6020 case glslang::EOpConvInt16ToFloat16:
6021 case glslang::EOpConvInt16ToFloat:
6022 case glslang::EOpConvInt16ToDouble:
6023 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006024 case glslang::EOpConvIntToFloat:
6025 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006026 case glslang::EOpConvInt64ToFloat:
6027 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006028 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006029 convOp = spv::OpConvertSToF;
6030 break;
6031
John Kessenich66011cb2018-03-06 16:12:04 -07006032 case glslang::EOpConvUint8ToFloat16:
6033 case glslang::EOpConvUint8ToFloat:
6034 case glslang::EOpConvUint8ToDouble:
6035 case glslang::EOpConvUint16ToFloat16:
6036 case glslang::EOpConvUint16ToFloat:
6037 case glslang::EOpConvUint16ToDouble:
6038 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006039 case glslang::EOpConvUintToFloat:
6040 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006041 case glslang::EOpConvUint64ToFloat:
6042 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006043 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006044 convOp = spv::OpConvertUToF;
6045 break;
6046
John Kessenich66011cb2018-03-06 16:12:04 -07006047 case glslang::EOpConvFloat16ToInt8:
6048 case glslang::EOpConvFloatToInt8:
6049 case glslang::EOpConvDoubleToInt8:
6050 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006051 case glslang::EOpConvFloatToInt16:
6052 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006053 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006054 case glslang::EOpConvFloatToInt:
6055 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006056 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006057 case glslang::EOpConvFloatToInt64:
6058 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006059 convOp = spv::OpConvertFToS;
6060 break;
6061
John Kessenich66011cb2018-03-06 16:12:04 -07006062 case glslang::EOpConvUint8ToInt8:
6063 case glslang::EOpConvInt8ToUint8:
6064 case glslang::EOpConvUint16ToInt16:
6065 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006066 case glslang::EOpConvUintToInt:
6067 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006068 case glslang::EOpConvUint64ToInt64:
6069 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006070 if (builder.isInSpecConstCodeGenMode()) {
6071 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006072#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006073 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6074 zero = builder.makeUint8Constant(0);
6075 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006076 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006077 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6078 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006079 } else
6080#endif
6081 {
Rex Xucabbb782017-03-24 13:41:14 +08006082 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006083 }
qining189b2032016-04-12 23:16:20 -04006084 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006085 // Use OpIAdd, instead of OpBitcast to do the conversion when
6086 // generating for OpSpecConstantOp instruction.
6087 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6088 }
6089 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006090 convOp = spv::OpBitcast;
6091 break;
6092
John Kessenich66011cb2018-03-06 16:12:04 -07006093 case glslang::EOpConvFloat16ToUint8:
6094 case glslang::EOpConvFloatToUint8:
6095 case glslang::EOpConvDoubleToUint8:
6096 case glslang::EOpConvFloat16ToUint16:
6097 case glslang::EOpConvFloatToUint16:
6098 case glslang::EOpConvDoubleToUint16:
6099 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006100 case glslang::EOpConvFloatToUint:
6101 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006102 case glslang::EOpConvFloatToUint64:
6103 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006104 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006105 convOp = spv::OpConvertFToU;
6106 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006107
John Kessenich39697cd2019-08-08 10:35:51 -06006108#ifndef GLSLANG_WEB
6109 case glslang::EOpConvInt8ToBool:
6110 case glslang::EOpConvUint8ToBool:
6111 zero = builder.makeUint8Constant(0);
6112 zero = makeSmearedConstant(zero, vectorSize);
6113 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6114 case glslang::EOpConvInt16ToBool:
6115 case glslang::EOpConvUint16ToBool:
6116 zero = builder.makeUint16Constant(0);
6117 zero = makeSmearedConstant(zero, vectorSize);
6118 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6119 case glslang::EOpConvInt64ToBool:
6120 case glslang::EOpConvUint64ToBool:
6121 zero = builder.makeUint64Constant(0);
6122 zero = makeSmearedConstant(zero, vectorSize);
6123 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6124 case glslang::EOpConvDoubleToBool:
6125 zero = builder.makeDoubleConstant(0.0);
6126 zero = makeSmearedConstant(zero, vectorSize);
6127 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6128 case glslang::EOpConvFloat16ToBool:
6129 zero = builder.makeFloat16Constant(0.0F);
6130 zero = makeSmearedConstant(zero, vectorSize);
6131 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6132 case glslang::EOpConvBoolToDouble:
6133 convOp = spv::OpSelect;
6134 zero = builder.makeDoubleConstant(0.0);
6135 one = builder.makeDoubleConstant(1.0);
6136 break;
6137 case glslang::EOpConvBoolToFloat16:
6138 convOp = spv::OpSelect;
6139 zero = builder.makeFloat16Constant(0.0F);
6140 one = builder.makeFloat16Constant(1.0F);
6141 break;
6142 case glslang::EOpConvBoolToInt8:
6143 zero = builder.makeInt8Constant(0);
6144 one = builder.makeInt8Constant(1);
6145 convOp = spv::OpSelect;
6146 break;
6147 case glslang::EOpConvBoolToUint8:
6148 zero = builder.makeUint8Constant(0);
6149 one = builder.makeUint8Constant(1);
6150 convOp = spv::OpSelect;
6151 break;
6152 case glslang::EOpConvBoolToInt16:
6153 zero = builder.makeInt16Constant(0);
6154 one = builder.makeInt16Constant(1);
6155 convOp = spv::OpSelect;
6156 break;
6157 case glslang::EOpConvBoolToUint16:
6158 zero = builder.makeUint16Constant(0);
6159 one = builder.makeUint16Constant(1);
6160 convOp = spv::OpSelect;
6161 break;
6162 case glslang::EOpConvDoubleToFloat:
6163 case glslang::EOpConvFloatToDouble:
6164 case glslang::EOpConvDoubleToFloat16:
6165 case glslang::EOpConvFloat16ToDouble:
6166 case glslang::EOpConvFloatToFloat16:
6167 case glslang::EOpConvFloat16ToFloat:
6168 convOp = spv::OpFConvert;
6169 if (builder.isMatrixType(destType))
6170 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6171 break;
6172
John Kessenich66011cb2018-03-06 16:12:04 -07006173 case glslang::EOpConvInt8ToInt16:
6174 case glslang::EOpConvInt8ToInt:
6175 case glslang::EOpConvInt8ToInt64:
6176 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006177 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006178 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006179 case glslang::EOpConvIntToInt8:
6180 case glslang::EOpConvIntToInt16:
6181 case glslang::EOpConvIntToInt64:
6182 case glslang::EOpConvInt64ToInt8:
6183 case glslang::EOpConvInt64ToInt16:
6184 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006185 convOp = spv::OpSConvert;
6186 break;
6187
John Kessenich66011cb2018-03-06 16:12:04 -07006188 case glslang::EOpConvUint8ToUint16:
6189 case glslang::EOpConvUint8ToUint:
6190 case glslang::EOpConvUint8ToUint64:
6191 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006192 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006193 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006194 case glslang::EOpConvUintToUint8:
6195 case glslang::EOpConvUintToUint16:
6196 case glslang::EOpConvUintToUint64:
6197 case glslang::EOpConvUint64ToUint8:
6198 case glslang::EOpConvUint64ToUint16:
6199 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006200 convOp = spv::OpUConvert;
6201 break;
6202
John Kessenich66011cb2018-03-06 16:12:04 -07006203 case glslang::EOpConvInt8ToUint16:
6204 case glslang::EOpConvInt8ToUint:
6205 case glslang::EOpConvInt8ToUint64:
6206 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006207 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006208 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006209 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006210 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006211 case glslang::EOpConvIntToUint64:
6212 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006213 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006214 case glslang::EOpConvInt64ToUint:
6215 case glslang::EOpConvUint8ToInt16:
6216 case glslang::EOpConvUint8ToInt:
6217 case glslang::EOpConvUint8ToInt64:
6218 case glslang::EOpConvUint16ToInt8:
6219 case glslang::EOpConvUint16ToInt:
6220 case glslang::EOpConvUint16ToInt64:
6221 case glslang::EOpConvUintToInt8:
6222 case glslang::EOpConvUintToInt16:
6223 case glslang::EOpConvUintToInt64:
6224 case glslang::EOpConvUint64ToInt8:
6225 case glslang::EOpConvUint64ToInt16:
6226 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006227 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006228 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006229
6230 if (builder.isInSpecConstCodeGenMode()) {
6231 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006232 switch(op) {
6233 case glslang::EOpConvInt16ToUint8:
6234 case glslang::EOpConvIntToUint8:
6235 case glslang::EOpConvInt64ToUint8:
6236 case glslang::EOpConvUint16ToInt8:
6237 case glslang::EOpConvUintToInt8:
6238 case glslang::EOpConvUint64ToInt8:
6239 zero = builder.makeUint8Constant(0);
6240 break;
6241 case glslang::EOpConvInt8ToUint16:
6242 case glslang::EOpConvIntToUint16:
6243 case glslang::EOpConvInt64ToUint16:
6244 case glslang::EOpConvUint8ToInt16:
6245 case glslang::EOpConvUintToInt16:
6246 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006247 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006248 break;
6249 case glslang::EOpConvInt8ToUint:
6250 case glslang::EOpConvInt16ToUint:
6251 case glslang::EOpConvInt64ToUint:
6252 case glslang::EOpConvUint8ToInt:
6253 case glslang::EOpConvUint16ToInt:
6254 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006255 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006256 break;
6257 case glslang::EOpConvInt8ToUint64:
6258 case glslang::EOpConvInt16ToUint64:
6259 case glslang::EOpConvIntToUint64:
6260 case glslang::EOpConvUint8ToInt64:
6261 case glslang::EOpConvUint16ToInt64:
6262 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006263 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006264 break;
6265 default:
6266 assert(false && "Default missing");
6267 break;
6268 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006269 zero = makeSmearedConstant(zero, vectorSize);
6270 // Use OpIAdd, instead of OpBitcast to do the conversion when
6271 // generating for OpSpecConstantOp instruction.
6272 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6273 }
6274 // For normal run-time conversion instruction, use OpBitcast.
6275 convOp = spv::OpBitcast;
6276 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006277 case glslang::EOpConvUint64ToPtr:
6278 convOp = spv::OpConvertUToPtr;
6279 break;
6280 case glslang::EOpConvPtrToUint64:
6281 convOp = spv::OpConvertPtrToU;
6282 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006283#endif
6284
John Kessenich140f3df2015-06-26 16:58:36 -06006285 default:
6286 break;
6287 }
6288
6289 spv::Id result = 0;
6290 if (convOp == spv::OpNop)
6291 return result;
6292
6293 if (convOp == spv::OpSelect) {
6294 zero = makeSmearedConstant(zero, vectorSize);
6295 one = makeSmearedConstant(one, vectorSize);
6296 result = builder.createTriOp(convOp, destType, operand, one, zero);
6297 } else
6298 result = builder.createUnaryOp(convOp, destType, operand);
6299
John Kessenichead86222018-03-28 18:01:20 -06006300 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006301 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006302 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006303}
6304
6305spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6306{
6307 if (vectorSize == 0)
6308 return constant;
6309
6310 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6311 std::vector<spv::Id> components;
6312 for (int c = 0; c < vectorSize; ++c)
6313 components.push_back(constant);
6314 return builder.makeCompositeConstant(vectorTypeId, components);
6315}
6316
John Kessenich426394d2015-07-23 10:22:48 -06006317// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006318spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006319{
6320 spv::Op opCode = spv::OpNop;
6321
6322 switch (op) {
6323 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006324 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006325 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006326 opCode = spv::OpAtomicIAdd;
6327 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006328 case glslang::EOpAtomicCounterSubtract:
6329 opCode = spv::OpAtomicISub;
6330 break;
John Kessenich426394d2015-07-23 10:22:48 -06006331 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006332 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006333 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006334 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006335 break;
6336 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006337 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006338 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006339 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006340 break;
6341 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006342 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006343 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006344 opCode = spv::OpAtomicAnd;
6345 break;
6346 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006347 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006348 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006349 opCode = spv::OpAtomicOr;
6350 break;
6351 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006352 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006353 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006354 opCode = spv::OpAtomicXor;
6355 break;
6356 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006357 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006358 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006359 opCode = spv::OpAtomicExchange;
6360 break;
6361 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006362 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006363 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006364 opCode = spv::OpAtomicCompareExchange;
6365 break;
6366 case glslang::EOpAtomicCounterIncrement:
6367 opCode = spv::OpAtomicIIncrement;
6368 break;
6369 case glslang::EOpAtomicCounterDecrement:
6370 opCode = spv::OpAtomicIDecrement;
6371 break;
6372 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006373 case glslang::EOpImageAtomicLoad:
6374 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006375 opCode = spv::OpAtomicLoad;
6376 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006377 case glslang::EOpAtomicStore:
6378 case glslang::EOpImageAtomicStore:
6379 opCode = spv::OpAtomicStore;
6380 break;
John Kessenich426394d2015-07-23 10:22:48 -06006381 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006382 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006383 break;
6384 }
6385
Rex Xue8fe8b02017-09-26 15:42:56 +08006386 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6387 builder.addCapability(spv::CapabilityInt64Atomics);
6388
John Kessenich426394d2015-07-23 10:22:48 -06006389 // Sort out the operands
6390 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006391 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006392 // - compare-exchange swaps the value and comparator
6393 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006394 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006395 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6396 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6397 spv::Id scopeId;
6398 if (glslangIntermediate->usingVulkanMemoryModel()) {
6399 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6400 } else {
6401 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6402 }
6403 // semantics default to relaxed
John Kessenichb9197c82019-08-11 07:41:45 -06006404 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() ?
6405 spv::MemorySemanticsVolatileMask :
6406 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006407 spv::Id semanticsId2 = semanticsId;
6408
6409 pointerId = operands[0];
6410 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6411 // no additional operands
6412 } else if (opCode == spv::OpAtomicCompareExchange) {
6413 compareId = operands[1];
6414 valueId = operands[2];
6415 if (operands.size() > 3) {
6416 scopeId = operands[3];
6417 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6418 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6419 }
6420 } else if (opCode == spv::OpAtomicLoad) {
6421 if (operands.size() > 1) {
6422 scopeId = operands[1];
6423 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6424 }
6425 } else {
6426 // atomic store or RMW
6427 valueId = operands[1];
6428 if (operands.size() > 2) {
6429 scopeId = operands[2];
6430 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6431 }
Rex Xu04db3f52015-09-16 11:44:02 +08006432 }
John Kessenich426394d2015-07-23 10:22:48 -06006433
Jeff Bolz36831c92018-09-05 10:11:41 -05006434 // Check for capabilities
6435 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006436 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6437 spv::MemorySemanticsMakeVisibleKHRMask |
6438 spv::MemorySemanticsOutputMemoryKHRMask |
6439 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006440 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6441 }
John Kessenich426394d2015-07-23 10:22:48 -06006442
Jeff Bolz36831c92018-09-05 10:11:41 -05006443 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6444 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6445 }
John Kessenich48d6e792017-10-06 21:21:48 -06006446
Jeff Bolz36831c92018-09-05 10:11:41 -05006447 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6448 spvAtomicOperands.push_back(pointerId);
6449 spvAtomicOperands.push_back(scopeId);
6450 spvAtomicOperands.push_back(semanticsId);
6451 if (opCode == spv::OpAtomicCompareExchange) {
6452 spvAtomicOperands.push_back(semanticsId2);
6453 spvAtomicOperands.push_back(valueId);
6454 spvAtomicOperands.push_back(compareId);
6455 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6456 spvAtomicOperands.push_back(valueId);
6457 }
John Kessenich48d6e792017-10-06 21:21:48 -06006458
Jeff Bolz36831c92018-09-05 10:11:41 -05006459 if (opCode == spv::OpAtomicStore) {
6460 builder.createNoResultOp(opCode, spvAtomicOperands);
6461 return 0;
6462 } else {
6463 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6464
6465 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6466 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6467 if (op == glslang::EOpAtomicCounterDecrement)
6468 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6469
6470 return resultId;
6471 }
John Kessenich426394d2015-07-23 10:22:48 -06006472}
6473
John Kessenich91cef522016-05-05 16:45:40 -06006474// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006475spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006476{
John Kessenich66011cb2018-03-06 16:12:04 -07006477 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6478 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006479
Rex Xu51596642016-09-21 18:56:12 +08006480 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006481 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006482 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6483
chaocf200da82016-12-20 12:44:35 -08006484 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6485 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006486 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6487 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006488 } else if (op == glslang::EOpAnyInvocation ||
6489 op == glslang::EOpAllInvocations ||
6490 op == glslang::EOpAllInvocationsEqual) {
6491 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6492 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006493 } else {
6494 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006495 if (op == glslang::EOpMinInvocationsNonUniform ||
6496 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006497 op == glslang::EOpAddInvocationsNonUniform ||
6498 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6499 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6500 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6501 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6502 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6503 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006504 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006505
Rex Xu430ef402016-10-14 17:22:23 +08006506 switch (op) {
6507 case glslang::EOpMinInvocations:
6508 case glslang::EOpMaxInvocations:
6509 case glslang::EOpAddInvocations:
6510 case glslang::EOpMinInvocationsNonUniform:
6511 case glslang::EOpMaxInvocationsNonUniform:
6512 case glslang::EOpAddInvocationsNonUniform:
6513 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006514 break;
6515 case glslang::EOpMinInvocationsInclusiveScan:
6516 case glslang::EOpMaxInvocationsInclusiveScan:
6517 case glslang::EOpAddInvocationsInclusiveScan:
6518 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6519 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6520 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6521 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006522 break;
6523 case glslang::EOpMinInvocationsExclusiveScan:
6524 case glslang::EOpMaxInvocationsExclusiveScan:
6525 case glslang::EOpAddInvocationsExclusiveScan:
6526 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6527 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6528 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6529 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006530 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006531 default:
6532 break;
Rex Xu430ef402016-10-14 17:22:23 +08006533 }
John Kessenich149afc32018-08-14 13:31:43 -06006534 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6535 spvGroupOperands.push_back(scope);
6536 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006537 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006538 spvGroupOperands.push_back(groupOp);
6539 }
Rex Xu51596642016-09-21 18:56:12 +08006540 }
6541
John Kessenich149afc32018-08-14 13:31:43 -06006542 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6543 spv::IdImmediate op = { true, *opIt };
6544 spvGroupOperands.push_back(op);
6545 }
John Kessenich91cef522016-05-05 16:45:40 -06006546
6547 switch (op) {
6548 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006549 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006550 break;
John Kessenich91cef522016-05-05 16:45:40 -06006551 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006552 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006553 break;
John Kessenich91cef522016-05-05 16:45:40 -06006554 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006555 opCode = spv::OpSubgroupAllEqualKHR;
6556 break;
Rex Xu51596642016-09-21 18:56:12 +08006557 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006558 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006559 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006560 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006561 break;
6562 case glslang::EOpReadFirstInvocation:
6563 opCode = spv::OpSubgroupFirstInvocationKHR;
6564 break;
6565 case glslang::EOpBallot:
6566 {
6567 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6568 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6569 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6570 //
6571 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6572 //
6573 spv::Id uintType = builder.makeUintType(32);
6574 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6575 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6576
6577 std::vector<spv::Id> components;
6578 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6579 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6580
6581 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6582 return builder.createUnaryOp(spv::OpBitcast, typeId,
6583 builder.createCompositeConstruct(uvec2Type, components));
6584 }
6585
Rex Xu9d93a232016-05-05 12:30:44 +08006586 case glslang::EOpMinInvocations:
6587 case glslang::EOpMaxInvocations:
6588 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006589 case glslang::EOpMinInvocationsInclusiveScan:
6590 case glslang::EOpMaxInvocationsInclusiveScan:
6591 case glslang::EOpAddInvocationsInclusiveScan:
6592 case glslang::EOpMinInvocationsExclusiveScan:
6593 case glslang::EOpMaxInvocationsExclusiveScan:
6594 case glslang::EOpAddInvocationsExclusiveScan:
6595 if (op == glslang::EOpMinInvocations ||
6596 op == glslang::EOpMinInvocationsInclusiveScan ||
6597 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006598 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006599 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006600 else {
6601 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006602 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006603 else
Rex Xu51596642016-09-21 18:56:12 +08006604 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006605 }
Rex Xu430ef402016-10-14 17:22:23 +08006606 } else if (op == glslang::EOpMaxInvocations ||
6607 op == glslang::EOpMaxInvocationsInclusiveScan ||
6608 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006609 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006610 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006611 else {
6612 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006613 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006614 else
Rex Xu51596642016-09-21 18:56:12 +08006615 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006616 }
6617 } else {
6618 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006619 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006620 else
Rex Xu51596642016-09-21 18:56:12 +08006621 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006622 }
6623
Rex Xu2bbbe062016-08-23 15:41:05 +08006624 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006625 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006626
6627 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006628 case glslang::EOpMinInvocationsNonUniform:
6629 case glslang::EOpMaxInvocationsNonUniform:
6630 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006631 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6632 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6633 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6634 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6635 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6636 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6637 if (op == glslang::EOpMinInvocationsNonUniform ||
6638 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6639 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006640 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006641 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006642 else {
6643 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006644 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006645 else
Rex Xu51596642016-09-21 18:56:12 +08006646 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006647 }
6648 }
Rex Xu430ef402016-10-14 17:22:23 +08006649 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6650 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6651 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006652 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006653 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006654 else {
6655 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006656 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006657 else
Rex Xu51596642016-09-21 18:56:12 +08006658 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006659 }
6660 }
6661 else {
6662 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006663 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006664 else
Rex Xu51596642016-09-21 18:56:12 +08006665 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006666 }
6667
Rex Xu2bbbe062016-08-23 15:41:05 +08006668 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006669 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006670
6671 break;
John Kessenich91cef522016-05-05 16:45:40 -06006672 default:
6673 logger->missingFunctionality("invocation operation");
6674 return spv::NoResult;
6675 }
Rex Xu51596642016-09-21 18:56:12 +08006676
6677 assert(opCode != spv::OpNop);
6678 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006679}
6680
Rex Xu2bbbe062016-08-23 15:41:05 +08006681// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006682spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6683 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006684{
6685 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6686 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006687 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006688 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006689 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6690 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6691 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6692
6693 // Handle group invocation operations scalar by scalar.
6694 // The result type is the same type as the original type.
6695 // The algorithm is to:
6696 // - break the vector into scalars
6697 // - apply the operation to each scalar
6698 // - make a vector out the scalar results
6699
6700 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006701 int numComponents = builder.getNumComponents(operands[0]);
6702 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006703 std::vector<spv::Id> results;
6704
6705 // do each scalar op
6706 for (int comp = 0; comp < numComponents; ++comp) {
6707 std::vector<unsigned int> indexes;
6708 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006709 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6710 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006711 if (op == spv::OpSubgroupReadInvocationKHR) {
6712 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006713 spv::IdImmediate operand = { true, operands[1] };
6714 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006715 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006716 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6717 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006718 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006719 spv::IdImmediate operand = { true, operands[1] };
6720 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006721 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006722 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6723 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006724 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006725 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006726 spvGroupOperands.push_back(scalar);
6727 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006728
Rex Xub7072052016-09-26 15:53:40 +08006729 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006730 }
6731
6732 // put the pieces together
6733 return builder.createCompositeConstruct(typeId, results);
6734}
Rex Xu2bbbe062016-08-23 15:41:05 +08006735
John Kessenich66011cb2018-03-06 16:12:04 -07006736// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006737spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6738 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006739{
6740 // Add the required capabilities.
6741 switch (op) {
6742 case glslang::EOpSubgroupElect:
6743 builder.addCapability(spv::CapabilityGroupNonUniform);
6744 break;
6745 case glslang::EOpSubgroupAll:
6746 case glslang::EOpSubgroupAny:
6747 case glslang::EOpSubgroupAllEqual:
6748 builder.addCapability(spv::CapabilityGroupNonUniform);
6749 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6750 break;
6751 case glslang::EOpSubgroupBroadcast:
6752 case glslang::EOpSubgroupBroadcastFirst:
6753 case glslang::EOpSubgroupBallot:
6754 case glslang::EOpSubgroupInverseBallot:
6755 case glslang::EOpSubgroupBallotBitExtract:
6756 case glslang::EOpSubgroupBallotBitCount:
6757 case glslang::EOpSubgroupBallotInclusiveBitCount:
6758 case glslang::EOpSubgroupBallotExclusiveBitCount:
6759 case glslang::EOpSubgroupBallotFindLSB:
6760 case glslang::EOpSubgroupBallotFindMSB:
6761 builder.addCapability(spv::CapabilityGroupNonUniform);
6762 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6763 break;
6764 case glslang::EOpSubgroupShuffle:
6765 case glslang::EOpSubgroupShuffleXor:
6766 builder.addCapability(spv::CapabilityGroupNonUniform);
6767 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6768 break;
6769 case glslang::EOpSubgroupShuffleUp:
6770 case glslang::EOpSubgroupShuffleDown:
6771 builder.addCapability(spv::CapabilityGroupNonUniform);
6772 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6773 break;
6774 case glslang::EOpSubgroupAdd:
6775 case glslang::EOpSubgroupMul:
6776 case glslang::EOpSubgroupMin:
6777 case glslang::EOpSubgroupMax:
6778 case glslang::EOpSubgroupAnd:
6779 case glslang::EOpSubgroupOr:
6780 case glslang::EOpSubgroupXor:
6781 case glslang::EOpSubgroupInclusiveAdd:
6782 case glslang::EOpSubgroupInclusiveMul:
6783 case glslang::EOpSubgroupInclusiveMin:
6784 case glslang::EOpSubgroupInclusiveMax:
6785 case glslang::EOpSubgroupInclusiveAnd:
6786 case glslang::EOpSubgroupInclusiveOr:
6787 case glslang::EOpSubgroupInclusiveXor:
6788 case glslang::EOpSubgroupExclusiveAdd:
6789 case glslang::EOpSubgroupExclusiveMul:
6790 case glslang::EOpSubgroupExclusiveMin:
6791 case glslang::EOpSubgroupExclusiveMax:
6792 case glslang::EOpSubgroupExclusiveAnd:
6793 case glslang::EOpSubgroupExclusiveOr:
6794 case glslang::EOpSubgroupExclusiveXor:
6795 builder.addCapability(spv::CapabilityGroupNonUniform);
6796 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6797 break;
6798 case glslang::EOpSubgroupClusteredAdd:
6799 case glslang::EOpSubgroupClusteredMul:
6800 case glslang::EOpSubgroupClusteredMin:
6801 case glslang::EOpSubgroupClusteredMax:
6802 case glslang::EOpSubgroupClusteredAnd:
6803 case glslang::EOpSubgroupClusteredOr:
6804 case glslang::EOpSubgroupClusteredXor:
6805 builder.addCapability(spv::CapabilityGroupNonUniform);
6806 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6807 break;
6808 case glslang::EOpSubgroupQuadBroadcast:
6809 case glslang::EOpSubgroupQuadSwapHorizontal:
6810 case glslang::EOpSubgroupQuadSwapVertical:
6811 case glslang::EOpSubgroupQuadSwapDiagonal:
6812 builder.addCapability(spv::CapabilityGroupNonUniform);
6813 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6814 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006815 case glslang::EOpSubgroupPartitionedAdd:
6816 case glslang::EOpSubgroupPartitionedMul:
6817 case glslang::EOpSubgroupPartitionedMin:
6818 case glslang::EOpSubgroupPartitionedMax:
6819 case glslang::EOpSubgroupPartitionedAnd:
6820 case glslang::EOpSubgroupPartitionedOr:
6821 case glslang::EOpSubgroupPartitionedXor:
6822 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6823 case glslang::EOpSubgroupPartitionedInclusiveMul:
6824 case glslang::EOpSubgroupPartitionedInclusiveMin:
6825 case glslang::EOpSubgroupPartitionedInclusiveMax:
6826 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6827 case glslang::EOpSubgroupPartitionedInclusiveOr:
6828 case glslang::EOpSubgroupPartitionedInclusiveXor:
6829 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6830 case glslang::EOpSubgroupPartitionedExclusiveMul:
6831 case glslang::EOpSubgroupPartitionedExclusiveMin:
6832 case glslang::EOpSubgroupPartitionedExclusiveMax:
6833 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6834 case glslang::EOpSubgroupPartitionedExclusiveOr:
6835 case glslang::EOpSubgroupPartitionedExclusiveXor:
6836 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6837 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6838 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006839 default: assert(0 && "Unhandled subgroup operation!");
6840 }
6841
6842 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6843 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6844 const bool isBool = typeProxy == glslang::EbtBool;
6845
6846 spv::Op opCode = spv::OpNop;
6847
6848 // Figure out which opcode to use.
6849 switch (op) {
6850 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6851 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6852 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6853 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6854 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6855 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6856 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6857 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6858 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6859 case glslang::EOpSubgroupBallotBitCount:
6860 case glslang::EOpSubgroupBallotInclusiveBitCount:
6861 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6862 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6863 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6864 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6865 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6866 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6867 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6868 case glslang::EOpSubgroupAdd:
6869 case glslang::EOpSubgroupInclusiveAdd:
6870 case glslang::EOpSubgroupExclusiveAdd:
6871 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006872 case glslang::EOpSubgroupPartitionedAdd:
6873 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6874 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006875 if (isFloat) {
6876 opCode = spv::OpGroupNonUniformFAdd;
6877 } else {
6878 opCode = spv::OpGroupNonUniformIAdd;
6879 }
6880 break;
6881 case glslang::EOpSubgroupMul:
6882 case glslang::EOpSubgroupInclusiveMul:
6883 case glslang::EOpSubgroupExclusiveMul:
6884 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006885 case glslang::EOpSubgroupPartitionedMul:
6886 case glslang::EOpSubgroupPartitionedInclusiveMul:
6887 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006888 if (isFloat) {
6889 opCode = spv::OpGroupNonUniformFMul;
6890 } else {
6891 opCode = spv::OpGroupNonUniformIMul;
6892 }
6893 break;
6894 case glslang::EOpSubgroupMin:
6895 case glslang::EOpSubgroupInclusiveMin:
6896 case glslang::EOpSubgroupExclusiveMin:
6897 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006898 case glslang::EOpSubgroupPartitionedMin:
6899 case glslang::EOpSubgroupPartitionedInclusiveMin:
6900 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006901 if (isFloat) {
6902 opCode = spv::OpGroupNonUniformFMin;
6903 } else if (isUnsigned) {
6904 opCode = spv::OpGroupNonUniformUMin;
6905 } else {
6906 opCode = spv::OpGroupNonUniformSMin;
6907 }
6908 break;
6909 case glslang::EOpSubgroupMax:
6910 case glslang::EOpSubgroupInclusiveMax:
6911 case glslang::EOpSubgroupExclusiveMax:
6912 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006913 case glslang::EOpSubgroupPartitionedMax:
6914 case glslang::EOpSubgroupPartitionedInclusiveMax:
6915 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006916 if (isFloat) {
6917 opCode = spv::OpGroupNonUniformFMax;
6918 } else if (isUnsigned) {
6919 opCode = spv::OpGroupNonUniformUMax;
6920 } else {
6921 opCode = spv::OpGroupNonUniformSMax;
6922 }
6923 break;
6924 case glslang::EOpSubgroupAnd:
6925 case glslang::EOpSubgroupInclusiveAnd:
6926 case glslang::EOpSubgroupExclusiveAnd:
6927 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006928 case glslang::EOpSubgroupPartitionedAnd:
6929 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6930 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006931 if (isBool) {
6932 opCode = spv::OpGroupNonUniformLogicalAnd;
6933 } else {
6934 opCode = spv::OpGroupNonUniformBitwiseAnd;
6935 }
6936 break;
6937 case glslang::EOpSubgroupOr:
6938 case glslang::EOpSubgroupInclusiveOr:
6939 case glslang::EOpSubgroupExclusiveOr:
6940 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006941 case glslang::EOpSubgroupPartitionedOr:
6942 case glslang::EOpSubgroupPartitionedInclusiveOr:
6943 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006944 if (isBool) {
6945 opCode = spv::OpGroupNonUniformLogicalOr;
6946 } else {
6947 opCode = spv::OpGroupNonUniformBitwiseOr;
6948 }
6949 break;
6950 case glslang::EOpSubgroupXor:
6951 case glslang::EOpSubgroupInclusiveXor:
6952 case glslang::EOpSubgroupExclusiveXor:
6953 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006954 case glslang::EOpSubgroupPartitionedXor:
6955 case glslang::EOpSubgroupPartitionedInclusiveXor:
6956 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006957 if (isBool) {
6958 opCode = spv::OpGroupNonUniformLogicalXor;
6959 } else {
6960 opCode = spv::OpGroupNonUniformBitwiseXor;
6961 }
6962 break;
6963 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6964 case glslang::EOpSubgroupQuadSwapHorizontal:
6965 case glslang::EOpSubgroupQuadSwapVertical:
6966 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6967 default: assert(0 && "Unhandled subgroup operation!");
6968 }
6969
John Kessenich149afc32018-08-14 13:31:43 -06006970 // get the right Group Operation
6971 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006972 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006973 default:
6974 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006975 case glslang::EOpSubgroupBallotBitCount:
6976 case glslang::EOpSubgroupAdd:
6977 case glslang::EOpSubgroupMul:
6978 case glslang::EOpSubgroupMin:
6979 case glslang::EOpSubgroupMax:
6980 case glslang::EOpSubgroupAnd:
6981 case glslang::EOpSubgroupOr:
6982 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006983 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006984 break;
6985 case glslang::EOpSubgroupBallotInclusiveBitCount:
6986 case glslang::EOpSubgroupInclusiveAdd:
6987 case glslang::EOpSubgroupInclusiveMul:
6988 case glslang::EOpSubgroupInclusiveMin:
6989 case glslang::EOpSubgroupInclusiveMax:
6990 case glslang::EOpSubgroupInclusiveAnd:
6991 case glslang::EOpSubgroupInclusiveOr:
6992 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006993 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006994 break;
6995 case glslang::EOpSubgroupBallotExclusiveBitCount:
6996 case glslang::EOpSubgroupExclusiveAdd:
6997 case glslang::EOpSubgroupExclusiveMul:
6998 case glslang::EOpSubgroupExclusiveMin:
6999 case glslang::EOpSubgroupExclusiveMax:
7000 case glslang::EOpSubgroupExclusiveAnd:
7001 case glslang::EOpSubgroupExclusiveOr:
7002 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007003 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007004 break;
7005 case glslang::EOpSubgroupClusteredAdd:
7006 case glslang::EOpSubgroupClusteredMul:
7007 case glslang::EOpSubgroupClusteredMin:
7008 case glslang::EOpSubgroupClusteredMax:
7009 case glslang::EOpSubgroupClusteredAnd:
7010 case glslang::EOpSubgroupClusteredOr:
7011 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007012 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007013 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007014 case glslang::EOpSubgroupPartitionedAdd:
7015 case glslang::EOpSubgroupPartitionedMul:
7016 case glslang::EOpSubgroupPartitionedMin:
7017 case glslang::EOpSubgroupPartitionedMax:
7018 case glslang::EOpSubgroupPartitionedAnd:
7019 case glslang::EOpSubgroupPartitionedOr:
7020 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007021 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007022 break;
7023 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7024 case glslang::EOpSubgroupPartitionedInclusiveMul:
7025 case glslang::EOpSubgroupPartitionedInclusiveMin:
7026 case glslang::EOpSubgroupPartitionedInclusiveMax:
7027 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7028 case glslang::EOpSubgroupPartitionedInclusiveOr:
7029 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007030 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007031 break;
7032 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7033 case glslang::EOpSubgroupPartitionedExclusiveMul:
7034 case glslang::EOpSubgroupPartitionedExclusiveMin:
7035 case glslang::EOpSubgroupPartitionedExclusiveMax:
7036 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7037 case glslang::EOpSubgroupPartitionedExclusiveOr:
7038 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007039 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007040 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007041 }
7042
John Kessenich149afc32018-08-14 13:31:43 -06007043 // build the instruction
7044 std::vector<spv::IdImmediate> spvGroupOperands;
7045
7046 // Every operation begins with the Execution Scope operand.
7047 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7048 spvGroupOperands.push_back(executionScope);
7049
7050 // Next, for all operations that use a Group Operation, push that as an operand.
7051 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007052 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007053 spvGroupOperands.push_back(groupOperand);
7054 }
7055
John Kessenich66011cb2018-03-06 16:12:04 -07007056 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007057 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7058 spv::IdImmediate operand = { true, *opIt };
7059 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007060 }
7061
7062 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007063 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007064 switch (op) {
7065 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007066 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7067 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7068 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7069 }
7070 if (directionId != spv::NoResult) {
7071 spv::IdImmediate direction = { true, directionId };
7072 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007073 }
7074
7075 return builder.createOp(opCode, typeId, spvGroupOperands);
7076}
7077
John Kessenich5e4b1242015-08-06 22:53:06 -06007078spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007079{
John Kessenich66011cb2018-03-06 16:12:04 -07007080 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7081 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007082
John Kessenich140f3df2015-06-26 16:58:36 -06007083 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007084 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007085 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007086 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007087 spv::Id typeId0 = 0;
7088 if (consumedOperands > 0)
7089 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007090 spv::Id typeId1 = 0;
7091 if (consumedOperands > 1)
7092 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007093 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007094
7095 switch (op) {
7096 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007097 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007098 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007099 else if (isUnsigned)
7100 libCall = spv::GLSLstd450UMin;
7101 else
7102 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007103 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007104 break;
7105 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007106 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007107 break;
7108 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007109 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007110 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007111 else if (isUnsigned)
7112 libCall = spv::GLSLstd450UMax;
7113 else
7114 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007115 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007116 break;
7117 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007118 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007119 break;
7120 case glslang::EOpDot:
7121 opCode = spv::OpDot;
7122 break;
7123 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007124 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007125 break;
7126
7127 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007128 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007129 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007130 else if (isUnsigned)
7131 libCall = spv::GLSLstd450UClamp;
7132 else
7133 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007134 builder.promoteScalar(precision, operands.front(), operands[1]);
7135 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007136 break;
7137 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007138 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7139 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007140 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007141 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007142 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007143 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007144 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007145 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007146 break;
7147 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007148 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007149 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007150 break;
7151 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007152 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007153 builder.promoteScalar(precision, operands[0], operands[2]);
7154 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007155 break;
7156
7157 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007158 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007159 break;
7160 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007161 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007162 break;
7163 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007164 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007165 break;
7166 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007167 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007168 break;
7169 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007170 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007171 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007172#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007173 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007174 if (typeProxy == glslang::EbtFloat16)
7175 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007176 libCall = spv::GLSLstd450InterpolateAtSample;
7177 break;
7178 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007179 if (typeProxy == glslang::EbtFloat16)
7180 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007181 libCall = spv::GLSLstd450InterpolateAtOffset;
7182 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007183 case glslang::EOpAddCarry:
7184 opCode = spv::OpIAddCarry;
7185 typeId = builder.makeStructResultType(typeId0, typeId0);
7186 consumedOperands = 2;
7187 break;
7188 case glslang::EOpSubBorrow:
7189 opCode = spv::OpISubBorrow;
7190 typeId = builder.makeStructResultType(typeId0, typeId0);
7191 consumedOperands = 2;
7192 break;
7193 case glslang::EOpUMulExtended:
7194 opCode = spv::OpUMulExtended;
7195 typeId = builder.makeStructResultType(typeId0, typeId0);
7196 consumedOperands = 2;
7197 break;
7198 case glslang::EOpIMulExtended:
7199 opCode = spv::OpSMulExtended;
7200 typeId = builder.makeStructResultType(typeId0, typeId0);
7201 consumedOperands = 2;
7202 break;
7203 case glslang::EOpBitfieldExtract:
7204 if (isUnsigned)
7205 opCode = spv::OpBitFieldUExtract;
7206 else
7207 opCode = spv::OpBitFieldSExtract;
7208 break;
7209 case glslang::EOpBitfieldInsert:
7210 opCode = spv::OpBitFieldInsert;
7211 break;
7212
7213 case glslang::EOpFma:
7214 libCall = spv::GLSLstd450Fma;
7215 break;
7216 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007217 {
7218 libCall = spv::GLSLstd450FrexpStruct;
7219 assert(builder.isPointerType(typeId1));
7220 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007221 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007222 if (width == 16)
7223 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7224 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007225 if (builder.getNumComponents(operands[0]) == 1)
7226 frexpIntType = builder.makeIntegerType(width, true);
7227 else
7228 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7229 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7230 consumedOperands = 1;
7231 }
John Kessenich55e7d112015-11-15 21:33:39 -07007232 break;
7233 case glslang::EOpLdexp:
7234 libCall = spv::GLSLstd450Ldexp;
7235 break;
7236
Rex Xu574ab042016-04-14 16:53:07 +08007237 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007238 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007239
John Kessenich66011cb2018-03-06 16:12:04 -07007240 case glslang::EOpSubgroupBroadcast:
7241 case glslang::EOpSubgroupBallotBitExtract:
7242 case glslang::EOpSubgroupShuffle:
7243 case glslang::EOpSubgroupShuffleXor:
7244 case glslang::EOpSubgroupShuffleUp:
7245 case glslang::EOpSubgroupShuffleDown:
7246 case glslang::EOpSubgroupClusteredAdd:
7247 case glslang::EOpSubgroupClusteredMul:
7248 case glslang::EOpSubgroupClusteredMin:
7249 case glslang::EOpSubgroupClusteredMax:
7250 case glslang::EOpSubgroupClusteredAnd:
7251 case glslang::EOpSubgroupClusteredOr:
7252 case glslang::EOpSubgroupClusteredXor:
7253 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007254 case glslang::EOpSubgroupPartitionedAdd:
7255 case glslang::EOpSubgroupPartitionedMul:
7256 case glslang::EOpSubgroupPartitionedMin:
7257 case glslang::EOpSubgroupPartitionedMax:
7258 case glslang::EOpSubgroupPartitionedAnd:
7259 case glslang::EOpSubgroupPartitionedOr:
7260 case glslang::EOpSubgroupPartitionedXor:
7261 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7262 case glslang::EOpSubgroupPartitionedInclusiveMul:
7263 case glslang::EOpSubgroupPartitionedInclusiveMin:
7264 case glslang::EOpSubgroupPartitionedInclusiveMax:
7265 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7266 case glslang::EOpSubgroupPartitionedInclusiveOr:
7267 case glslang::EOpSubgroupPartitionedInclusiveXor:
7268 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7269 case glslang::EOpSubgroupPartitionedExclusiveMul:
7270 case glslang::EOpSubgroupPartitionedExclusiveMin:
7271 case glslang::EOpSubgroupPartitionedExclusiveMax:
7272 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7273 case glslang::EOpSubgroupPartitionedExclusiveOr:
7274 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007275 return createSubgroupOperation(op, typeId, operands, typeProxy);
7276
Rex Xu9d93a232016-05-05 12:30:44 +08007277 case glslang::EOpSwizzleInvocations:
7278 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7279 libCall = spv::SwizzleInvocationsAMD;
7280 break;
7281 case glslang::EOpSwizzleInvocationsMasked:
7282 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7283 libCall = spv::SwizzleInvocationsMaskedAMD;
7284 break;
7285 case glslang::EOpWriteInvocation:
7286 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7287 libCall = spv::WriteInvocationAMD;
7288 break;
7289
7290 case glslang::EOpMin3:
7291 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7292 if (isFloat)
7293 libCall = spv::FMin3AMD;
7294 else {
7295 if (isUnsigned)
7296 libCall = spv::UMin3AMD;
7297 else
7298 libCall = spv::SMin3AMD;
7299 }
7300 break;
7301 case glslang::EOpMax3:
7302 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7303 if (isFloat)
7304 libCall = spv::FMax3AMD;
7305 else {
7306 if (isUnsigned)
7307 libCall = spv::UMax3AMD;
7308 else
7309 libCall = spv::SMax3AMD;
7310 }
7311 break;
7312 case glslang::EOpMid3:
7313 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7314 if (isFloat)
7315 libCall = spv::FMid3AMD;
7316 else {
7317 if (isUnsigned)
7318 libCall = spv::UMid3AMD;
7319 else
7320 libCall = spv::SMid3AMD;
7321 }
7322 break;
7323
7324 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007325 if (typeProxy == glslang::EbtFloat16)
7326 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007327 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7328 libCall = spv::InterpolateAtVertexAMD;
7329 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007330 case glslang::EOpBarrier:
7331 {
7332 // This is for the extended controlBarrier function, with four operands.
7333 // The unextended barrier() goes through createNoArgOperation.
7334 assert(operands.size() == 4);
7335 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7336 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7337 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7338 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007339 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7340 spv::MemorySemanticsMakeVisibleKHRMask |
7341 spv::MemorySemanticsOutputMemoryKHRMask |
7342 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007343 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7344 }
7345 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7346 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7347 }
7348 return 0;
7349 }
7350 break;
7351 case glslang::EOpMemoryBarrier:
7352 {
7353 // This is for the extended memoryBarrier function, with three operands.
7354 // The unextended memoryBarrier() goes through createNoArgOperation.
7355 assert(operands.size() == 3);
7356 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7357 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7358 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007359 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7360 spv::MemorySemanticsMakeVisibleKHRMask |
7361 spv::MemorySemanticsOutputMemoryKHRMask |
7362 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007363 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7364 }
7365 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7366 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7367 }
7368 return 0;
7369 }
7370 break;
Chao Chen3c366992018-09-19 11:41:59 -07007371
Chao Chenb50c02e2018-09-19 11:42:24 -07007372 case glslang::EOpReportIntersectionNV:
7373 {
7374 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007375 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007376 }
7377 break;
7378 case glslang::EOpTraceNV:
7379 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007380 builder.createNoResultOp(spv::OpTraceNV, operands);
7381 return 0;
7382 }
7383 break;
7384 case glslang::EOpExecuteCallableNV:
7385 {
7386 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007387 return 0;
7388 }
7389 break;
Chao Chen3c366992018-09-19 11:41:59 -07007390 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7391 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7392 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007393 case glslang::EOpCooperativeMatrixMulAdd:
7394 opCode = spv::OpCooperativeMatrixMulAddNV;
7395 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007396#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007397 default:
7398 return 0;
7399 }
7400
7401 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007402 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007403 // Use an extended instruction from the standard library.
7404 // Construct the call arguments, without modifying the original operands vector.
7405 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7406 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007407 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007408 } else if (opCode == spv::OpDot && !isFloat) {
7409 // int dot(int, int)
7410 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7411 const int componentCount = builder.getNumComponents(operands[0]);
7412 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7413 builder.setPrecision(mulOp, precision);
7414 id = builder.createCompositeExtract(mulOp, typeId, 0);
7415 for (int i = 1; i < componentCount; ++i) {
7416 builder.setPrecision(id, precision);
7417 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7418 }
John Kessenich2359bd02015-12-06 19:29:11 -07007419 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007420 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007421 case 0:
7422 // should all be handled by visitAggregate and createNoArgOperation
7423 assert(0);
7424 return 0;
7425 case 1:
7426 // should all be handled by createUnaryOperation
7427 assert(0);
7428 return 0;
7429 case 2:
7430 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7431 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007432 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007433 // anything 3 or over doesn't have l-value operands, so all should be consumed
7434 assert(consumedOperands == operands.size());
7435 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007436 break;
7437 }
7438 }
7439
John Kessenichb9197c82019-08-11 07:41:45 -06007440#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007441 // Decode the return types that were structures
7442 switch (op) {
7443 case glslang::EOpAddCarry:
7444 case glslang::EOpSubBorrow:
7445 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7446 id = builder.createCompositeExtract(id, typeId0, 0);
7447 break;
7448 case glslang::EOpUMulExtended:
7449 case glslang::EOpIMulExtended:
7450 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7451 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7452 break;
7453 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007454 {
7455 assert(operands.size() == 2);
7456 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7457 // "exp" is floating-point type (from HLSL intrinsic)
7458 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7459 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7460 builder.createStore(member1, operands[1]);
7461 } else
7462 // "exp" is integer type (from GLSL built-in function)
7463 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7464 id = builder.createCompositeExtract(id, typeId0, 0);
7465 }
John Kessenich55e7d112015-11-15 21:33:39 -07007466 break;
7467 default:
7468 break;
7469 }
John Kessenichb9197c82019-08-11 07:41:45 -06007470#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007471
John Kessenich32cfd492016-02-02 12:37:46 -07007472 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007473}
7474
Rex Xu9d93a232016-05-05 12:30:44 +08007475// Intrinsics with no arguments (or no return value, and no precision).
7476spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007477{
John Kessenich155d3512019-08-08 23:29:20 -06007478#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05007479 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7480 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007481
7482 switch (op) {
7483 case glslang::EOpEmitVertex:
7484 builder.createNoResultOp(spv::OpEmitVertex);
7485 return 0;
7486 case glslang::EOpEndPrimitive:
7487 builder.createNoResultOp(spv::OpEndPrimitive);
7488 return 0;
7489 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007490 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007491 if (glslangIntermediate->usingVulkanMemoryModel()) {
7492 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7493 spv::MemorySemanticsOutputMemoryKHRMask |
7494 spv::MemorySemanticsAcquireReleaseMask);
7495 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7496 } else {
7497 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7498 }
John Kessenich82979362017-12-11 04:02:24 -07007499 } else {
7500 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7501 spv::MemorySemanticsWorkgroupMemoryMask |
7502 spv::MemorySemanticsAcquireReleaseMask);
7503 }
John Kessenich140f3df2015-06-26 16:58:36 -06007504 return 0;
7505 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007506 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7507 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007508 return 0;
7509 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007510 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7511 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007512 return 0;
7513 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007514 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7515 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007516 return 0;
7517 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007518 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7519 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007520 return 0;
7521 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007522 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7523 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007524 return 0;
7525 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007526 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7527 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007528 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007529 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007530 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007531 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007532 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007533 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007534 case glslang::EOpDeviceMemoryBarrier:
7535 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7536 spv::MemorySemanticsImageMemoryMask |
7537 spv::MemorySemanticsAcquireReleaseMask);
7538 return 0;
7539 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7540 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7541 spv::MemorySemanticsImageMemoryMask |
7542 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007543 return 0;
7544 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007545 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7546 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007547 return 0;
7548 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007549 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7550 spv::MemorySemanticsWorkgroupMemoryMask |
7551 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007552 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007553 case glslang::EOpSubgroupBarrier:
7554 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7555 spv::MemorySemanticsAcquireReleaseMask);
7556 return spv::NoResult;
7557 case glslang::EOpSubgroupMemoryBarrier:
7558 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7559 spv::MemorySemanticsAcquireReleaseMask);
7560 return spv::NoResult;
7561 case glslang::EOpSubgroupMemoryBarrierBuffer:
7562 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7563 spv::MemorySemanticsAcquireReleaseMask);
7564 return spv::NoResult;
7565 case glslang::EOpSubgroupMemoryBarrierImage:
7566 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7567 spv::MemorySemanticsAcquireReleaseMask);
7568 return spv::NoResult;
7569 case glslang::EOpSubgroupMemoryBarrierShared:
7570 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7571 spv::MemorySemanticsAcquireReleaseMask);
7572 return spv::NoResult;
7573 case glslang::EOpSubgroupElect: {
7574 std::vector<spv::Id> operands;
7575 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7576 }
Rex Xu9d93a232016-05-05 12:30:44 +08007577 case glslang::EOpTime:
7578 {
7579 std::vector<spv::Id> args; // Dummy arguments
7580 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7581 return builder.setPrecision(id, precision);
7582 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007583 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007584 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007585 return 0;
7586 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007587 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007588 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007589
7590 case glslang::EOpBeginInvocationInterlock:
7591 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7592 return 0;
7593 case glslang::EOpEndInvocationInterlock:
7594 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7595 return 0;
7596
Jeff Bolzba6170b2019-07-01 09:23:23 -05007597 case glslang::EOpIsHelperInvocation:
7598 {
7599 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007600 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7601 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7602 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007603 }
7604
amhagan91fb0092019-07-10 21:14:38 -04007605 case glslang::EOpReadClockSubgroupKHR: {
7606 std::vector<spv::Id> args;
7607 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7608 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7609 builder.addCapability(spv::CapabilityShaderClockKHR);
7610 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7611 }
7612
7613 case glslang::EOpReadClockDeviceKHR: {
7614 std::vector<spv::Id> args;
7615 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7616 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7617 builder.addCapability(spv::CapabilityShaderClockKHR);
7618 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7619 }
John Kessenich140f3df2015-06-26 16:58:36 -06007620 default:
John Kessenich155d3512019-08-08 23:29:20 -06007621 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007622 }
John Kessenich155d3512019-08-08 23:29:20 -06007623#endif
7624
7625 logger->missingFunctionality("unknown operation with no arguments");
7626
7627 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007628}
7629
7630spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7631{
John Kessenich2f273362015-07-18 22:34:27 -06007632 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007633 spv::Id id;
7634 if (symbolValues.end() != iter) {
7635 id = iter->second;
7636 return id;
7637 }
7638
7639 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007640 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7641 auto forcedType = getForcedType(builtIn, symbol->getType());
7642 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007643 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007644 if (forcedType.second != spv::NoType)
7645 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007646
Rex Xuc884b4a2016-06-29 15:03:44 +08007647 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007648 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7649 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7650 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007651#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007652 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007653 if (symbol->getQualifier().hasComponent())
7654 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7655 if (symbol->getQualifier().hasIndex())
7656 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007657#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007658 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007659 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007660 // atomic counters use this:
7661 if (symbol->getQualifier().hasOffset())
7662 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007663 }
7664
scygan2c864272016-05-18 18:09:17 +02007665 if (symbol->getQualifier().hasLocation())
7666 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007667 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007668 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007669 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007670 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007671 }
John Kessenich140f3df2015-06-26 16:58:36 -06007672 if (symbol->getQualifier().hasSet())
7673 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007674 else if (IsDescriptorResource(symbol->getType())) {
7675 // default to 0
7676 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7677 }
John Kessenich140f3df2015-06-26 16:58:36 -06007678 if (symbol->getQualifier().hasBinding())
7679 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007680 else if (IsDescriptorResource(symbol->getType())) {
7681 // default to 0
7682 builder.addDecoration(id, spv::DecorationBinding, 0);
7683 }
John Kessenich6c292d32016-02-15 20:58:50 -07007684 if (symbol->getQualifier().hasAttachment())
7685 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007686 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007687 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007688 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007689 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007690 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7691 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7692 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7693 }
7694 if (symbol->getQualifier().hasXfbOffset())
7695 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007696 }
7697
John Kessenichb9197c82019-08-11 07:41:45 -06007698 // add built-in variable decoration
7699 if (builtIn != spv::BuiltInMax) {
7700 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7701 }
7702
7703#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007704 if (symbol->getType().isImage()) {
7705 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007706 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007707 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007708 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007709 }
7710
John Kessenich5611c6d2018-04-05 11:25:02 -06007711 // nonuniform
7712 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7713
chaoc0ad6a4e2016-12-19 16:29:34 -08007714 if (builtIn == spv::BuiltInSampleMask) {
7715 spv::Decoration decoration;
7716 // GL_NV_sample_mask_override_coverage extension
7717 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007718 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007719 else
7720 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007721 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007722 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007723 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007724 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7725 }
7726 }
chaoc771d89f2017-01-13 01:10:53 -08007727 else if (builtIn == spv::BuiltInLayer) {
7728 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007729 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007730 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007731 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7732 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7733 }
John Kessenichb41bff62017-08-11 13:07:17 -06007734 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007735 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7736 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007737 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7738 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7739 }
7740 }
7741
chaoc6e5acae2016-12-20 13:28:52 -08007742 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007743 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007744 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007745 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7746 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007747 if (symbol->getQualifier().pervertexNV) {
7748 builder.addDecoration(id, spv::DecorationPerVertexNV);
7749 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7750 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7751 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007752
John Kessenich5d610ee2018-03-07 18:05:55 -07007753 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7754 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7755 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7756 symbol->getType().getQualifier().semanticName);
7757 }
7758
John Kessenich7015bd62019-08-01 03:28:08 -06007759 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007760 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7761 }
John Kessenichb9197c82019-08-11 07:41:45 -06007762#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007763
John Kessenich140f3df2015-06-26 16:58:36 -06007764 return id;
7765}
7766
John Kessenicha28f7a72019-08-06 07:00:58 -06007767#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007768// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7769void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7770{
7771 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007772 if (qualifier.perPrimitiveNV) {
7773 // Need to add capability/extension for fragment shader.
7774 // Mesh shader already adds this by default.
7775 if (glslangIntermediate->getStage() == EShLangFragment) {
7776 builder.addCapability(spv::CapabilityMeshShadingNV);
7777 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7778 }
Chao Chen3c366992018-09-19 11:41:59 -07007779 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007780 }
Chao Chen3c366992018-09-19 11:41:59 -07007781 if (qualifier.perViewNV)
7782 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7783 if (qualifier.perTaskNV)
7784 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7785 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007786 if (qualifier.perPrimitiveNV) {
7787 // Need to add capability/extension for fragment shader.
7788 // Mesh shader already adds this by default.
7789 if (glslangIntermediate->getStage() == EShLangFragment) {
7790 builder.addCapability(spv::CapabilityMeshShadingNV);
7791 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7792 }
Chao Chen3c366992018-09-19 11:41:59 -07007793 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007794 }
Chao Chen3c366992018-09-19 11:41:59 -07007795 if (qualifier.perViewNV)
7796 builder.addDecoration(id, spv::DecorationPerViewNV);
7797 if (qualifier.perTaskNV)
7798 builder.addDecoration(id, spv::DecorationPerTaskNV);
7799 }
7800}
7801#endif
7802
John Kessenich55e7d112015-11-15 21:33:39 -07007803// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007804// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007805//
7806// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7807//
7808// Recursively walk the nodes. The nodes form a tree whose leaves are
7809// regular constants, which themselves are trees that createSpvConstant()
7810// recursively walks. So, this function walks the "top" of the tree:
7811// - emit specialization constant-building instructions for specConstant
7812// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007813spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007814{
John Kessenich7cc0e282016-03-20 00:46:02 -06007815 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007816
qining4f4bb812016-04-03 23:55:17 -04007817 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007818 if (! node.getQualifier().specConstant) {
7819 // hand off to the non-spec-constant path
7820 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7821 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007822 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007823 nextConst, false);
7824 }
7825
7826 // We now know we have a specialization constant to build
7827
John Kessenich155d3512019-08-08 23:29:20 -06007828#ifndef GLSLANG_WEB
John Kessenichd94c0032016-05-30 19:29:40 -06007829 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007830 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7831 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7832 std::vector<spv::Id> dimConstId;
7833 for (int dim = 0; dim < 3; ++dim) {
7834 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7835 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007836 if (specConst) {
7837 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7838 glslangIntermediate->getLocalSizeSpecId(dim));
7839 }
qining4f4bb812016-04-03 23:55:17 -04007840 }
7841 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7842 }
John Kessenich155d3512019-08-08 23:29:20 -06007843#endif
qining4f4bb812016-04-03 23:55:17 -04007844
7845 // An AST node labelled as specialization constant should be a symbol node.
7846 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7847 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007848 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007849 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007850 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7851 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7852 // will set the builder into spec constant op instruction generating mode.
7853 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007854 result = accessChainLoad(sub_tree->getType());
7855 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007856 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007857 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007858 } else {
7859 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007860 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007861 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007862 builder.addName(result, sn->getName().c_str());
7863 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007864 }
qining4f4bb812016-04-03 23:55:17 -04007865
7866 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7867 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007868 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007869 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007870}
7871
John Kessenich140f3df2015-06-26 16:58:36 -06007872// Use 'consts' as the flattened glslang source of scalar constants to recursively
7873// build the aggregate SPIR-V constant.
7874//
7875// If there are not enough elements present in 'consts', 0 will be substituted;
7876// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7877//
qining08408382016-03-21 09:51:37 -04007878spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007879{
7880 // vector of constants for SPIR-V
7881 std::vector<spv::Id> spvConsts;
7882
7883 // Type is used for struct and array constants
7884 spv::Id typeId = convertGlslangToSpvType(glslangType);
7885
7886 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007887 glslang::TType elementType(glslangType, 0);
7888 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007889 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007890 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007891 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007892 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007893 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007894 } else if (glslangType.isCoopMat()) {
7895 glslang::TType componentType(glslangType.getBasicType());
7896 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007897 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007898 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7899 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007900 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007901 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007902 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7903 bool zero = nextConst >= consts.size();
7904 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007905 case glslang::EbtInt:
7906 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7907 break;
7908 case glslang::EbtUint:
7909 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7910 break;
7911 case glslang::EbtFloat:
7912 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7913 break;
7914 case glslang::EbtBool:
7915 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7916 break;
7917#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007918 case glslang::EbtInt8:
7919 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7920 break;
7921 case glslang::EbtUint8:
7922 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7923 break;
7924 case glslang::EbtInt16:
7925 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7926 break;
7927 case glslang::EbtUint16:
7928 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7929 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007930 case glslang::EbtInt64:
7931 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7932 break;
7933 case glslang::EbtUint64:
7934 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7935 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007936 case glslang::EbtDouble:
7937 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7938 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007939 case glslang::EbtFloat16:
7940 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7941 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007942#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007943 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007944 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007945 break;
7946 }
7947 ++nextConst;
7948 }
7949 } else {
7950 // we have a non-aggregate (scalar) constant
7951 bool zero = nextConst >= consts.size();
7952 spv::Id scalar = 0;
7953 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007954 case glslang::EbtInt:
7955 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7956 break;
7957 case glslang::EbtUint:
7958 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7959 break;
7960 case glslang::EbtFloat:
7961 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7962 break;
7963 case glslang::EbtBool:
7964 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7965 break;
7966#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007967 case glslang::EbtInt8:
7968 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7969 break;
7970 case glslang::EbtUint8:
7971 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7972 break;
7973 case glslang::EbtInt16:
7974 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7975 break;
7976 case glslang::EbtUint16:
7977 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7978 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007979 case glslang::EbtInt64:
7980 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7981 break;
7982 case glslang::EbtUint64:
7983 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7984 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007985 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007986 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007987 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007988 case glslang::EbtFloat16:
7989 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7990 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007991 case glslang::EbtReference:
7992 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7993 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7994 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007995#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007996 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007997 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007998 break;
7999 }
8000 ++nextConst;
8001 return scalar;
8002 }
8003
8004 return builder.makeCompositeConstant(typeId, spvConsts);
8005}
8006
John Kessenich7c1aa102015-10-15 13:29:11 -06008007// Return true if the node is a constant or symbol whose reading has no
8008// non-trivial observable cost or effect.
8009bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8010{
8011 // don't know what this is
8012 if (node == nullptr)
8013 return false;
8014
8015 // a constant is safe
8016 if (node->getAsConstantUnion() != nullptr)
8017 return true;
8018
8019 // not a symbol means non-trivial
8020 if (node->getAsSymbolNode() == nullptr)
8021 return false;
8022
8023 // a symbol, depends on what's being read
8024 switch (node->getType().getQualifier().storage) {
8025 case glslang::EvqTemporary:
8026 case glslang::EvqGlobal:
8027 case glslang::EvqIn:
8028 case glslang::EvqInOut:
8029 case glslang::EvqConst:
8030 case glslang::EvqConstReadOnly:
8031 case glslang::EvqUniform:
8032 return true;
8033 default:
8034 return false;
8035 }
qining25262b32016-05-06 17:25:16 -04008036}
John Kessenich7c1aa102015-10-15 13:29:11 -06008037
8038// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008039// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008040// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008041// Return true if trivial.
8042bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8043{
8044 if (node == nullptr)
8045 return false;
8046
John Kessenich84cc15f2017-05-24 16:44:47 -06008047 // count non scalars as trivial, as well as anything coming from HLSL
8048 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008049 return true;
8050
John Kessenich7c1aa102015-10-15 13:29:11 -06008051 // symbols and constants are trivial
8052 if (isTrivialLeaf(node))
8053 return true;
8054
8055 // otherwise, it needs to be a simple operation or one or two leaf nodes
8056
8057 // not a simple operation
8058 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8059 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8060 if (binaryNode == nullptr && unaryNode == nullptr)
8061 return false;
8062
8063 // not on leaf nodes
8064 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8065 return false;
8066
8067 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8068 return false;
8069 }
8070
8071 switch (node->getAsOperator()->getOp()) {
8072 case glslang::EOpLogicalNot:
8073 case glslang::EOpConvIntToBool:
8074 case glslang::EOpConvUintToBool:
8075 case glslang::EOpConvFloatToBool:
8076 case glslang::EOpConvDoubleToBool:
8077 case glslang::EOpEqual:
8078 case glslang::EOpNotEqual:
8079 case glslang::EOpLessThan:
8080 case glslang::EOpGreaterThan:
8081 case glslang::EOpLessThanEqual:
8082 case glslang::EOpGreaterThanEqual:
8083 case glslang::EOpIndexDirect:
8084 case glslang::EOpIndexDirectStruct:
8085 case glslang::EOpLogicalXor:
8086 case glslang::EOpAny:
8087 case glslang::EOpAll:
8088 return true;
8089 default:
8090 return false;
8091 }
8092}
8093
8094// Emit short-circuiting code, where 'right' is never evaluated unless
8095// the left side is true (for &&) or false (for ||).
8096spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8097{
8098 spv::Id boolTypeId = builder.makeBoolType();
8099
8100 // emit left operand
8101 builder.clearAccessChain();
8102 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008103 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008104
8105 // Operands to accumulate OpPhi operands
8106 std::vector<spv::Id> phiOperands;
8107 // accumulate left operand's phi information
8108 phiOperands.push_back(leftId);
8109 phiOperands.push_back(builder.getBuildPoint()->getId());
8110
8111 // Make the two kinds of operation symmetric with a "!"
8112 // || => emit "if (! left) result = right"
8113 // && => emit "if ( left) result = right"
8114 //
8115 // TODO: this runtime "not" for || could be avoided by adding functionality
8116 // to 'builder' to have an "else" without an "then"
8117 if (op == glslang::EOpLogicalOr)
8118 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8119
8120 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008121 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008122
8123 // emit right operand as the "then" part of the "if"
8124 builder.clearAccessChain();
8125 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008126 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008127
8128 // accumulate left operand's phi information
8129 phiOperands.push_back(rightId);
8130 phiOperands.push_back(builder.getBuildPoint()->getId());
8131
8132 // finish the "if"
8133 ifBuilder.makeEndIf();
8134
8135 // phi together the two results
8136 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8137}
8138
John Kessenicha28f7a72019-08-06 07:00:58 -06008139#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008140// Return type Id of the imported set of extended instructions corresponds to the name.
8141// Import this set if it has not been imported yet.
8142spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8143{
8144 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8145 return extBuiltinMap[name];
8146 else {
Rex Xu51596642016-09-21 18:56:12 +08008147 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008148 spv::Id extBuiltins = builder.import(name);
8149 extBuiltinMap[name] = extBuiltins;
8150 return extBuiltins;
8151 }
8152}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008153#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008154
John Kessenich140f3df2015-06-26 16:58:36 -06008155}; // end anonymous namespace
8156
8157namespace glslang {
8158
John Kessenich68d78fd2015-07-12 19:28:10 -06008159void GetSpirvVersion(std::string& version)
8160{
John Kessenich9e55f632015-07-15 10:03:39 -06008161 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008162 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008163 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008164 version = buf;
8165}
8166
John Kessenicha372a3e2017-11-02 22:32:14 -06008167// For low-order part of the generator's magic number. Bump up
8168// when there is a change in the style (e.g., if SSA form changes,
8169// or a different instruction sequence to do something gets used).
8170int GetSpirvGeneratorVersion()
8171{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008172 // return 1; // start
8173 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008174 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008175 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008176 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008177 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8178 // versions 4 and 6 each generate OpArrayLength as it has long been done
8179 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008180}
8181
John Kessenich140f3df2015-06-26 16:58:36 -06008182// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008183void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008184{
8185 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008186 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008187 if (out.fail())
8188 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008189 for (int i = 0; i < (int)spirv.size(); ++i) {
8190 unsigned int word = spirv[i];
8191 out.write((const char*)&word, 4);
8192 }
8193 out.close();
8194}
8195
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008196// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008197void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008198{
John Kessenich155d3512019-08-08 23:29:20 -06008199#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008200 std::ofstream out;
8201 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008202 if (out.fail())
8203 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008204 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008205 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008206 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008207 if (varName != nullptr) {
8208 out << "\t #pragma once" << std::endl;
8209 out << "const uint32_t " << varName << "[] = {" << std::endl;
8210 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008211 const int WORDS_PER_LINE = 8;
8212 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8213 out << "\t";
8214 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8215 const unsigned int word = spirv[i + j];
8216 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8217 if (i + j + 1 < (int)spirv.size()) {
8218 out << ",";
8219 }
8220 }
8221 out << std::endl;
8222 }
Flavio15017db2017-02-15 14:29:33 -08008223 if (varName != nullptr) {
8224 out << "};";
8225 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008226 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008227#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008228}
8229
John Kessenich140f3df2015-06-26 16:58:36 -06008230//
8231// Set up the glslang traversal
8232//
John Kessenich4e11b612018-08-30 16:56:59 -06008233void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008234{
Lei Zhang17535f72016-05-04 15:55:59 -04008235 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008236 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008237}
8238
John Kessenich4e11b612018-08-30 16:56:59 -06008239void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008240 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008241{
John Kessenich140f3df2015-06-26 16:58:36 -06008242 TIntermNode* root = intermediate.getTreeRoot();
8243
8244 if (root == 0)
8245 return;
8246
John Kessenich4e11b612018-08-30 16:56:59 -06008247 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008248 if (options == nullptr)
8249 options = &defaultOptions;
8250
John Kessenich4e11b612018-08-30 16:56:59 -06008251 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008252
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008253 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008254 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008255 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008256 it.dumpSpv(spirv);
8257
GregFfb03a552018-03-29 11:49:14 -06008258#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008259 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8260 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008261 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8262 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008263 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008264 prelegalization = false;
8265 }
John Kessenich717c80a2018-08-23 15:17:10 -06008266
John Kessenich4e11b612018-08-30 16:56:59 -06008267 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008268 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008269
John Kessenich717c80a2018-08-23 15:17:10 -06008270 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008271 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008272
GregFcd1f1692017-09-21 18:40:22 -06008273#endif
8274
John Kessenich4e11b612018-08-30 16:56:59 -06008275 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008276}
8277
8278}; // end namespace glslang