blob: 2c9fcd81a216ce1a866e318adfd63d659214ca17 [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);
John Kessenichdeec1932019-08-13 08:00:30 -0600393 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800394 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600395 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800396 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) {
John Kessenichdeec1932019-08-13 08:00:30 -06001183 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001184 return spv::StorageClassAtomicCounter;
1185 if (type.containsOpaque())
1186 return spv::StorageClassUniformConstant;
1187 }
1188
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001189 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001190 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001191 return spv::StorageClassShaderRecordBufferNV;
1192 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001193
John Kessenichbed4e4f2017-09-08 02:38:07 -06001194 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001195 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001196 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001197 }
1198
1199 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001200 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001201 return spv::StorageClassPushConstant;
1202 if (type.getBasicType() == glslang::EbtBlock)
1203 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001204 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001205 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001206
1207 switch (type.getQualifier().storage) {
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1209 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1210 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenicha28f7a72019-08-06 07:00:58 -06001211#ifndef GLSLANG_WEB
John Kessenichdeec1932019-08-13 08:00:30 -06001212 case glslang::EvqShared: return spv::StorageClassWorkgroup;
Ashwin Leleff1783d2018-10-22 16:41:44 -07001213 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1214 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1215 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1216 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1217 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001218#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001219 default:
1220 assert(0);
1221 break;
1222 }
1223
1224 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001225}
1226
John Kessenich5611c6d2018-04-05 11:25:02 -06001227// Add capabilities pertaining to how an array is indexed.
1228void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1229 const glslang::TType& indexType)
1230{
John Kessenichb9197c82019-08-11 07:41:45 -06001231#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001232 if (indexType.getQualifier().isNonUniform()) {
1233 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001234 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001235 if (baseType.getBasicType() == glslang::EbtSampler) {
1236 if (baseType.getQualifier().hasAttachment())
1237 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001238 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001239 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001240 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001241 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1242 else if (baseType.isImage())
1243 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1244 else if (baseType.isTexture())
1245 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1246 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1247 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1248 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1249 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1250 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1251 }
1252 } else {
1253 // assume a dynamically uniform index
1254 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001255 if (baseType.getQualifier().hasAttachment()) {
1256 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001257 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001258 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001259 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001260 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001261 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001262 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001263 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001264 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001265 }
1266 }
John Kessenichb9197c82019-08-11 07:41:45 -06001267#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001268}
1269
qining25262b32016-05-06 17:25:16 -04001270// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001271// descriptor set.
1272bool IsDescriptorResource(const glslang::TType& type)
1273{
John Kessenichf7497e22016-03-08 21:36:22 -07001274 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001275 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001276 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001277 ! type.getQualifier().isShaderRecordNV() &&
1278 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001279
1280 // non block...
1281 // basically samplerXXX/subpass/sampler/texture are all included
1282 // if they are the global-scope-class, not the function parameter
1283 // (or local, if they ever exist) class.
1284 if (type.getBasicType() == glslang::EbtSampler)
1285 return type.getQualifier().isUniformOrBuffer();
1286
1287 // None of the above.
1288 return false;
1289}
1290
John Kesseniche0b6cad2015-12-24 10:30:13 -07001291void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1292{
1293 if (child.layoutMatrix == glslang::ElmNone)
1294 child.layoutMatrix = parent.layoutMatrix;
1295
1296 if (parent.invariant)
1297 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001298 if (parent.flat)
1299 child.flat = true;
1300 if (parent.centroid)
1301 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001302#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001303 if (parent.nopersp)
1304 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001305 if (parent.explicitInterp)
1306 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001307 if (parent.perPrimitiveNV)
1308 child.perPrimitiveNV = true;
1309 if (parent.perViewNV)
1310 child.perViewNV = true;
1311 if (parent.perTaskNV)
1312 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001313 if (parent.patch)
1314 child.patch = true;
1315 if (parent.sample)
1316 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001317 if (parent.coherent)
1318 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001319 if (parent.devicecoherent)
1320 child.devicecoherent = true;
1321 if (parent.queuefamilycoherent)
1322 child.queuefamilycoherent = true;
1323 if (parent.workgroupcoherent)
1324 child.workgroupcoherent = true;
1325 if (parent.subgroupcoherent)
1326 child.subgroupcoherent = true;
1327 if (parent.nonprivate)
1328 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001329 if (parent.volatil)
1330 child.volatil = true;
1331 if (parent.restrict)
1332 child.restrict = true;
1333 if (parent.readonly)
1334 child.readonly = true;
1335 if (parent.writeonly)
1336 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001337#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001338}
1339
John Kessenichf2b7f332016-09-01 17:05:23 -06001340bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001341{
John Kessenich7b9fa252016-01-21 18:56:57 -07001342 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001343 // - struct members might inherit from a struct declaration
1344 // (note that non-block structs don't explicitly inherit,
1345 // only implicitly, meaning no decoration involved)
1346 // - affect decorations on the struct members
1347 // (note smooth does not, and expecting something like volatile
1348 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001349 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001350 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenich140f3df2015-06-26 16:58:36 -06001353//
1354// Implement the TGlslangToSpvTraverser class.
1355//
1356
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001357TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001358 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1359 : TIntermTraverser(true, false, true),
1360 options(options),
1361 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001362 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001363 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001364 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001365 glslangIntermediate(glslangIntermediate),
1366 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001367{
1368 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1369
1370 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001371 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1372 glslangIntermediate->getVersion());
1373
John Kessenich121853f2017-05-31 17:11:16 -06001374 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001375 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001376 builder.setSourceFile(glslangIntermediate->getSourceFile());
1377
1378 // Set the source shader's text. If for SPV version 1.0, include
1379 // a preamble in comments stating the OpModuleProcessed instructions.
1380 // Otherwise, emit those as actual instructions.
1381 std::string text;
1382 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1383 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001384 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001385 text.append("// OpModuleProcessed ");
1386 text.append(processes[p]);
1387 text.append("\n");
1388 } else
1389 builder.addModuleProcessed(processes[p]);
1390 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001391 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001392 text.append("#line 1\n");
1393 text.append(glslangIntermediate->getSourceText());
1394 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001395 // Pass name and text for all included files
1396 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1397 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1398 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001399 }
John Kessenich140f3df2015-06-26 16:58:36 -06001400 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001401
1402 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1403 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1404
1405 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1406 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1407 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1408 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1409 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001410 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001411 memoryModel = spv::MemoryModelVulkanKHR;
1412 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001413 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001414 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001415 builder.setMemoryModel(addressingModel, memoryModel);
1416
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001417 if (glslangIntermediate->usingVariablePointers()) {
1418 builder.addCapability(spv::CapabilityVariablePointers);
1419 }
1420
John Kessenicheee9d532016-09-19 18:09:30 -06001421 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1422 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001423
1424 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001425 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1426 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001427 builder.addSourceExtension(it->c_str());
1428
1429 // Add the top-level modes for this shader.
1430
John Kessenich92187592016-02-01 13:45:25 -07001431 if (glslangIntermediate->getXfbMode()) {
1432 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001434 }
John Kessenich140f3df2015-06-26 16:58:36 -06001435
1436 unsigned int mode;
1437 switch (glslangIntermediate->getStage()) {
1438 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001439 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001440 break;
1441
John Kessenicha28f7a72019-08-06 07:00:58 -06001442 case EShLangFragment:
1443 builder.addCapability(spv::CapabilityShader);
1444 if (glslangIntermediate->getPixelCenterInteger())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1446
1447 if (glslangIntermediate->getOriginUpperLeft())
1448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1449 else
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1451
1452 if (glslangIntermediate->getEarlyFragmentTests())
1453 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1454
1455 if (glslangIntermediate->getPostDepthCoverage()) {
1456 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1457 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1458 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1459 }
1460
John Kessenichb9197c82019-08-11 07:41:45 -06001461 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1462 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1463
1464#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001465 switch(glslangIntermediate->getDepth()) {
1466 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1467 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1468 default: mode = spv::ExecutionModeMax; break;
1469 }
1470 if (mode != spv::ExecutionModeMax)
1471 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001472 switch (glslangIntermediate->getInterlockOrdering()) {
1473 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1474 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1475 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1476 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1477 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1478 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1479 default: mode = spv::ExecutionModeMax; break;
1480 }
1481 if (mode != spv::ExecutionModeMax) {
1482 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1483 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1484 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1485 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1486 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1487 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1488 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1489 } else {
1490 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1491 }
1492 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1493 }
John Kessenichb9197c82019-08-11 07:41:45 -06001494#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001495 break;
1496
1497#ifndef GLSLANG_WEB
1498 case EShLangCompute:
1499 builder.addCapability(spv::CapabilityShader);
1500 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1501 glslangIntermediate->getLocalSize(1),
1502 glslangIntermediate->getLocalSize(2));
1503 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1504 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1505 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1506 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1507 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1508 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1509 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1510 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1511 }
1512 break;
steve-lunarge7412492017-03-23 11:56:07 -06001513 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001514 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001515 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001516
steve-lunarge7412492017-03-23 11:56:07 -06001517 glslang::TLayoutGeometry primitive;
1518
1519 if (glslangIntermediate->getStage() == EShLangTessControl) {
1520 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1521 primitive = glslangIntermediate->getOutputPrimitive();
1522 } else {
1523 primitive = glslangIntermediate->getInputPrimitive();
1524 }
1525
1526 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001527 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1528 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1529 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001530 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001531 }
John Kessenich4016e382016-07-15 11:53:56 -06001532 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001533 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1534
John Kesseniche6903322015-10-13 16:29:02 -06001535 switch (glslangIntermediate->getVertexSpacing()) {
1536 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1537 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1538 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001539 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001540 }
John Kessenich4016e382016-07-15 11:53:56 -06001541 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001542 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1543
1544 switch (glslangIntermediate->getVertexOrder()) {
1545 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1546 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001547 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001548 }
John Kessenich4016e382016-07-15 11:53:56 -06001549 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001550 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1551
1552 if (glslangIntermediate->getPointMode())
1553 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001554 break;
1555
1556 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001557 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001558 switch (glslangIntermediate->getInputPrimitive()) {
1559 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1560 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1561 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001562 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001563 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001564 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001565 }
John Kessenich4016e382016-07-15 11:53:56 -06001566 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001567 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001568
John Kessenich140f3df2015-06-26 16:58:36 -06001569 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1570
1571 switch (glslangIntermediate->getOutputPrimitive()) {
1572 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1573 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1574 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001575 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001576 }
John Kessenich4016e382016-07-15 11:53:56 -06001577 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001578 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1579 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1580 break;
1581
Chao Chenb50c02e2018-09-19 11:42:24 -07001582 case EShLangRayGenNV:
1583 case EShLangIntersectNV:
1584 case EShLangAnyHitNV:
1585 case EShLangClosestHitNV:
1586 case EShLangMissNV:
1587 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001588 builder.addCapability(spv::CapabilityRayTracingNV);
1589 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001590 break;
Chao Chen3c366992018-09-19 11:41:59 -07001591 case EShLangTaskNV:
1592 case EShLangMeshNV:
1593 builder.addCapability(spv::CapabilityMeshShadingNV);
1594 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1595 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1596 glslangIntermediate->getLocalSize(1),
1597 glslangIntermediate->getLocalSize(2));
1598 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1599 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1600 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1601
1602 switch (glslangIntermediate->getOutputPrimitive()) {
1603 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1604 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1605 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1606 default: mode = spv::ExecutionModeMax; break;
1607 }
1608 if (mode != spv::ExecutionModeMax)
1609 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1610 }
1611 break;
1612#endif
1613
John Kessenich140f3df2015-06-26 16:58:36 -06001614 default:
1615 break;
1616 }
John Kessenich140f3df2015-06-26 16:58:36 -06001617}
1618
John Kessenichfca82622016-11-26 13:23:20 -07001619// Finish creating SPV, after the traversal is complete.
1620void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001621{
John Kessenichf04c51b2018-08-03 15:56:12 -06001622 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001623 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001624 builder.setBuildPoint(shaderEntry->getLastBlock());
1625 builder.leaveFunction();
1626 }
1627
John Kessenich7ba63412015-12-20 17:37:07 -07001628 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001629 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1630 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001631
John Kessenich23d27752019-07-28 02:12:10 -06001632#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001633 // Add capabilities, extensions, remove unneeded decorations, etc.,
1634 // based on the resulting SPIR-V.
1635 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001636#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001637}
1638
John Kessenichfca82622016-11-26 13:23:20 -07001639// Write the SPV into 'out'.
1640void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001641{
John Kessenichfca82622016-11-26 13:23:20 -07001642 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001643}
1644
1645//
1646// Implement the traversal functions.
1647//
1648// Return true from interior nodes to have the external traversal
1649// continue on to children. Return false if children were
1650// already processed.
1651//
1652
1653//
qining25262b32016-05-06 17:25:16 -04001654// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001655// - uniform/input reads
1656// - output writes
1657// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1658// - something simple that degenerates into the last bullet
1659//
1660void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1661{
qining75d1d802016-04-06 14:42:01 -04001662 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1663 if (symbol->getType().getQualifier().isSpecConstant())
1664 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1665
John Kessenich140f3df2015-06-26 16:58:36 -06001666 // getSymbolId() will set up all the IO decorations on the first call.
1667 // Formal function parameters were mapped during makeFunctions().
1668 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001669
John Kessenich7ba63412015-12-20 17:37:07 -07001670 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001671 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001672 // Consider adding to the OpEntryPoint interface list.
1673 // Only looking at structures if they have at least one member.
1674 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1675 spv::StorageClass sc = builder.getStorageClass(id);
1676 // Before SPIR-V 1.4, we only want to include Input and Output.
1677 // Starting with SPIR-V 1.4, we want all globals.
1678 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1679 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001680 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001681 }
John Kessenich5f77d862017-09-19 11:09:59 -06001682 }
John Kessenich9c14f772019-06-17 08:38:35 -06001683
1684 // If the SPIR-V type is required to be different than the AST type,
1685 // translate now from the SPIR-V type to the AST type, for the consuming
1686 // operation.
1687 // Note this turns it from an l-value to an r-value.
1688 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1689 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1690 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001691 }
1692
1693 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001694 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001695 // Prepare to generate code for the access
1696
1697 // L-value chains will be computed left to right. We're on the symbol now,
1698 // which is the left-most part of the access chain, so now is "clear" time,
1699 // followed by setting the base.
1700 builder.clearAccessChain();
1701
1702 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001703 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001704 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001705 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001706 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001707 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001708 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001709 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001710 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1711 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001712 builder.setAccessChainRValue(id);
1713 else
1714 builder.setAccessChainLValue(id);
1715 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001716
John Kessenichb9197c82019-08-11 07:41:45 -06001717#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001718 // Process linkage-only nodes for any special additional interface work.
1719 if (linkageOnly) {
1720 if (glslangIntermediate->getHlslFunctionality1()) {
1721 // Map implicit counter buffers to their originating buffers, which should have been
1722 // seen by now, given earlier pruning of unused counters, and preservation of order
1723 // of declaration.
1724 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1725 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1726 // Save possible originating buffers for counter buffers, keyed by
1727 // making the potential counter-buffer name.
1728 std::string keyName = symbol->getName().c_str();
1729 keyName = glslangIntermediate->addCounterBufferName(keyName);
1730 counterOriginator[keyName] = symbol;
1731 } else {
1732 // Handle a counter buffer, by finding the saved originating buffer.
1733 std::string keyName = symbol->getName().c_str();
1734 auto it = counterOriginator.find(keyName);
1735 if (it != counterOriginator.end()) {
1736 id = getSymbolId(it->second);
1737 if (id != spv::NoResult) {
1738 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001739 if (counterId != spv::NoResult) {
1740 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001741 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001742 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001743 }
1744 }
1745 }
1746 }
1747 }
1748 }
John Kessenich155d3512019-08-08 23:29:20 -06001749#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001750}
1751
1752bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1753{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001754 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001755
qining40887662016-04-03 22:20:42 -04001756 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1757 if (node->getType().getQualifier().isSpecConstant())
1758 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1759
John Kessenich140f3df2015-06-26 16:58:36 -06001760 // First, handle special cases
1761 switch (node->getOp()) {
1762 case glslang::EOpAssign:
1763 case glslang::EOpAddAssign:
1764 case glslang::EOpSubAssign:
1765 case glslang::EOpMulAssign:
1766 case glslang::EOpVectorTimesMatrixAssign:
1767 case glslang::EOpVectorTimesScalarAssign:
1768 case glslang::EOpMatrixTimesScalarAssign:
1769 case glslang::EOpMatrixTimesMatrixAssign:
1770 case glslang::EOpDivAssign:
1771 case glslang::EOpModAssign:
1772 case glslang::EOpAndAssign:
1773 case glslang::EOpInclusiveOrAssign:
1774 case glslang::EOpExclusiveOrAssign:
1775 case glslang::EOpLeftShiftAssign:
1776 case glslang::EOpRightShiftAssign:
1777 // A bin-op assign "a += b" means the same thing as "a = a + b"
1778 // where a is evaluated before b. For a simple assignment, GLSL
1779 // says to evaluate the left before the right. So, always, left
1780 // node then right node.
1781 {
1782 // get the left l-value, save it away
1783 builder.clearAccessChain();
1784 node->getLeft()->traverse(this);
1785 spv::Builder::AccessChain lValue = builder.getAccessChain();
1786
1787 // evaluate the right
1788 builder.clearAccessChain();
1789 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001790 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001791
1792 if (node->getOp() != glslang::EOpAssign) {
1793 // the left is also an r-value
1794 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001795 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001796
1797 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001798 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001799 TranslateNoContractionDecoration(node->getType().getQualifier()),
1800 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001801 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001802 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1803 node->getType().getBasicType());
1804
1805 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001806 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001807 }
1808
1809 // store the result
1810 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001811 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001812
1813 // assignments are expressions having an rValue after they are evaluated...
1814 builder.clearAccessChain();
1815 builder.setAccessChainRValue(rValue);
1816 }
1817 return false;
1818 case glslang::EOpIndexDirect:
1819 case glslang::EOpIndexDirectStruct:
1820 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001821 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001822 // Get the left part of the access chain.
1823 node->getLeft()->traverse(this);
1824
1825 // Add the next element in the chain
1826
David Netoa901ffe2016-06-08 14:11:40 +01001827 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001828 if (! node->getLeft()->getType().isArray() &&
1829 node->getLeft()->getType().isVector() &&
1830 node->getOp() == glslang::EOpIndexDirect) {
1831 // This is essentially a hard-coded vector swizzle of size 1,
1832 // so short circuit the access-chain stuff with a swizzle.
1833 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001834 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001835 int dummySize;
1836 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1837 TranslateCoherent(node->getLeft()->getType()),
1838 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001839 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001840
1841 // Load through a block reference is performed with a dot operator that
1842 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1843 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001844 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001845 !node->getLeft()->getType().isArray() &&
1846 node->getOp() == glslang::EOpIndexDirectStruct)
1847 {
1848 spv::Id left = accessChainLoad(node->getLeft()->getType());
1849 builder.clearAccessChain();
1850 builder.setAccessChainLValue(left);
1851 }
1852
David Netoa901ffe2016-06-08 14:11:40 +01001853 int spvIndex = glslangIndex;
1854 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1855 node->getOp() == glslang::EOpIndexDirectStruct)
1856 {
1857 // This may be, e.g., an anonymous block-member selection, which generally need
1858 // index remapping due to hidden members in anonymous blocks.
1859 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1860 assert(remapper.size() > 0);
1861 spvIndex = remapper[glslangIndex];
1862 }
John Kessenichebb50532016-05-16 19:22:05 -06001863
David Netoa901ffe2016-06-08 14:11:40 +01001864 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001865 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001866
1867 // Add capabilities here for accessing PointSize and clip/cull distance.
1868 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001869 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001870 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 }
1872 }
1873 return false;
1874 case glslang::EOpIndexIndirect:
1875 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001876 // Array, matrix, or vector indirection with variable index.
1877 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001878 // matrices are arrays of vectors, so will also work for a matrix.
1879 // Will use the access chain's 'component' for variable index into a vector.
1880
1881 // This adapter is building access chains left to right.
1882 // Set up the access chain to the left.
1883 node->getLeft()->traverse(this);
1884
1885 // save it so that computing the right side doesn't trash it
1886 spv::Builder::AccessChain partial = builder.getAccessChain();
1887
1888 // compute the next index in the chain
1889 builder.clearAccessChain();
1890 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001891 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001892
John Kessenich5611c6d2018-04-05 11:25:02 -06001893 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1894
John Kessenich140f3df2015-06-26 16:58:36 -06001895 // restore the saved access chain
1896 builder.setAccessChain(partial);
1897
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001898 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1899 int dummySize;
1900 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1901 TranslateCoherent(node->getLeft()->getType()),
1902 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1903 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001904 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001905 }
1906 return false;
1907 case glslang::EOpVectorSwizzle:
1908 {
1909 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001910 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001912 int dummySize;
1913 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1914 TranslateCoherent(node->getLeft()->getType()),
1915 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001916 }
1917 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001918 case glslang::EOpMatrixSwizzle:
1919 logger->missingFunctionality("matrix swizzle");
1920 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001921 case glslang::EOpLogicalOr:
1922 case glslang::EOpLogicalAnd:
1923 {
1924
1925 // These may require short circuiting, but can sometimes be done as straight
1926 // binary operations. The right operand must be short circuited if it has
1927 // side effects, and should probably be if it is complex.
1928 if (isTrivial(node->getRight()->getAsTyped()))
1929 break; // handle below as a normal binary operation
1930 // otherwise, we need to do dynamic short circuiting on the right operand
1931 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1932 builder.clearAccessChain();
1933 builder.setAccessChainRValue(result);
1934 }
1935 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001936 default:
1937 break;
1938 }
1939
1940 // Assume generic binary op...
1941
John Kessenich32cfd492016-02-02 12:37:46 -07001942 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001943 builder.clearAccessChain();
1944 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001945 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001946
John Kessenich32cfd492016-02-02 12:37:46 -07001947 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001948 builder.clearAccessChain();
1949 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001950 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001951
John Kessenich32cfd492016-02-02 12:37:46 -07001952 // get result
John Kessenichead86222018-03-28 18:01:20 -06001953 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001954 TranslateNoContractionDecoration(node->getType().getQualifier()),
1955 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001956 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001957 convertGlslangToSpvType(node->getType()), left, right,
1958 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001959
John Kessenich50e57562015-12-21 21:21:11 -07001960 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001961 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001962 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001963 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001964 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001965 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001966 return false;
1967 }
John Kessenich140f3df2015-06-26 16:58:36 -06001968}
1969
John Kessenich9c14f772019-06-17 08:38:35 -06001970// Figure out what, if any, type changes are needed when accessing a specific built-in.
1971// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1972// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1973std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1974 const glslang::TType& glslangType)
1975{
1976 switch(builtIn)
1977 {
1978 case spv::BuiltInSubgroupEqMask:
1979 case spv::BuiltInSubgroupGeMask:
1980 case spv::BuiltInSubgroupGtMask:
1981 case spv::BuiltInSubgroupLeMask:
1982 case spv::BuiltInSubgroupLtMask: {
1983 // these require changing a 64-bit scaler -> a vector of 32-bit components
1984 if (glslangType.isVector())
1985 break;
1986 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1987 builder.makeUintType(64));
1988 return ret;
1989 }
1990 default:
1991 break;
1992 }
1993
1994 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1995 return ret;
1996}
1997
1998// For an object previously identified (see getForcedType() and forceType)
1999// as needing type translations, do the translation needed for a load, turning
2000// an L-value into in R-value.
2001spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2002{
2003 const auto forceIt = forceType.find(object);
2004 if (forceIt == forceType.end())
2005 return object;
2006
2007 spv::Id desiredTypeId = forceIt->second;
2008 spv::Id objectTypeId = builder.getTypeId(object);
2009 assert(builder.isPointerType(objectTypeId));
2010 objectTypeId = builder.getContainedTypeId(objectTypeId);
2011 if (builder.isVectorType(objectTypeId) &&
2012 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2013 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2014 // handle 32-bit v.xy* -> 64-bit
2015 builder.clearAccessChain();
2016 builder.setAccessChainLValue(object);
2017 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2018 std::vector<spv::Id> components;
2019 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2020 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2021
2022 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2023 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2024 builder.createCompositeConstruct(vecType, components));
2025 } else {
2026 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2027 }
2028 } else {
2029 logger->missingFunctionality("forcing non 32-bit vector type");
2030 }
2031
2032 return object;
2033}
2034
John Kessenich140f3df2015-06-26 16:58:36 -06002035bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2036{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002037 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002038
qining40887662016-04-03 22:20:42 -04002039 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2040 if (node->getType().getQualifier().isSpecConstant())
2041 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2042
John Kessenichfc51d282015-08-19 13:34:18 -06002043 spv::Id result = spv::NoResult;
2044
2045 // try texturing first
2046 result = createImageTextureFunctionCall(node);
2047 if (result != spv::NoResult) {
2048 builder.clearAccessChain();
2049 builder.setAccessChainRValue(result);
2050
2051 return false; // done with this node
2052 }
2053
2054 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002055
2056 if (node->getOp() == glslang::EOpArrayLength) {
2057 // Quite special; won't want to evaluate the operand.
2058
John Kessenich5611c6d2018-04-05 11:25:02 -06002059 // Currently, the front-end does not allow .length() on an array until it is sized,
2060 // except for the last block membeor of an SSBO.
2061 // TODO: If this changes, link-time sized arrays might show up here, and need their
2062 // size extracted.
2063
John Kessenichc9a80832015-09-12 12:17:44 -06002064 // Normal .length() would have been constant folded by the front-end.
2065 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002066 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002067
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002068 spv::Id length;
2069 if (node->getOperand()->getType().isCoopMat()) {
2070 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2071
2072 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2073 assert(builder.isCooperativeMatrixType(typeId));
2074
2075 length = builder.createCooperativeMatrixLength(typeId);
2076 } else {
2077 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2078 block->traverse(this);
2079 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2080 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2081 }
John Kessenichc9a80832015-09-12 12:17:44 -06002082
John Kessenich8c869672018-11-28 07:01:37 -07002083 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2084 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2085 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002086 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2087 if (builder.isInSpecConstCodeGenMode()) {
2088 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2089 } else {
2090 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2091 }
2092 }
John Kessenich8c869672018-11-28 07:01:37 -07002093
John Kessenichc9a80832015-09-12 12:17:44 -06002094 builder.clearAccessChain();
2095 builder.setAccessChainRValue(length);
2096
2097 return false;
2098 }
2099
John Kessenichfc51d282015-08-19 13:34:18 -06002100 // Start by evaluating the operand
2101
John Kessenich8c8505c2016-07-26 12:50:38 -06002102 // Does it need a swizzle inversion? If so, evaluation is inverted;
2103 // operate first on the swizzle base, then apply the swizzle.
2104 spv::Id invertedType = spv::NoType;
2105 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2106 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2107 invertedType = getInvertedSwizzleType(*node->getOperand());
2108
John Kessenich140f3df2015-06-26 16:58:36 -06002109 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002110 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002111 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002112 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002113 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002114 operandNode = node->getOperand();
2115
2116 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002117
Rex Xufc618912015-09-09 16:42:49 +08002118 spv::Id operand = spv::NoResult;
2119
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002120 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2121
John Kessenichfb4f2332019-08-09 03:49:15 -06002122#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002123 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2124 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002125 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002126 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002127 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002128 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2129 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2130 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002131#endif
2132 {
John Kessenich32cfd492016-02-02 12:37:46 -07002133 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002134 }
John Kessenich140f3df2015-06-26 16:58:36 -06002135
John Kessenichead86222018-03-28 18:01:20 -06002136 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002137 TranslateNoContractionDecoration(node->getType().getQualifier()),
2138 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002139
2140 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002141 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002142 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002143
2144 // if not, then possibly an operation
2145 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002146 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002147
2148 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002149 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002150 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002151 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002152 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002153
John Kessenich140f3df2015-06-26 16:58:36 -06002154 builder.clearAccessChain();
2155 builder.setAccessChainRValue(result);
2156
2157 return false; // done with this node
2158 }
2159
2160 // it must be a special case, check...
2161 switch (node->getOp()) {
2162 case glslang::EOpPostIncrement:
2163 case glslang::EOpPostDecrement:
2164 case glslang::EOpPreIncrement:
2165 case glslang::EOpPreDecrement:
2166 {
2167 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002168 spv::Id one = 0;
2169 if (node->getBasicType() == glslang::EbtFloat)
2170 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002171#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002172 else if (node->getBasicType() == glslang::EbtDouble)
2173 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002174 else if (node->getBasicType() == glslang::EbtFloat16)
2175 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002176 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2177 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002178 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2179 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002180 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2181 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002182#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002183 else
2184 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002185 glslang::TOperator op;
2186 if (node->getOp() == glslang::EOpPreIncrement ||
2187 node->getOp() == glslang::EOpPostIncrement)
2188 op = glslang::EOpAdd;
2189 else
2190 op = glslang::EOpSub;
2191
John Kessenichead86222018-03-28 18:01:20 -06002192 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002193 convertGlslangToSpvType(node->getType()), operand, one,
2194 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002195 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002196
2197 // The result of operation is always stored, but conditionally the
2198 // consumed result. The consumed result is always an r-value.
2199 builder.accessChainStore(result);
2200 builder.clearAccessChain();
2201 if (node->getOp() == glslang::EOpPreIncrement ||
2202 node->getOp() == glslang::EOpPreDecrement)
2203 builder.setAccessChainRValue(result);
2204 else
2205 builder.setAccessChainRValue(operand);
2206 }
2207
2208 return false;
2209
John Kessenich155d3512019-08-08 23:29:20 -06002210#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002211 case glslang::EOpEmitStreamVertex:
2212 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2213 return false;
2214 case glslang::EOpEndStreamPrimitive:
2215 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2216 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002217#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002218
2219 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002220 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002221 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002222 }
John Kessenich140f3df2015-06-26 16:58:36 -06002223}
2224
Jeff Bolz53134492019-06-25 13:31:10 -05002225// Construct a composite object, recursively copying members if their types don't match
2226spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2227{
2228 for (int c = 0; c < (int)constituents.size(); ++c) {
2229 spv::Id& constituent = constituents[c];
2230 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2231 spv::Id rType = builder.getTypeId(constituent);
2232 if (lType != rType) {
2233 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2234 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2235 } else if (builder.isStructType(rType)) {
2236 std::vector<spv::Id> rTypeConstituents;
2237 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2238 for (int i = 0; i < numrTypeConstituents; ++i) {
2239 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2240 }
2241 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2242 } else {
2243 assert(builder.isArrayType(rType));
2244 std::vector<spv::Id> rTypeConstituents;
2245 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2246
2247 spv::Id elementRType = builder.getContainedTypeId(rType);
2248 for (int i = 0; i < numrTypeConstituents; ++i) {
2249 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2250 }
2251 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2252 }
2253 }
2254 }
2255 return builder.createCompositeConstruct(resultTypeId, constituents);
2256}
2257
John Kessenich140f3df2015-06-26 16:58:36 -06002258bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2259{
qining27e04a02016-04-14 16:40:20 -04002260 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2261 if (node->getType().getQualifier().isSpecConstant())
2262 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2263
John Kessenichfc51d282015-08-19 13:34:18 -06002264 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002265 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2266 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002267
2268 // try texturing
2269 result = createImageTextureFunctionCall(node);
2270 if (result != spv::NoResult) {
2271 builder.clearAccessChain();
2272 builder.setAccessChainRValue(result);
2273
2274 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002275 }
2276#ifndef GLSLANG_WEB
2277 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002278 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002279 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002280 // "imageStore" is a special case, which has no result
2281 return false;
2282 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002283#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002284
John Kessenich140f3df2015-06-26 16:58:36 -06002285 glslang::TOperator binOp = glslang::EOpNull;
2286 bool reduceComparison = true;
2287 bool isMatrix = false;
2288 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002289 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002290
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002291 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2292
John Kessenich140f3df2015-06-26 16:58:36 -06002293 assert(node->getOp());
2294
John Kessenichf6640762016-08-01 19:44:00 -06002295 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002296
2297 switch (node->getOp()) {
2298 case glslang::EOpSequence:
2299 {
2300 if (preVisit)
2301 ++sequenceDepth;
2302 else
2303 --sequenceDepth;
2304
2305 if (sequenceDepth == 1) {
2306 // If this is the parent node of all the functions, we want to see them
2307 // early, so all call points have actual SPIR-V functions to reference.
2308 // In all cases, still let the traverser visit the children for us.
2309 makeFunctions(node->getAsAggregate()->getSequence());
2310
John Kessenich6fccb3c2016-09-19 16:01:41 -06002311 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002312 // anything else gets there, so visit out of order, doing them all now.
2313 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2314
John Kessenich6a60c2f2016-12-08 21:01:59 -07002315 // 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 -06002316 // so do them manually.
2317 visitFunctions(node->getAsAggregate()->getSequence());
2318
2319 return false;
2320 }
2321
2322 return true;
2323 }
2324 case glslang::EOpLinkerObjects:
2325 {
2326 if (visit == glslang::EvPreVisit)
2327 linkageOnly = true;
2328 else
2329 linkageOnly = false;
2330
2331 return true;
2332 }
2333 case glslang::EOpComma:
2334 {
2335 // processing from left to right naturally leaves the right-most
2336 // lying around in the access chain
2337 glslang::TIntermSequence& glslangOperands = node->getSequence();
2338 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2339 glslangOperands[i]->traverse(this);
2340
2341 return false;
2342 }
2343 case glslang::EOpFunction:
2344 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002345 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002346 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002347 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002348 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002349 } else {
2350 handleFunctionEntry(node);
2351 }
2352 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002353 if (inEntryPoint)
2354 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002355 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002356 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002357 }
2358
2359 return true;
2360 case glslang::EOpParameters:
2361 // Parameters will have been consumed by EOpFunction processing, but not
2362 // the body, so we still visited the function node's children, making this
2363 // child redundant.
2364 return false;
2365 case glslang::EOpFunctionCall:
2366 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002367 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002368 if (node->isUserDefined())
2369 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002370 // 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 -07002371 if (result) {
2372 builder.clearAccessChain();
2373 builder.setAccessChainRValue(result);
2374 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002375 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002376
2377 return false;
2378 }
2379 case glslang::EOpConstructMat2x2:
2380 case glslang::EOpConstructMat2x3:
2381 case glslang::EOpConstructMat2x4:
2382 case glslang::EOpConstructMat3x2:
2383 case glslang::EOpConstructMat3x3:
2384 case glslang::EOpConstructMat3x4:
2385 case glslang::EOpConstructMat4x2:
2386 case glslang::EOpConstructMat4x3:
2387 case glslang::EOpConstructMat4x4:
2388 case glslang::EOpConstructDMat2x2:
2389 case glslang::EOpConstructDMat2x3:
2390 case glslang::EOpConstructDMat2x4:
2391 case glslang::EOpConstructDMat3x2:
2392 case glslang::EOpConstructDMat3x3:
2393 case glslang::EOpConstructDMat3x4:
2394 case glslang::EOpConstructDMat4x2:
2395 case glslang::EOpConstructDMat4x3:
2396 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002397 case glslang::EOpConstructIMat2x2:
2398 case glslang::EOpConstructIMat2x3:
2399 case glslang::EOpConstructIMat2x4:
2400 case glslang::EOpConstructIMat3x2:
2401 case glslang::EOpConstructIMat3x3:
2402 case glslang::EOpConstructIMat3x4:
2403 case glslang::EOpConstructIMat4x2:
2404 case glslang::EOpConstructIMat4x3:
2405 case glslang::EOpConstructIMat4x4:
2406 case glslang::EOpConstructUMat2x2:
2407 case glslang::EOpConstructUMat2x3:
2408 case glslang::EOpConstructUMat2x4:
2409 case glslang::EOpConstructUMat3x2:
2410 case glslang::EOpConstructUMat3x3:
2411 case glslang::EOpConstructUMat3x4:
2412 case glslang::EOpConstructUMat4x2:
2413 case glslang::EOpConstructUMat4x3:
2414 case glslang::EOpConstructUMat4x4:
2415 case glslang::EOpConstructBMat2x2:
2416 case glslang::EOpConstructBMat2x3:
2417 case glslang::EOpConstructBMat2x4:
2418 case glslang::EOpConstructBMat3x2:
2419 case glslang::EOpConstructBMat3x3:
2420 case glslang::EOpConstructBMat3x4:
2421 case glslang::EOpConstructBMat4x2:
2422 case glslang::EOpConstructBMat4x3:
2423 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002424 case glslang::EOpConstructF16Mat2x2:
2425 case glslang::EOpConstructF16Mat2x3:
2426 case glslang::EOpConstructF16Mat2x4:
2427 case glslang::EOpConstructF16Mat3x2:
2428 case glslang::EOpConstructF16Mat3x3:
2429 case glslang::EOpConstructF16Mat3x4:
2430 case glslang::EOpConstructF16Mat4x2:
2431 case glslang::EOpConstructF16Mat4x3:
2432 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002433 isMatrix = true;
2434 // fall through
2435 case glslang::EOpConstructFloat:
2436 case glslang::EOpConstructVec2:
2437 case glslang::EOpConstructVec3:
2438 case glslang::EOpConstructVec4:
2439 case glslang::EOpConstructDouble:
2440 case glslang::EOpConstructDVec2:
2441 case glslang::EOpConstructDVec3:
2442 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002443 case glslang::EOpConstructFloat16:
2444 case glslang::EOpConstructF16Vec2:
2445 case glslang::EOpConstructF16Vec3:
2446 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002447 case glslang::EOpConstructBool:
2448 case glslang::EOpConstructBVec2:
2449 case glslang::EOpConstructBVec3:
2450 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002451 case glslang::EOpConstructInt8:
2452 case glslang::EOpConstructI8Vec2:
2453 case glslang::EOpConstructI8Vec3:
2454 case glslang::EOpConstructI8Vec4:
2455 case glslang::EOpConstructUint8:
2456 case glslang::EOpConstructU8Vec2:
2457 case glslang::EOpConstructU8Vec3:
2458 case glslang::EOpConstructU8Vec4:
2459 case glslang::EOpConstructInt16:
2460 case glslang::EOpConstructI16Vec2:
2461 case glslang::EOpConstructI16Vec3:
2462 case glslang::EOpConstructI16Vec4:
2463 case glslang::EOpConstructUint16:
2464 case glslang::EOpConstructU16Vec2:
2465 case glslang::EOpConstructU16Vec3:
2466 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002467 case glslang::EOpConstructInt:
2468 case glslang::EOpConstructIVec2:
2469 case glslang::EOpConstructIVec3:
2470 case glslang::EOpConstructIVec4:
2471 case glslang::EOpConstructUint:
2472 case glslang::EOpConstructUVec2:
2473 case glslang::EOpConstructUVec3:
2474 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002475 case glslang::EOpConstructInt64:
2476 case glslang::EOpConstructI64Vec2:
2477 case glslang::EOpConstructI64Vec3:
2478 case glslang::EOpConstructI64Vec4:
2479 case glslang::EOpConstructUint64:
2480 case glslang::EOpConstructU64Vec2:
2481 case glslang::EOpConstructU64Vec3:
2482 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002483 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002484 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002485 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002486 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002487 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002488 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002489 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002490 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002491 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002492 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002493 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002494 else if (node->getOp() == glslang::EOpConstructStruct ||
2495 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2496 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002497 std::vector<spv::Id> constituents;
2498 for (int c = 0; c < (int)arguments.size(); ++c)
2499 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002500 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002501 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002502 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002503 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002504 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002505
2506 builder.clearAccessChain();
2507 builder.setAccessChainRValue(constructed);
2508
2509 return false;
2510 }
2511
2512 // These six are component-wise compares with component-wise results.
2513 // Forward on to createBinaryOperation(), requesting a vector result.
2514 case glslang::EOpLessThan:
2515 case glslang::EOpGreaterThan:
2516 case glslang::EOpLessThanEqual:
2517 case glslang::EOpGreaterThanEqual:
2518 case glslang::EOpVectorEqual:
2519 case glslang::EOpVectorNotEqual:
2520 {
2521 // Map the operation to a binary
2522 binOp = node->getOp();
2523 reduceComparison = false;
2524 switch (node->getOp()) {
2525 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2526 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2527 default: binOp = node->getOp(); break;
2528 }
2529
2530 break;
2531 }
2532 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002533 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002534 binOp = glslang::EOpMul;
2535 break;
2536 case glslang::EOpOuterProduct:
2537 // two vectors multiplied to make a matrix
2538 binOp = glslang::EOpOuterProduct;
2539 break;
2540 case glslang::EOpDot:
2541 {
qining25262b32016-05-06 17:25:16 -04002542 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002543 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002544 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002545 binOp = glslang::EOpMul;
2546 break;
2547 }
2548 case glslang::EOpMod:
2549 // when an aggregate, this is the floating-point mod built-in function,
2550 // which can be emitted by the one in createBinaryOperation()
2551 binOp = glslang::EOpMod;
2552 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002553
2554#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002555 case glslang::EOpEmitVertex:
2556 case glslang::EOpEndPrimitive:
2557 case glslang::EOpBarrier:
2558 case glslang::EOpMemoryBarrier:
2559 case glslang::EOpMemoryBarrierAtomicCounter:
2560 case glslang::EOpMemoryBarrierBuffer:
2561 case glslang::EOpMemoryBarrierImage:
2562 case glslang::EOpMemoryBarrierShared:
2563 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002564 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002565 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002566 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002567 case glslang::EOpWorkgroupMemoryBarrier:
2568 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002569 case glslang::EOpSubgroupBarrier:
2570 case glslang::EOpSubgroupMemoryBarrier:
2571 case glslang::EOpSubgroupMemoryBarrierBuffer:
2572 case glslang::EOpSubgroupMemoryBarrierImage:
2573 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002574 noReturnValue = true;
2575 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2576 break;
2577
Jeff Bolz36831c92018-09-05 10:11:41 -05002578 case glslang::EOpAtomicStore:
2579 noReturnValue = true;
2580 // fallthrough
2581 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002582 case glslang::EOpAtomicAdd:
2583 case glslang::EOpAtomicMin:
2584 case glslang::EOpAtomicMax:
2585 case glslang::EOpAtomicAnd:
2586 case glslang::EOpAtomicOr:
2587 case glslang::EOpAtomicXor:
2588 case glslang::EOpAtomicExchange:
2589 case glslang::EOpAtomicCompSwap:
2590 atomic = true;
2591 break;
2592
John Kessenich0d0c6d32017-07-23 16:08:26 -06002593 case glslang::EOpAtomicCounterAdd:
2594 case glslang::EOpAtomicCounterSubtract:
2595 case glslang::EOpAtomicCounterMin:
2596 case glslang::EOpAtomicCounterMax:
2597 case glslang::EOpAtomicCounterAnd:
2598 case glslang::EOpAtomicCounterOr:
2599 case glslang::EOpAtomicCounterXor:
2600 case glslang::EOpAtomicCounterExchange:
2601 case glslang::EOpAtomicCounterCompSwap:
2602 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2603 builder.addCapability(spv::CapabilityAtomicStorageOps);
2604 atomic = true;
2605 break;
2606
Chao Chenb50c02e2018-09-19 11:42:24 -07002607 case glslang::EOpIgnoreIntersectionNV:
2608 case glslang::EOpTerminateRayNV:
2609 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002610 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002611 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2612 noReturnValue = true;
2613 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002614 case glslang::EOpCooperativeMatrixLoad:
2615 case glslang::EOpCooperativeMatrixStore:
2616 noReturnValue = true;
2617 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002618 case glslang::EOpBeginInvocationInterlock:
2619 case glslang::EOpEndInvocationInterlock:
2620 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2621 noReturnValue = true;
2622 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002623#endif
Chao Chen3c366992018-09-19 11:41:59 -07002624
John Kessenich140f3df2015-06-26 16:58:36 -06002625 default:
2626 break;
2627 }
2628
2629 //
2630 // See if it maps to a regular operation.
2631 //
John Kessenich140f3df2015-06-26 16:58:36 -06002632 if (binOp != glslang::EOpNull) {
2633 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2634 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2635 assert(left && right);
2636
2637 builder.clearAccessChain();
2638 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002639 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002640
2641 builder.clearAccessChain();
2642 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002643 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002644
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002645 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002646 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002647 TranslateNoContractionDecoration(node->getType().getQualifier()),
2648 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002649 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002650 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002651 left->getType().getBasicType(), reduceComparison);
2652
2653 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002654 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002655 builder.clearAccessChain();
2656 builder.setAccessChainRValue(result);
2657
2658 return false;
2659 }
2660
John Kessenich426394d2015-07-23 10:22:48 -06002661 //
2662 // Create the list of operands.
2663 //
John Kessenich140f3df2015-06-26 16:58:36 -06002664 glslang::TIntermSequence& glslangOperands = node->getSequence();
2665 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002666 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002667 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002668 // special case l-value operands; there are just a few
2669 bool lvalue = false;
2670 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002671 case glslang::EOpModf:
2672 if (arg == 1)
2673 lvalue = true;
2674 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002675#ifndef GLSLANG_WEB
2676 case glslang::EOpFrexp:
2677 if (arg == 1)
2678 lvalue = true;
2679 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002680 case glslang::EOpInterpolateAtSample:
2681 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002682 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002683 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002684 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002685
2686 // Does it need a swizzle inversion? If so, evaluation is inverted;
2687 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002688 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002689 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2690 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2691 }
Rex Xu7a26c172015-12-08 17:12:09 +08002692 break;
Rex Xud4782c12015-09-06 16:30:11 +08002693 case glslang::EOpAtomicAdd:
2694 case glslang::EOpAtomicMin:
2695 case glslang::EOpAtomicMax:
2696 case glslang::EOpAtomicAnd:
2697 case glslang::EOpAtomicOr:
2698 case glslang::EOpAtomicXor:
2699 case glslang::EOpAtomicExchange:
2700 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002701 case glslang::EOpAtomicLoad:
2702 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002703 case glslang::EOpAtomicCounterAdd:
2704 case glslang::EOpAtomicCounterSubtract:
2705 case glslang::EOpAtomicCounterMin:
2706 case glslang::EOpAtomicCounterMax:
2707 case glslang::EOpAtomicCounterAnd:
2708 case glslang::EOpAtomicCounterOr:
2709 case glslang::EOpAtomicCounterXor:
2710 case glslang::EOpAtomicCounterExchange:
2711 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002712 if (arg == 0)
2713 lvalue = true;
2714 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002715 case glslang::EOpAddCarry:
2716 case glslang::EOpSubBorrow:
2717 if (arg == 2)
2718 lvalue = true;
2719 break;
2720 case glslang::EOpUMulExtended:
2721 case glslang::EOpIMulExtended:
2722 if (arg >= 2)
2723 lvalue = true;
2724 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002725 case glslang::EOpCooperativeMatrixLoad:
2726 if (arg == 0 || arg == 1)
2727 lvalue = true;
2728 break;
2729 case glslang::EOpCooperativeMatrixStore:
2730 if (arg == 1)
2731 lvalue = true;
2732 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002733#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002734 default:
2735 break;
2736 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002737 builder.clearAccessChain();
2738 if (invertedType != spv::NoType && arg == 0)
2739 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2740 else
2741 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002742
John Kessenichb9197c82019-08-11 07:41:45 -06002743#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002744 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2745 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2746
2747 if (arg == 1) {
2748 // fold "element" parameter into the access chain
2749 spv::Builder::AccessChain save = builder.getAccessChain();
2750 builder.clearAccessChain();
2751 glslangOperands[2]->traverse(this);
2752
2753 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2754
2755 builder.setAccessChain(save);
2756
2757 // Point to the first element of the array.
2758 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002759 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002760
2761 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2762 unsigned int alignment = builder.getAccessChain().alignment;
2763
2764 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2765 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2766 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2767 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2768 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2769 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2770 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2771 }
2772
2773 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2774
2775 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2776 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2777 }
2778
2779 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2780 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2781 }
2782 } else if (arg == 2) {
2783 continue;
2784 }
2785 }
John Kessenichb9197c82019-08-11 07:41:45 -06002786#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002787
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002788 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002789 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002790 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2791 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2792 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002793 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002794 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002795 }
John Kessenich140f3df2015-06-26 16:58:36 -06002796 }
John Kessenich426394d2015-07-23 10:22:48 -06002797
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002798 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002799#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002800 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2801 std::vector<spv::IdImmediate> idImmOps;
2802
2803 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2804 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2805 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2806 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2807 // get the pointee type
2808 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2809 assert(builder.isCooperativeMatrixType(typeId));
2810 // do the op
2811 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2812 // store the result to the pointer (out param 'm')
2813 builder.createStore(result, operands[0]);
2814 result = 0;
2815 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2816 std::vector<spv::IdImmediate> idImmOps;
2817
2818 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2819 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2820 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2821 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2822 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2823
2824 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2825 result = 0;
2826 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002827 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002828 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenichb9197c82019-08-11 07:41:45 -06002829 } else
2830#endif
2831 {
John Kessenich426394d2015-07-23 10:22:48 -06002832 // Pass through to generic operations.
2833 switch (glslangOperands.size()) {
2834 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002835 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002836 break;
2837 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002838 {
2839 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002840 TranslateNoContractionDecoration(node->getType().getQualifier()),
2841 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002842 result = createUnaryOperation(
2843 node->getOp(), decorations,
2844 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002845 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002846 }
John Kessenich426394d2015-07-23 10:22:48 -06002847 break;
2848 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002849 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002850 break;
2851 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002852 if (invertedType)
2853 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002854 }
2855
2856 if (noReturnValue)
2857 return false;
2858
2859 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002860 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002861 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002862 } else {
2863 builder.clearAccessChain();
2864 builder.setAccessChainRValue(result);
2865 return false;
2866 }
2867}
2868
John Kessenich433e9ff2017-01-26 20:31:11 -07002869// This path handles both if-then-else and ?:
2870// The if-then-else has a node type of void, while
2871// ?: has either a void or a non-void node type
2872//
2873// Leaving the result, when not void:
2874// GLSL only has r-values as the result of a :?, but
2875// if we have an l-value, that can be more efficient if it will
2876// become the base of a complex r-value expression, because the
2877// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002878bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2879{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002880 // see if OpSelect can handle it
2881 const auto isOpSelectable = [&]() {
2882 if (node->getBasicType() == glslang::EbtVoid)
2883 return false;
2884 // OpSelect can do all other types starting with SPV 1.4
2885 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2886 // pre-1.4, only scalars and vectors can be handled
2887 if ((!node->getType().isScalar() && !node->getType().isVector()))
2888 return false;
2889 }
2890 return true;
2891 };
2892
John Kessenich4bee5312018-02-20 21:29:05 -07002893 // See if it simple and safe, or required, to execute both sides.
2894 // Crucially, side effects must be either semantically required or avoided,
2895 // and there are performance trade-offs.
2896 // Return true if required or a good idea (and safe) to execute both sides,
2897 // false otherwise.
2898 const auto bothSidesPolicy = [&]() -> bool {
2899 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002900 if (node->getTrueBlock() == nullptr ||
2901 node->getFalseBlock() == nullptr)
2902 return false;
2903
John Kessenich4bee5312018-02-20 21:29:05 -07002904 // required? (unless we write additional code to look for side effects
2905 // and make performance trade-offs if none are present)
2906 if (!node->getShortCircuit())
2907 return true;
2908
2909 // if not required to execute both, decide based on performance/practicality...
2910
John Kessenich0c1e71a2019-01-10 18:23:06 +07002911 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002912 return false;
2913
John Kessenich433e9ff2017-01-26 20:31:11 -07002914 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2915 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2916
2917 // return true if a single operand to ? : is okay for OpSelect
2918 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002919 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002920 };
2921
2922 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2923 operandOkay(node->getFalseBlock()->getAsTyped());
2924 };
2925
John Kessenich4bee5312018-02-20 21:29:05 -07002926 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2927 // emit the condition before doing anything with selection
2928 node->getCondition()->traverse(this);
2929 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2930
2931 // Find a way of executing both sides and selecting the right result.
2932 const auto executeBothSides = [&]() -> void {
2933 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002934 node->getTrueBlock()->traverse(this);
2935 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2936 node->getFalseBlock()->traverse(this);
2937 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2938
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002939 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002940
John Kessenich4bee5312018-02-20 21:29:05 -07002941 // done if void
2942 if (node->getBasicType() == glslang::EbtVoid)
2943 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002944
John Kessenich4bee5312018-02-20 21:29:05 -07002945 // emit code to select between trueValue and falseValue
2946
2947 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002948 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002949 // Emit OpSelect for this selection.
2950
2951 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002952 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2953 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002954 condition = builder.smearScalar(spv::NoPrecision, condition,
2955 builder.makeVectorType(builder.makeBoolType(),
2956 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002957 }
John Kessenich4bee5312018-02-20 21:29:05 -07002958
2959 // OpSelect
2960 result = builder.createTriOp(spv::OpSelect,
2961 convertGlslangToSpvType(node->getType()), condition,
2962 trueValue, falseValue);
2963
2964 builder.clearAccessChain();
2965 builder.setAccessChainRValue(result);
2966 } else {
2967 // We need control flow to select the result.
2968 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2969 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2970
2971 // Selection control:
2972 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2973
2974 // make an "if" based on the value created by the condition
2975 spv::Builder::If ifBuilder(condition, control, builder);
2976
2977 // emit the "then" statement
2978 builder.createStore(trueValue, result);
2979 ifBuilder.makeBeginElse();
2980 // emit the "else" statement
2981 builder.createStore(falseValue, result);
2982
2983 // finish off the control flow
2984 ifBuilder.makeEndIf();
2985
2986 builder.clearAccessChain();
2987 builder.setAccessChainLValue(result);
2988 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002989 };
2990
John Kessenich4bee5312018-02-20 21:29:05 -07002991 // Execute the one side needed, as per the condition
2992 const auto executeOneSide = [&]() {
2993 // Always emit control flow.
2994 if (node->getBasicType() != glslang::EbtVoid)
2995 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002996
John Kessenich4bee5312018-02-20 21:29:05 -07002997 // Selection control:
2998 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2999
3000 // make an "if" based on the value created by the condition
3001 spv::Builder::If ifBuilder(condition, control, builder);
3002
3003 // emit the "then" statement
3004 if (node->getTrueBlock() != nullptr) {
3005 node->getTrueBlock()->traverse(this);
3006 if (result != spv::NoResult)
3007 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3008 }
3009
3010 if (node->getFalseBlock() != nullptr) {
3011 ifBuilder.makeBeginElse();
3012 // emit the "else" statement
3013 node->getFalseBlock()->traverse(this);
3014 if (result != spv::NoResult)
3015 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3016 }
3017
3018 // finish off the control flow
3019 ifBuilder.makeEndIf();
3020
3021 if (result != spv::NoResult) {
3022 builder.clearAccessChain();
3023 builder.setAccessChainLValue(result);
3024 }
3025 };
3026
3027 // Try for OpSelect (or a requirement to execute both sides)
3028 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003029 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3030 if (node->getType().getQualifier().isSpecConstant())
3031 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003032 executeBothSides();
3033 } else
3034 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003035
3036 return false;
3037}
3038
3039bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3040{
3041 // emit and get the condition before doing anything with switch
3042 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003043 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003044
Rex Xu57e65922017-07-04 23:23:40 +08003045 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003046 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003047
John Kessenich140f3df2015-06-26 16:58:36 -06003048 // browse the children to sort out code segments
3049 int defaultSegment = -1;
3050 std::vector<TIntermNode*> codeSegments;
3051 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3052 std::vector<int> caseValues;
3053 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3054 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3055 TIntermNode* child = *c;
3056 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003057 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003058 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003059 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003060 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3061 } else
3062 codeSegments.push_back(child);
3063 }
3064
qining25262b32016-05-06 17:25:16 -04003065 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003066 // statements between the last case and the end of the switch statement
3067 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3068 (int)codeSegments.size() == defaultSegment)
3069 codeSegments.push_back(nullptr);
3070
3071 // make the switch statement
3072 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003073 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003074
3075 // emit all the code in the segments
3076 breakForLoop.push(false);
3077 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3078 builder.nextSwitchSegment(segmentBlocks, s);
3079 if (codeSegments[s])
3080 codeSegments[s]->traverse(this);
3081 else
3082 builder.addSwitchBreak();
3083 }
3084 breakForLoop.pop();
3085
3086 builder.endSwitch(segmentBlocks);
3087
3088 return false;
3089}
3090
3091void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3092{
3093 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003094 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003095
3096 builder.clearAccessChain();
3097 builder.setAccessChainRValue(constant);
3098}
3099
3100bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3101{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003102 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003103 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003104
3105 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003106 std::vector<unsigned int> operands;
3107 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003108
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003109 // Spec requires back edges to target header blocks, and every header block
3110 // must dominate its merge block. Make a header block first to ensure these
3111 // conditions are met. By definition, it will contain OpLoopMerge, followed
3112 // by a block-ending branch. But we don't want to put any other body/test
3113 // instructions in it, since the body/test may have arbitrary instructions,
3114 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003115 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003116 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003117 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003118 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003119 spv::Block& test = builder.makeNewBlock();
3120 builder.createBranch(&test);
3121
3122 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003123 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003124 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003125 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3126
3127 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003128 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003129 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003130 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003131 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003132 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003133
3134 builder.setBuildPoint(&blocks.continue_target);
3135 if (node->getTerminal())
3136 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003137 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003138 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003139 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003140 builder.createBranch(&blocks.body);
3141
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003142 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003143 builder.setBuildPoint(&blocks.body);
3144 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003145 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003146 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003147 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003148
3149 builder.setBuildPoint(&blocks.continue_target);
3150 if (node->getTerminal())
3151 node->getTerminal()->traverse(this);
3152 if (node->getTest()) {
3153 node->getTest()->traverse(this);
3154 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003155 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003156 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003157 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003158 // TODO: unless there was a break/return/discard instruction
3159 // somewhere in the body, this is an infinite loop, so we should
3160 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003161 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003162 }
John Kessenich140f3df2015-06-26 16:58:36 -06003163 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003164 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003165 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003166 return false;
3167}
3168
3169bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3170{
3171 if (node->getExpression())
3172 node->getExpression()->traverse(this);
3173
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003174 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003175
John Kessenich140f3df2015-06-26 16:58:36 -06003176 switch (node->getFlowOp()) {
3177 case glslang::EOpKill:
3178 builder.makeDiscard();
3179 break;
3180 case glslang::EOpBreak:
3181 if (breakForLoop.top())
3182 builder.createLoopExit();
3183 else
3184 builder.addSwitchBreak();
3185 break;
3186 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003187 builder.createLoopContinue();
3188 break;
3189 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003190 if (node->getExpression()) {
3191 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3192 spv::Id returnId = accessChainLoad(glslangReturnType);
3193 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3194 builder.clearAccessChain();
3195 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3196 builder.setAccessChainLValue(copyId);
3197 multiTypeStore(glslangReturnType, returnId);
3198 returnId = builder.createLoad(copyId);
3199 }
3200 builder.makeReturn(false, returnId);
3201 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003202 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003203
3204 builder.clearAccessChain();
3205 break;
3206
John Kessenichb9197c82019-08-11 07:41:45 -06003207#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003208 case glslang::EOpDemote:
3209 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3210 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3211 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3212 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003213#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003214
John Kessenich140f3df2015-06-26 16:58:36 -06003215 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003217 break;
3218 }
3219
3220 return false;
3221}
3222
John Kessenich9c14f772019-06-17 08:38:35 -06003223spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003224{
qining25262b32016-05-06 17:25:16 -04003225 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003226 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003227 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003228 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003229 spv::Id result = createSpvConstant(*node);
3230 if (result != spv::NoResult)
3231 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 }
3233
3234 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003235 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003236 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3237 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003238
John Kessenichb9197c82019-08-11 07:41:45 -06003239 const bool contains16BitType = node->getType().contains16BitFloat() ||
3240 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003241 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003242 switch (storageClass) {
3243 case spv::StorageClassInput:
3244 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003245 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003246 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003247 break;
John Kessenich18310872018-05-14 22:08:53 -06003248 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003249 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003250 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3251 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003252 else
3253 builder.addCapability(spv::CapabilityStorageUniform16);
3254 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003255#ifndef GLSLANG_WEB
3256 case spv::StorageClassPushConstant:
3257 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3258 builder.addCapability(spv::CapabilityStoragePushConstant16);
3259 break;
John Kessenich18310872018-05-14 22:08:53 -06003260 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003261 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003262 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3263 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3264 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003265#endif
John Kessenich18310872018-05-14 22:08:53 -06003266 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003267 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003268 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003269 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003270 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003271 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003272 }
3273 }
Rex Xuf89ad982017-04-07 23:22:33 +08003274
John Kessenichb9197c82019-08-11 07:41:45 -06003275 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003276 if (storageClass == spv::StorageClassPushConstant) {
3277 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3278 builder.addCapability(spv::CapabilityStoragePushConstant8);
3279 } else if (storageClass == spv::StorageClassUniform) {
3280 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3281 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003282 } else if (storageClass == spv::StorageClassStorageBuffer) {
3283 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3284 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003285 } else {
3286 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003287 }
3288 }
3289
John Kessenich140f3df2015-06-26 16:58:36 -06003290 const char* name = node->getName().c_str();
3291 if (glslang::IsAnonymous(name))
3292 name = "";
3293
3294 return builder.createVariable(storageClass, spvType, name);
3295}
3296
3297// Return type Id of the sampled type.
3298spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3299{
3300 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003301 case glslang::EbtInt: return builder.makeIntType(32);
3302 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003303 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003304#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003305 case glslang::EbtFloat16:
3306 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3307 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3308 return builder.makeFloatType(16);
3309#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003310 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003311 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003312 return builder.makeFloatType(32);
3313 }
3314}
3315
John Kessenich8c8505c2016-07-26 12:50:38 -06003316// If node is a swizzle operation, return the type that should be used if
3317// the swizzle base is first consumed by another operation, before the swizzle
3318// is applied.
3319spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3320{
John Kessenichecba76f2017-01-06 00:34:48 -07003321 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003322 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3323 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3324 else
3325 return spv::NoType;
3326}
3327
3328// When inverting a swizzle with a parent op, this function
3329// will apply the swizzle operation to a completed parent operation.
3330spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3331{
3332 std::vector<unsigned> swizzle;
3333 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3334 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3335}
3336
John Kessenich8c8505c2016-07-26 12:50:38 -06003337// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3338void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3339{
3340 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3341 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3342 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3343}
3344
John Kessenich3ac051e2015-12-20 11:29:16 -07003345// Convert from a glslang type to an SPV type, by calling into a
3346// recursive version of this function. This establishes the inherited
3347// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003348spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003349{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003350 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003351}
3352
3353// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003354// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003355// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003356spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003357 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3358 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003359{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003360 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003361
3362 switch (type.getBasicType()) {
3363 case glslang::EbtVoid:
3364 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003365 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003366 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003367 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003368 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3369 // a 32-bit int where non-0 means true.
3370 if (explicitLayout != glslang::ElpNone)
3371 spvType = builder.makeUintType(32);
3372 else
3373 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003374 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003375 case glslang::EbtInt:
3376 spvType = builder.makeIntType(32);
3377 break;
3378 case glslang::EbtUint:
3379 spvType = builder.makeUintType(32);
3380 break;
3381 case glslang::EbtFloat:
3382 spvType = builder.makeFloatType(32);
3383 break;
3384#ifndef GLSLANG_WEB
3385 case glslang::EbtDouble:
3386 spvType = builder.makeFloatType(64);
3387 break;
3388 case glslang::EbtFloat16:
3389 spvType = builder.makeFloatType(16);
3390 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003391 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003392 spvType = builder.makeIntType(8);
3393 break;
3394 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003395 spvType = builder.makeUintType(8);
3396 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003397 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003398 spvType = builder.makeIntType(16);
3399 break;
3400 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003401 spvType = builder.makeUintType(16);
3402 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003403 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003404 spvType = builder.makeIntType(64);
3405 break;
3406 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003407 spvType = builder.makeUintType(64);
3408 break;
John Kessenich426394d2015-07-23 10:22:48 -06003409 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003410 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003411 spvType = builder.makeUintType(32);
3412 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003413 case glslang::EbtAccStructNV:
3414 spvType = builder.makeAccelerationStructureNVType();
3415 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003416 case glslang::EbtReference:
3417 {
3418 // Make the forward pointer, then recurse to convert the structure type, then
3419 // patch up the forward pointer with a real pointer type.
3420 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3421 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3422 forwardPointers[type.getReferentType()] = forwardId;
3423 }
3424 spvType = forwardPointers[type.getReferentType()];
3425 if (!forwardReferenceOnly) {
3426 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3427 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3428 forwardPointers[type.getReferentType()],
3429 referentType);
3430 }
3431 }
3432 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003433#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003434 case glslang::EbtSampler:
3435 {
3436 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003437 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003438 spvType = builder.makeSamplerType();
3439 } else {
3440 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003441 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3442 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3443 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3444 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003445 // already has both image and sampler, make the combined type
3446 spvType = builder.makeSampledImageType(spvType);
3447 }
John Kessenich55e7d112015-11-15 21:33:39 -07003448 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003449 }
John Kessenich140f3df2015-06-26 16:58:36 -06003450 break;
3451 case glslang::EbtStruct:
3452 case glslang::EbtBlock:
3453 {
3454 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003455 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003456
3457 // Try to share structs for different layouts, but not yet for other
3458 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003459 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003460 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003461 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003462 break;
3463
3464 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003465 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003466 memberRemapper[glslangMembers].resize(glslangMembers->size());
3467 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003468 }
3469 break;
3470 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003471 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003472 break;
3473 }
3474
3475 if (type.isMatrix())
3476 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3477 else {
3478 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3479 if (type.getVectorSize() > 1)
3480 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3481 }
3482
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003483 if (type.isCoopMat()) {
3484 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3485 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3486 if (type.getBasicType() == glslang::EbtFloat16)
3487 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003488 if (type.getBasicType() == glslang::EbtUint8 ||
3489 type.getBasicType() == glslang::EbtInt8) {
3490 builder.addCapability(spv::CapabilityInt8);
3491 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003492
3493 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3494 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3495 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3496
3497 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3498 }
3499
John Kessenich140f3df2015-06-26 16:58:36 -06003500 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003501 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3502
John Kessenichc9a80832015-09-12 12:17:44 -06003503 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003504 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003505 // We need to decorate array strides for types needing explicit layout, except blocks.
3506 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003507 // Use a dummy glslang type for querying internal strides of
3508 // arrays of arrays, but using just a one-dimensional array.
3509 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003510 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3511 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003512
3513 // Will compute the higher-order strides here, rather than making a whole
3514 // pile of types and doing repetitive recursion on their contents.
3515 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3516 }
John Kessenichf8842e52016-01-04 19:22:56 -07003517
3518 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003519 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003520 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003521 if (stride > 0)
3522 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003523 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003524 }
3525 } else {
3526 // single-dimensional array, and don't yet have stride
3527
John Kessenichf8842e52016-01-04 19:22:56 -07003528 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003529 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3530 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003531 }
John Kessenich31ed4832015-09-09 17:51:38 -06003532
John Kessenichead86222018-03-28 18:01:20 -06003533 // Do the outer dimension, which might not be known for a runtime-sized array.
3534 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3535 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003536 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003537 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003538#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003539 if (!lastBufferBlockMember) {
3540 builder.addExtension("SPV_EXT_descriptor_indexing");
3541 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3542 }
John Kessenichead86222018-03-28 18:01:20 -06003543 spvType = builder.makeRuntimeArray(spvType);
John Kessenichb9197c82019-08-11 07:41:45 -06003544#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06003545 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003546 if (stride > 0)
3547 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 }
3549
3550 return spvType;
3551}
3552
John Kessenich0e737842017-03-24 18:38:16 -06003553// TODO: this functionality should exist at a higher level, in creating the AST
3554//
3555// Identify interface members that don't have their required extension turned on.
3556//
3557bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3558{
John Kessenicha28f7a72019-08-06 07:00:58 -06003559#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003560 auto& extensions = glslangIntermediate->getRequestedExtensions();
3561
Rex Xubcf291a2017-03-29 23:01:36 +08003562 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3563 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3564 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003565 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3566 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3567 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003568
3569 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3570 if (member.getFieldName() == "gl_ViewportMask" &&
3571 extensions.find("GL_NV_viewport_array2") == extensions.end())
3572 return true;
3573 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3574 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3575 return true;
3576 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3577 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3578 return true;
3579 }
3580#endif
John Kessenich0e737842017-03-24 18:38:16 -06003581
3582 return false;
3583};
3584
John Kessenich6090df02016-06-30 21:18:02 -06003585// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3586// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3587// Mutually recursive with convertGlslangToSpvType().
3588spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3589 const glslang::TTypeList* glslangMembers,
3590 glslang::TLayoutPacking explicitLayout,
3591 const glslang::TQualifier& qualifier)
3592{
3593 // Create a vector of struct types for SPIR-V to consume
3594 std::vector<spv::Id> spvMembers;
3595 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 -06003596 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003597 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3598 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3599 if (glslangMember.hiddenMember()) {
3600 ++memberDelta;
3601 if (type.getBasicType() == glslang::EbtBlock)
3602 memberRemapper[glslangMembers][i] = -1;
3603 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003604 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003605 if (filterMember(glslangMember)) {
3606 memberDelta++;
3607 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003608 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003609 }
3610 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003611 }
John Kessenich6090df02016-06-30 21:18:02 -06003612 // modify just this child's view of the qualifier
3613 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3614 InheritQualifiers(memberQualifier, qualifier);
3615
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003616 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003617 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003618 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003619
3620 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003621 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3622 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003623
3624 // Make forward pointers for any pointer members, and create a list of members to
3625 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003626 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003627 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3628 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3629 }
3630 spvMembers.push_back(
3631 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3632 } else {
3633 spvMembers.push_back(
3634 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3635 }
John Kessenich6090df02016-06-30 21:18:02 -06003636 }
3637 }
3638
3639 // Make the SPIR-V type
3640 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003641 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003642 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3643
3644 // Decorate it
3645 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3646
John Kessenichd72f4882019-01-16 14:55:37 +07003647 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003648 auto it = deferredForwardPointers[i];
3649 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3650 }
3651
John Kessenich6090df02016-06-30 21:18:02 -06003652 return spvType;
3653}
3654
3655void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3656 const glslang::TTypeList* glslangMembers,
3657 glslang::TLayoutPacking explicitLayout,
3658 const glslang::TQualifier& qualifier,
3659 spv::Id spvType)
3660{
3661 // Name and decorate the non-hidden members
3662 int offset = -1;
3663 int locationOffset = 0; // for use within the members of this struct
3664 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3665 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3666 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003667 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003668 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003669 if (filterMember(glslangMember))
3670 continue;
3671 }
John Kessenich6090df02016-06-30 21:18:02 -06003672
3673 // modify just this child's view of the qualifier
3674 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3675 InheritQualifiers(memberQualifier, qualifier);
3676
3677 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003678 if (member < 0)
3679 continue;
3680
3681 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3682 builder.addMemberDecoration(spvType, member,
3683 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3684 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3685 // Add interpolation and auxiliary storage decorations only to
3686 // top-level members of Input and Output storage classes
3687 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3688 type.getQualifier().storage == glslang::EvqVaryingOut) {
3689 if (type.getBasicType() == glslang::EbtBlock ||
3690 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3691 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3692 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003693#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003694 addMeshNVDecoration(spvType, member, memberQualifier);
3695#endif
John Kessenich6090df02016-06-30 21:18:02 -06003696 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003697 }
3698 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003699
John Kessenichb9197c82019-08-11 07:41:45 -06003700#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003701 if (type.getBasicType() == glslang::EbtBlock &&
3702 qualifier.storage == glslang::EvqBuffer) {
3703 // Add memory decorations only to top-level members of shader storage block
3704 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003705 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003706 for (unsigned int i = 0; i < memory.size(); ++i)
3707 builder.addMemberDecoration(spvType, member, memory[i]);
3708 }
John Kessenichb9197c82019-08-11 07:41:45 -06003709#endif
John Kessenich6090df02016-06-30 21:18:02 -06003710
John Kessenich5d610ee2018-03-07 18:05:55 -07003711 // Location assignment was already completed correctly by the front end,
3712 // just track whether a member needs to be decorated.
3713 // Ignore member locations if the container is an array, as that's
3714 // ill-specified and decisions have been made to not allow this.
3715 if (! type.isArray() && memberQualifier.hasLocation())
3716 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003717
John Kessenich5d610ee2018-03-07 18:05:55 -07003718 if (qualifier.hasLocation()) // track for upcoming inheritance
3719 locationOffset += glslangIntermediate->computeTypeLocationSize(
3720 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003721
John Kessenich5d610ee2018-03-07 18:05:55 -07003722 // component, XFB, others
3723 if (glslangMember.getQualifier().hasComponent())
3724 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3725 glslangMember.getQualifier().layoutComponent);
3726 if (glslangMember.getQualifier().hasXfbOffset())
3727 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3728 glslangMember.getQualifier().layoutXfbOffset);
3729 else if (explicitLayout != glslang::ElpNone) {
3730 // figure out what to do with offset, which is accumulating
3731 int nextOffset;
3732 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3733 if (offset >= 0)
3734 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3735 offset = nextOffset;
3736 }
John Kessenich6090df02016-06-30 21:18:02 -06003737
John Kessenich5d610ee2018-03-07 18:05:55 -07003738 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3739 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3740 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003741
John Kessenich5d610ee2018-03-07 18:05:55 -07003742 // built-in variable decorations
3743 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3744 if (builtIn != spv::BuiltInMax)
3745 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003746
John Kessenichb9197c82019-08-11 07:41:45 -06003747#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003748 // nonuniform
3749 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3750
John Kessenichead86222018-03-28 18:01:20 -06003751 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3752 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3753 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3754 memberQualifier.semanticName);
3755 }
3756
John Kessenich5d610ee2018-03-07 18:05:55 -07003757 if (builtIn == spv::BuiltInLayer) {
3758 // SPV_NV_viewport_array2 extension
3759 if (glslangMember.getQualifier().layoutViewportRelative){
3760 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3761 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3762 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003763 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003764 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3765 builder.addMemberDecoration(spvType, member,
3766 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3767 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3768 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3769 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003770 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003771 }
3772 if (glslangMember.getQualifier().layoutPassthrough) {
3773 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3774 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3775 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3776 }
chaoc771d89f2017-01-13 01:10:53 -08003777#endif
John Kessenich6090df02016-06-30 21:18:02 -06003778 }
3779
3780 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003781 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3782 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003783}
3784
John Kessenich6c292d32016-02-15 20:58:50 -07003785// Turn the expression forming the array size into an id.
3786// This is not quite trivial, because of specialization constants.
3787// Sometimes, a raw constant is turned into an Id, and sometimes
3788// a specialization constant expression is.
3789spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3790{
3791 // First, see if this is sized with a node, meaning a specialization constant:
3792 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3793 if (specNode != nullptr) {
3794 builder.clearAccessChain();
3795 specNode->traverse(this);
3796 return accessChainLoad(specNode->getAsTyped()->getType());
3797 }
qining25262b32016-05-06 17:25:16 -04003798
John Kessenich6c292d32016-02-15 20:58:50 -07003799 // Otherwise, need a compile-time (front end) size, get it:
3800 int size = arraySizes.getDimSize(dim);
3801 assert(size > 0);
3802 return builder.makeUintConstant(size);
3803}
3804
John Kessenich103bef92016-02-08 21:38:15 -07003805// Wrap the builder's accessChainLoad to:
3806// - localize handling of RelaxedPrecision
3807// - use the SPIR-V inferred type instead of another conversion of the glslang type
3808// (avoids unnecessary work and possible type punning for structures)
3809// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003810spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3811{
John Kessenich103bef92016-02-08 21:38:15 -07003812 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003813
3814 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3815 coherentFlags |= TranslateCoherent(type);
3816
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003817 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003818 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003819
John Kessenich5611c6d2018-04-05 11:25:02 -06003820 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003821 TranslateNonUniformDecoration(type.getQualifier()),
3822 nominalTypeId,
3823 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003824 TranslateMemoryScope(coherentFlags),
3825 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003826
3827 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003828 if (type.getBasicType() == glslang::EbtBool) {
3829 if (builder.isScalarType(nominalTypeId)) {
3830 // Conversion for bool
3831 spv::Id boolType = builder.makeBoolType();
3832 if (nominalTypeId != boolType)
3833 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3834 } else if (builder.isVectorType(nominalTypeId)) {
3835 // Conversion for bvec
3836 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3837 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3838 if (nominalTypeId != bvecType)
3839 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3840 }
3841 }
John Kessenich103bef92016-02-08 21:38:15 -07003842
3843 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003844}
3845
Rex Xu27253232016-02-23 17:51:09 +08003846// Wrap the builder's accessChainStore to:
3847// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003848//
3849// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003850void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3851{
3852 // Need to convert to abstract types when necessary
3853 if (type.getBasicType() == glslang::EbtBool) {
3854 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3855
3856 if (builder.isScalarType(nominalTypeId)) {
3857 // Conversion for bool
3858 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003859 if (nominalTypeId != boolType) {
3860 // keep these outside arguments, for determinant order-of-evaluation
3861 spv::Id one = builder.makeUintConstant(1);
3862 spv::Id zero = builder.makeUintConstant(0);
3863 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3864 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003865 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003866 } else if (builder.isVectorType(nominalTypeId)) {
3867 // Conversion for bvec
3868 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3869 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003870 if (nominalTypeId != bvecType) {
3871 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003872 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3873 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3874 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003875 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003876 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3877 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003878 }
3879 }
3880
Jeff Bolz36831c92018-09-05 10:11:41 -05003881 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3882 coherentFlags |= TranslateCoherent(type);
3883
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003884 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003885 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003886
Jeff Bolz36831c92018-09-05 10:11:41 -05003887 builder.accessChainStore(rvalue,
3888 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003889 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003890}
3891
John Kessenich4bf71552016-09-02 11:20:21 -06003892// For storing when types match at the glslang level, but not might match at the
3893// SPIR-V level.
3894//
3895// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003896// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003897// as in a member-decorated way.
3898//
3899// NOTE: This function can handle any store request; if it's not special it
3900// simplifies to a simple OpStore.
3901//
3902// Implicitly uses the existing builder.accessChain as the storage target.
3903void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3904{
John Kessenichb3e24e42016-09-11 12:33:43 -06003905 // we only do the complex path here if it's an aggregate
3906 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003907 accessChainStore(type, rValue);
3908 return;
3909 }
3910
John Kessenichb3e24e42016-09-11 12:33:43 -06003911 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003912 spv::Id rType = builder.getTypeId(rValue);
3913 spv::Id lValue = builder.accessChainGetLValue();
3914 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3915 if (lType == rType) {
3916 accessChainStore(type, rValue);
3917 return;
3918 }
3919
John Kessenichb3e24e42016-09-11 12:33:43 -06003920 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003921 // where the two types were the same type in GLSL. This requires member
3922 // by member copy, recursively.
3923
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003924 // SPIR-V 1.4 added an instruction to do help do this.
3925 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3926 // However, bool in uniform space is changed to int, so
3927 // OpCopyLogical does not work for that.
3928 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3929 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3930 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3931 if (lBool == rBool) {
3932 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3933 accessChainStore(type, logicalCopy);
3934 return;
3935 }
3936 }
3937
John Kessenichb3e24e42016-09-11 12:33:43 -06003938 // If an array, copy element by element.
3939 if (type.isArray()) {
3940 glslang::TType glslangElementType(type, 0);
3941 spv::Id elementRType = builder.getContainedTypeId(rType);
3942 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3943 // get the source member
3944 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003945
John Kessenichb3e24e42016-09-11 12:33:43 -06003946 // set up the target storage
3947 builder.clearAccessChain();
3948 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003949 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003950
John Kessenichb3e24e42016-09-11 12:33:43 -06003951 // store the member
3952 multiTypeStore(glslangElementType, elementRValue);
3953 }
3954 } else {
3955 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003956
John Kessenichb3e24e42016-09-11 12:33:43 -06003957 // loop over structure members
3958 const glslang::TTypeList& members = *type.getStruct();
3959 for (int m = 0; m < (int)members.size(); ++m) {
3960 const glslang::TType& glslangMemberType = *members[m].type;
3961
3962 // get the source member
3963 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3964 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3965
3966 // set up the target storage
3967 builder.clearAccessChain();
3968 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003969 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003970
3971 // store the member
3972 multiTypeStore(glslangMemberType, memberRValue);
3973 }
John Kessenich4bf71552016-09-02 11:20:21 -06003974 }
3975}
3976
John Kessenichf85e8062015-12-19 13:57:10 -07003977// Decide whether or not this type should be
3978// decorated with offsets and strides, and if so
3979// whether std140 or std430 rules should be applied.
3980glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003981{
John Kessenichf85e8062015-12-19 13:57:10 -07003982 // has to be a block
3983 if (type.getBasicType() != glslang::EbtBlock)
3984 return glslang::ElpNone;
3985
Chao Chen3c366992018-09-19 11:41:59 -07003986 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003987 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003988 type.getQualifier().storage != glslang::EvqBuffer &&
3989 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003990 return glslang::ElpNone;
3991
3992 // return the layout to use
3993 switch (type.getQualifier().layoutPacking) {
3994 case glslang::ElpStd140:
3995 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003996 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003997 return type.getQualifier().layoutPacking;
3998 default:
3999 return glslang::ElpNone;
4000 }
John Kessenich31ed4832015-09-09 17:51:38 -06004001}
4002
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004003// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004004int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004005{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004006 int size;
John Kessenich49987892015-12-29 17:11:44 -07004007 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004008 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004009
4010 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004011}
4012
John Kessenich49987892015-12-29 17:11:44 -07004013// 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 -07004014// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004015int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004016{
John Kessenich49987892015-12-29 17:11:44 -07004017 glslang::TType elementType;
4018 elementType.shallowCopy(matrixType);
4019 elementType.clearArraySizes();
4020
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004021 int size;
John Kessenich49987892015-12-29 17:11:44 -07004022 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004023 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004024
4025 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004026}
4027
John Kessenich5e4b1242015-08-06 22:53:06 -06004028// Given a member type of a struct, realign the current offset for it, and compute
4029// the next (not yet aligned) offset for the next member, which will get aligned
4030// on the next call.
4031// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4032// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4033// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004034void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004035 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004036{
4037 // this will get a positive value when deemed necessary
4038 nextOffset = -1;
4039
John Kessenich5e4b1242015-08-06 22:53:06 -06004040 // override anything in currentOffset with user-set offset
4041 if (memberType.getQualifier().hasOffset())
4042 currentOffset = memberType.getQualifier().layoutOffset;
4043
4044 // It could be that current linker usage in glslang updated all the layoutOffset,
4045 // in which case the following code does not matter. But, that's not quite right
4046 // once cross-compilation unit GLSL validation is done, as the original user
4047 // settings are needed in layoutOffset, and then the following will come into play.
4048
John Kessenichf85e8062015-12-19 13:57:10 -07004049 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 if (! memberType.getQualifier().hasOffset())
4051 currentOffset = -1;
4052
4053 return;
4054 }
4055
John Kessenichf85e8062015-12-19 13:57:10 -07004056 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 if (currentOffset < 0)
4058 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004059
John Kessenich5e4b1242015-08-06 22:53:06 -06004060 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4061 // but possibly not yet correctly aligned.
4062
4063 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004064 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004065 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004066
4067 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004068 // TODO: make this consistent in early phases of code:
4069 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4070 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4071 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004072 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004073 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004074 int dummySize;
4075 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4076 if (componentAlignment <= 4)
4077 memberAlignment = componentAlignment;
4078 }
4079
4080 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004082
4083 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004084 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004085 glslang::RoundToPow2(currentOffset, 16);
4086
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 nextOffset = currentOffset + memberSize;
4088}
4089
David Netoa901ffe2016-06-08 14:11:40 +01004090void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004091{
David Netoa901ffe2016-06-08 14:11:40 +01004092 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4093 switch (glslangBuiltIn)
4094 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004095 case glslang::EbvPointSize:
4096#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004097 case glslang::EbvClipDistance:
4098 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004099 case glslang::EbvViewportMaskNV:
4100 case glslang::EbvSecondaryPositionNV:
4101 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004102 case glslang::EbvPositionPerViewNV:
4103 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004104 case glslang::EbvTaskCountNV:
4105 case glslang::EbvPrimitiveCountNV:
4106 case glslang::EbvPrimitiveIndicesNV:
4107 case glslang::EbvClipDistancePerViewNV:
4108 case glslang::EbvCullDistancePerViewNV:
4109 case glslang::EbvLayerPerViewNV:
4110 case glslang::EbvMeshViewCountNV:
4111 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004112#endif
David Netoa901ffe2016-06-08 14:11:40 +01004113 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4114 // Alternately, we could just call this for any glslang built-in, since the
4115 // capability already guards against duplicates.
4116 TranslateBuiltInDecoration(glslangBuiltIn, false);
4117 break;
4118 default:
4119 // Capabilities were already generated when the struct was declared.
4120 break;
4121 }
John Kessenichebb50532016-05-16 19:22:05 -06004122}
4123
John Kessenich6fccb3c2016-09-19 16:01:41 -06004124bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004125{
John Kessenicheee9d532016-09-19 18:09:30 -06004126 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004127}
4128
John Kessenichd41993d2017-09-10 15:21:05 -06004129// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004130// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4131// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004132bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004133{
John Kessenich6a14f782017-12-04 02:48:10 -07004134 assert(qualifier == glslang::EvqIn ||
4135 qualifier == glslang::EvqOut ||
4136 qualifier == glslang::EvqInOut ||
4137 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004138 return qualifier != glslang::EvqConstReadOnly;
4139}
4140
4141// Is parameter pass-by-original?
4142bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4143 bool implicitThisParam)
4144{
4145 if (implicitThisParam) // implicit this
4146 return true;
4147 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004148 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004149 return paramType.containsOpaque() || // sampler, etc.
4150 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4151}
4152
John Kessenich140f3df2015-06-26 16:58:36 -06004153// Make all the functions, skeletally, without actually visiting their bodies.
4154void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4155{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004156 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004157 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4158 if (paramPrecision != spv::NoPrecision)
4159 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004160 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004161 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004162 // Original and non-writable params pass the pointer directly and
4163 // use restrict/aliased, others are stored to a pointer in Function
4164 // memory and use RestrictPointer/AliasedPointer.
4165 if (originalParam(type.getQualifier().storage, type, false) ||
4166 !writableParam(type.getQualifier().storage)) {
4167 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4168 } else {
4169 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4170 }
4171 }
John Kessenichfad62972017-07-18 02:35:46 -06004172 };
4173
John Kessenich140f3df2015-06-26 16:58:36 -06004174 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4175 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004176 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004177 continue;
4178
4179 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004180 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004181 //
qining25262b32016-05-06 17:25:16 -04004182 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004183 // function. What it is an address of varies:
4184 //
John Kessenich4bf71552016-09-02 11:20:21 -06004185 // - "in" parameters not marked as "const" can be written to without modifying the calling
4186 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004187 //
4188 // - "const in" parameters can just be the r-value, as no writes need occur.
4189 //
John Kessenich4bf71552016-09-02 11:20:21 -06004190 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4191 // 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 -06004192
4193 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004194 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004195 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4196
John Kessenich155d3512019-08-08 23:29:20 -06004197#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004198 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4199 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004200#else
4201 bool implicitThis = false;
4202#endif
John Kessenich37789792017-03-21 23:56:40 -06004203
John Kessenichfad62972017-07-18 02:35:46 -06004204 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004205 for (int p = 0; p < (int)parameters.size(); ++p) {
4206 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4207 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004208 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004209 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004210 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004211 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4212 else
John Kessenich4bf71552016-09-02 11:20:21 -06004213 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004214 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004215 paramTypes.push_back(typeId);
4216 }
4217
4218 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004219 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4220 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004221 glslFunction->getName().c_str(), paramTypes,
4222 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004223 if (implicitThis)
4224 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004225
4226 // Track function to emit/call later
4227 functionMap[glslFunction->getName().c_str()] = function;
4228
4229 // Set the parameter id's
4230 for (int p = 0; p < (int)parameters.size(); ++p) {
4231 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4232 // give a name too
4233 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004234
4235 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004236 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004237 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004238 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004239 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004240 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004241 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004242 }
4243 }
4244}
4245
4246// Process all the initializers, while skipping the functions and link objects
4247void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4248{
4249 builder.setBuildPoint(shaderEntry->getLastBlock());
4250 for (int i = 0; i < (int)initializers.size(); ++i) {
4251 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4252 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4253
4254 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004255 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004256 initializer->traverse(this);
4257 }
4258 }
4259}
4260
4261// Process all the functions, while skipping initializers.
4262void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4263{
4264 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4265 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004266 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004267 node->traverse(this);
4268 }
4269}
4270
4271void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4272{
qining25262b32016-05-06 17:25:16 -04004273 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004274 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004275 currentFunction = functionMap[node->getName().c_str()];
4276 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004277 builder.setBuildPoint(functionBlock);
4278}
4279
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004280void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004281{
Rex Xufc618912015-09-09 16:42:49 +08004282 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004283
4284 glslang::TSampler sampler = {};
4285 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004286#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004287 bool f16ShadowCompare = false;
4288#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004289 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004290 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4291 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004292#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004293 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4294#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004295 }
4296
John Kessenich140f3df2015-06-26 16:58:36 -06004297 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4298 builder.clearAccessChain();
4299 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004300
John Kessenicha28f7a72019-08-06 07:00:58 -06004301#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004302 // Special case l-value operands
4303 bool lvalue = false;
4304 switch (node.getOp()) {
4305 case glslang::EOpImageAtomicAdd:
4306 case glslang::EOpImageAtomicMin:
4307 case glslang::EOpImageAtomicMax:
4308 case glslang::EOpImageAtomicAnd:
4309 case glslang::EOpImageAtomicOr:
4310 case glslang::EOpImageAtomicXor:
4311 case glslang::EOpImageAtomicExchange:
4312 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004313 case glslang::EOpImageAtomicLoad:
4314 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004315 if (i == 0)
4316 lvalue = true;
4317 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004318 case glslang::EOpSparseImageLoad:
4319 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4320 lvalue = true;
4321 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004322 case glslang::EOpSparseTexture:
4323 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4324 lvalue = true;
4325 break;
4326 case glslang::EOpSparseTextureClamp:
4327 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4328 lvalue = true;
4329 break;
4330 case glslang::EOpSparseTextureLod:
4331 case glslang::EOpSparseTextureOffset:
4332 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4333 lvalue = true;
4334 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004335 case glslang::EOpSparseTextureFetch:
4336 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4337 lvalue = true;
4338 break;
4339 case glslang::EOpSparseTextureFetchOffset:
4340 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4341 lvalue = true;
4342 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004343 case glslang::EOpSparseTextureLodOffset:
4344 case glslang::EOpSparseTextureGrad:
4345 case glslang::EOpSparseTextureOffsetClamp:
4346 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4347 lvalue = true;
4348 break;
4349 case glslang::EOpSparseTextureGradOffset:
4350 case glslang::EOpSparseTextureGradClamp:
4351 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4352 lvalue = true;
4353 break;
4354 case glslang::EOpSparseTextureGradOffsetClamp:
4355 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4356 lvalue = true;
4357 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004358 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004359 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4360 lvalue = true;
4361 break;
4362 case glslang::EOpSparseTextureGatherOffset:
4363 case glslang::EOpSparseTextureGatherOffsets:
4364 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4365 lvalue = true;
4366 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004367 case glslang::EOpSparseTextureGatherLod:
4368 if (i == 3)
4369 lvalue = true;
4370 break;
4371 case glslang::EOpSparseTextureGatherLodOffset:
4372 case glslang::EOpSparseTextureGatherLodOffsets:
4373 if (i == 4)
4374 lvalue = true;
4375 break;
Rex Xu129799a2017-07-05 17:23:28 +08004376 case glslang::EOpSparseImageLoadLod:
4377 if (i == 3)
4378 lvalue = true;
4379 break;
Chao Chen3a137962018-09-19 11:41:27 -07004380 case glslang::EOpImageSampleFootprintNV:
4381 if (i == 4)
4382 lvalue = true;
4383 break;
4384 case glslang::EOpImageSampleFootprintClampNV:
4385 case glslang::EOpImageSampleFootprintLodNV:
4386 if (i == 5)
4387 lvalue = true;
4388 break;
4389 case glslang::EOpImageSampleFootprintGradNV:
4390 if (i == 6)
4391 lvalue = true;
4392 break;
4393 case glslang::EOpImageSampleFootprintGradClampNV:
4394 if (i == 7)
4395 lvalue = true;
4396 break;
Rex Xufc618912015-09-09 16:42:49 +08004397 default:
4398 break;
4399 }
4400
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004401 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004402 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004403 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4404 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4405 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004406#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004407 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004408 }
4409}
4410
John Kessenichfc51d282015-08-19 13:34:18 -06004411void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004412{
John Kessenichfc51d282015-08-19 13:34:18 -06004413 builder.clearAccessChain();
4414 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004415 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004416}
John Kessenich140f3df2015-06-26 16:58:36 -06004417
John Kessenichfc51d282015-08-19 13:34:18 -06004418spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4419{
John Kesseniche485c7a2017-05-31 18:50:53 -06004420 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004421 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004422
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004423 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004424
John Kessenichfc51d282015-08-19 13:34:18 -06004425 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004426
John Kessenichf43c7392019-03-31 10:51:57 -06004427 const glslang::TType &imageType = node->getAsAggregate()
4428 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4429 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004430 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004431#ifdef GLSLANG_WEB
4432 const bool f16ShadowCompare = false;
4433#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004434 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004435 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4436 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004437#endif
4438
John Kessenichf43c7392019-03-31 10:51:57 -06004439 const auto signExtensionMask = [&]() {
4440 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4441 if (sampler.type == glslang::EbtUint)
4442 return spv::ImageOperandsZeroExtendMask;
4443 else if (sampler.type == glslang::EbtInt)
4444 return spv::ImageOperandsSignExtendMask;
4445 }
4446 return spv::ImageOperandsMaskNone;
4447 };
4448
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004449 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4450
John Kessenichfc51d282015-08-19 13:34:18 -06004451 std::vector<spv::Id> arguments;
4452 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004453 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004454 else
4455 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004456 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004457
4458 spv::Builder::TextureParameters params = { };
4459 params.sampler = arguments[0];
4460
Rex Xu04db3f52015-09-16 11:44:02 +08004461 glslang::TCrackedTextureOp cracked;
4462 node->crackTexture(sampler, cracked);
4463
amhagan05506bb2017-06-13 16:53:02 -04004464 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004465
John Kessenichfc51d282015-08-19 13:34:18 -06004466 // Check for queries
4467 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004468 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4469 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004470 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004471
John Kessenichfc51d282015-08-19 13:34:18 -06004472 switch (node->getOp()) {
4473 case glslang::EOpImageQuerySize:
4474 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004475 if (arguments.size() > 1) {
4476 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004477 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004478 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004479 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004480#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004481 case glslang::EOpImageQuerySamples:
4482 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004483 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004484 case glslang::EOpTextureQueryLod:
4485 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004486 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004487 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004488 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004489 case glslang::EOpSparseTexelsResident:
4490 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004491#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004492 default:
4493 assert(0);
4494 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 }
John Kessenich140f3df2015-06-26 16:58:36 -06004496 }
4497
LoopDawg4425f242018-02-18 11:40:01 -07004498 int components = node->getType().getVectorSize();
4499
4500 if (node->getOp() == glslang::EOpTextureFetch) {
4501 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4502 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4503 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4504 // here around e.g. which ones return scalars or other types.
4505 components = 4;
4506 }
4507
4508 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4509
4510 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4511
Rex Xufc618912015-09-09 16:42:49 +08004512 // Check for image functions other than queries
4513 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004514 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004515 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004516 spv::IdImmediate image = { true, *(opIt++) };
4517 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004518
4519 // Handle subpass operations
4520 // TODO: GLSL should change to have the "MS" only on the type rather than the
4521 // built-in function.
4522 if (cracked.subpass) {
4523 // add on the (0,0) coordinate
4524 spv::Id zero = builder.makeIntConstant(0);
4525 std::vector<spv::Id> comps;
4526 comps.push_back(zero);
4527 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004528 spv::IdImmediate coord = { true,
4529 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4530 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004531 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4532 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004533 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004534 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4535 }
4536 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004537 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004538 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004539 spv::IdImmediate imageOperand = { true, *(opIt++) };
4540 operands.push_back(imageOperand);
4541 }
John Kessenich6c292d32016-02-15 20:58:50 -07004542 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004543 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4544 builder.setPrecision(result, precision);
4545 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004546 }
4547
John Kessenich149afc32018-08-14 13:31:43 -06004548 spv::IdImmediate coord = { true, *(opIt++) };
4549 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004550 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004551 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004552 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004553 mask = mask | spv::ImageOperandsSampleMask;
4554 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004555 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004556 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4557 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004558 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004559 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004560 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4561 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004562 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004563 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004564 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4565 operands.push_back(imageOperands);
4566 }
4567 if (mask & spv::ImageOperandsSampleMask) {
4568 spv::IdImmediate imageOperand = { true, *opIt++ };
4569 operands.push_back(imageOperand);
4570 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004571 if (mask & spv::ImageOperandsLodMask) {
4572 spv::IdImmediate imageOperand = { true, *opIt++ };
4573 operands.push_back(imageOperand);
4574 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004575 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004576 spv::IdImmediate imageOperand = { true,
4577 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004578 operands.push_back(imageOperand);
4579 }
4580
John Kessenich149afc32018-08-14 13:31:43 -06004581 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004582 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004583
John Kessenich149afc32018-08-14 13:31:43 -06004584 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004585 builder.setPrecision(result[0], precision);
4586
4587 // If needed, add a conversion constructor to the proper size.
4588 if (components != node->getType().getVectorSize())
4589 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4590
4591 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004592 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004593
Jeff Bolz36831c92018-09-05 10:11:41 -05004594 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004595 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004596 spv::IdImmediate texel = { true, *(opIt + 1) };
4597 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004598 } else {
4599 spv::IdImmediate texel = { true, *opIt };
4600 operands.push_back(texel);
4601 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004602
4603 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004604 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004605 mask = mask | spv::ImageOperandsSampleMask;
4606 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004607 if (cracked.lod) {
4608 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4609 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4610 mask = mask | spv::ImageOperandsLodMask;
4611 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004612 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4613 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004614 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004615 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004616 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4617 operands.push_back(imageOperands);
4618 }
4619 if (mask & spv::ImageOperandsSampleMask) {
4620 spv::IdImmediate imageOperand = { true, *opIt++ };
4621 operands.push_back(imageOperand);
4622 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004623 if (mask & spv::ImageOperandsLodMask) {
4624 spv::IdImmediate imageOperand = { true, *opIt++ };
4625 operands.push_back(imageOperand);
4626 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004627 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004628 spv::IdImmediate imageOperand = { true,
4629 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004630 operands.push_back(imageOperand);
4631 }
4632
John Kessenich56bab042015-09-16 10:54:31 -06004633 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004634 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004635 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004636 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004637 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4638 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004639 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004640 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004641 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4642
Jeff Bolz36831c92018-09-05 10:11:41 -05004643 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004644 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004645 mask = mask | spv::ImageOperandsSampleMask;
4646 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004647 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004648 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4649 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4650
Jeff Bolz36831c92018-09-05 10:11:41 -05004651 mask = mask | spv::ImageOperandsLodMask;
4652 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004653 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4654 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004655 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004656 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004657 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004658 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004659 }
4660 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004661 spv::IdImmediate imageOperand = { true, *opIt++ };
4662 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004663 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004664 if (mask & spv::ImageOperandsLodMask) {
4665 spv::IdImmediate imageOperand = { true, *opIt++ };
4666 operands.push_back(imageOperand);
4667 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004668 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4669 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4670 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004671 }
4672
4673 // Create the return type that was a special structure
4674 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004675 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004676 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4677 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4678
4679 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4680
4681 // Decode the return type
4682 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4683 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004684 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004685 // Process image atomic operations
4686
4687 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4688 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004689 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004690 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004691 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004692
Jeff Bolz36831c92018-09-05 10:11:41 -05004693 spv::Id resultTypeId;
4694 // imageAtomicStore has a void return type so base the pointer type on
4695 // the type of the value operand.
4696 if (node->getOp() == glslang::EOpImageAtomicStore) {
4697 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4698 } else {
4699 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4700 }
John Kessenich56bab042015-09-16 10:54:31 -06004701 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004702
4703 std::vector<spv::Id> operands;
4704 operands.push_back(pointer);
4705 for (; opIt != arguments.end(); ++opIt)
4706 operands.push_back(*opIt);
4707
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004708 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004709 }
4710 }
4711
John Kessenicha28f7a72019-08-06 07:00:58 -06004712#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004713 // Check for fragment mask functions other than queries
4714 if (cracked.fragMask) {
4715 assert(sampler.ms);
4716
4717 auto opIt = arguments.begin();
4718 std::vector<spv::Id> operands;
4719
4720 // Extract the image if necessary
4721 if (builder.isSampledImage(params.sampler))
4722 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4723
4724 operands.push_back(params.sampler);
4725 ++opIt;
4726
4727 if (sampler.isSubpass()) {
4728 // add on the (0,0) coordinate
4729 spv::Id zero = builder.makeIntConstant(0);
4730 std::vector<spv::Id> comps;
4731 comps.push_back(zero);
4732 comps.push_back(zero);
4733 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4734 }
4735
4736 for (; opIt != arguments.end(); ++opIt)
4737 operands.push_back(*opIt);
4738
4739 spv::Op fragMaskOp = spv::OpNop;
4740 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4741 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4742 else if (node->getOp() == glslang::EOpFragmentFetch)
4743 fragMaskOp = spv::OpFragmentFetchAMD;
4744
4745 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4746 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4747 return builder.createOp(fragMaskOp, resultType(), operands);
4748 }
4749#endif
4750
Rex Xufc618912015-09-09 16:42:49 +08004751 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004752 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004753 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004754 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004755
John Kessenichfc51d282015-08-19 13:34:18 -06004756 // check for bias argument
4757 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004758 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004759 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004760 if (cracked.gather)
4761 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004762
4763 if (f16ShadowCompare)
4764 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004765 if (cracked.offset)
4766 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004767 else if (cracked.offsets)
4768 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004769 if (cracked.grad)
4770 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004771 if (cracked.lodClamp)
4772 ++nonBiasArgCount;
4773 if (sparse)
4774 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004775 if (imageFootprint)
4776 //Following three extra arguments
4777 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4778 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004779 if ((int)arguments.size() > nonBiasArgCount)
4780 bias = true;
4781 }
4782
John Kessenicha5c33d62016-06-02 23:45:21 -06004783 // See if the sampler param should really be just the SPV image part
4784 if (cracked.fetch) {
4785 // a fetch needs to have the image extracted first
4786 if (builder.isSampledImage(params.sampler))
4787 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4788 }
4789
John Kessenicha28f7a72019-08-06 07:00:58 -06004790#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004791 if (cracked.gather) {
4792 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4793 if (bias || cracked.lod ||
4794 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4795 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004796 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004797 }
4798 }
4799#endif
4800
John Kessenichfc51d282015-08-19 13:34:18 -06004801 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004802
John Kessenichfc51d282015-08-19 13:34:18 -06004803 params.coords = arguments[1];
4804 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004805 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004806
4807 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004808 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004809 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004810 ++extraArgs;
4811 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004812 params.Dref = arguments[2];
4813 ++extraArgs;
4814 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004815 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004816 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004817 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004818 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004819 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004820 dRefComp = builder.getNumComponents(params.coords) - 1;
4821 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004822 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4823 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004824
4825 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004826 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004827 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004828 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004829 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4830 !(glslangIntermediate->getStage() == EShLangCompute &&
4831 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004832 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4833 noImplicitLod = true;
4834 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004835
4836 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004837 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004838 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004839 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004840 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004841
4842 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004843 if (cracked.grad) {
4844 params.gradX = arguments[2 + extraArgs];
4845 params.gradY = arguments[3 + extraArgs];
4846 extraArgs += 2;
4847 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004848
4849 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004850 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004851 params.offset = arguments[2 + extraArgs];
4852 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004853 } else if (cracked.offsets) {
4854 params.offsets = arguments[2 + extraArgs];
4855 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004856 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004857
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004858#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004859 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004860 if (cracked.lodClamp) {
4861 params.lodClamp = arguments[2 + extraArgs];
4862 ++extraArgs;
4863 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004864 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004865 if (sparse) {
4866 params.texelOut = arguments[2 + extraArgs];
4867 ++extraArgs;
4868 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004869 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004870 if (cracked.gather && ! sampler.shadow) {
4871 // default component is 0, if missing, otherwise an argument
4872 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004873 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004874 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004875 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004876 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004877 }
Chao Chen3a137962018-09-19 11:41:27 -07004878 spv::Id resultStruct = spv::NoResult;
4879 if (imageFootprint) {
4880 //Following three extra arguments
4881 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4882 params.granularity = arguments[2 + extraArgs];
4883 params.coarse = arguments[3 + extraArgs];
4884 resultStruct = arguments[4 + extraArgs];
4885 extraArgs += 3;
4886 }
4887#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004888 // bias
4889 if (bias) {
4890 params.bias = arguments[2 + extraArgs];
4891 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004892 }
John Kessenichfc51d282015-08-19 13:34:18 -06004893
John Kessenicha28f7a72019-08-06 07:00:58 -06004894#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004895 if (imageFootprint) {
4896 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4897 builder.addCapability(spv::CapabilityImageFootprintNV);
4898
4899
4900 //resultStructType(OpenGL type) contains 5 elements:
4901 //struct gl_TextureFootprint2DNV {
4902 // uvec2 anchor;
4903 // uvec2 offset;
4904 // uvec2 mask;
4905 // uint lod;
4906 // uint granularity;
4907 //};
4908 //or
4909 //struct gl_TextureFootprint3DNV {
4910 // uvec3 anchor;
4911 // uvec3 offset;
4912 // uvec2 mask;
4913 // uint lod;
4914 // uint granularity;
4915 //};
4916 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4917 assert(builder.isStructType(resultStructType));
4918
4919 //resType (SPIR-V type) contains 6 elements:
4920 //Member 0 must be a Boolean type scalar(LOD),
4921 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4922 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4923 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4924 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4925 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4926 std::vector<spv::Id> members;
4927 members.push_back(resultType());
4928 for (int i = 0; i < 5; i++) {
4929 members.push_back(builder.getContainedTypeId(resultStructType, i));
4930 }
4931 spv::Id resType = builder.makeStructType(members, "ResType");
4932
4933 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004934 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4935 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004936
4937 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4938 for (int i = 0; i < 5; i++) {
4939 builder.clearAccessChain();
4940 builder.setAccessChainLValue(resultStruct);
4941
4942 //Accessing to a struct we created, no coherent flag is set
4943 spv::Builder::AccessChain::CoherentFlags flags;
4944 flags.clear();
4945
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004946 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004947 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4948 }
4949 return builder.createCompositeExtract(res, resultType(), 0);
4950 }
4951#endif
4952
John Kessenich65336482016-06-16 14:06:26 -06004953 // projective component (might not to move)
4954 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4955 // are divided by the last component of P."
4956 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4957 // unused components will appear after all used components."
4958 if (cracked.proj) {
4959 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4960 int projTargetComp;
4961 switch (sampler.dim) {
4962 case glslang::Esd1D: projTargetComp = 1; break;
4963 case glslang::Esd2D: projTargetComp = 2; break;
4964 case glslang::EsdRect: projTargetComp = 2; break;
4965 default: projTargetComp = projSourceComp; break;
4966 }
4967 // copy the projective coordinate if we have to
4968 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004969 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004970 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4971 projSourceComp);
4972 params.coords = builder.createCompositeInsert(projComp, params.coords,
4973 builder.getTypeId(params.coords), projTargetComp);
4974 }
4975 }
4976
Jeff Bolz36831c92018-09-05 10:11:41 -05004977 // nonprivate
4978 if (imageType.getQualifier().nonprivate) {
4979 params.nonprivate = true;
4980 }
4981
4982 // volatile
4983 if (imageType.getQualifier().volatil) {
4984 params.volatil = true;
4985 }
4986
St0fFa1184dd2018-04-09 21:08:14 +02004987 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004988 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4989 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004990 );
LoopDawg4425f242018-02-18 11:40:01 -07004991
4992 if (components != node->getType().getVectorSize())
4993 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4994
4995 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004996}
4997
4998spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4999{
5000 // Grab the function's pointer from the previously created function
5001 spv::Function* function = functionMap[node->getName().c_str()];
5002 if (! function)
5003 return 0;
5004
5005 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5006 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5007
5008 // See comments in makeFunctions() for details about the semantics for parameter passing.
5009 //
5010 // These imply we need a four step process:
5011 // 1. Evaluate the arguments
5012 // 2. Allocate and make copies of in, out, and inout arguments
5013 // 3. Make the call
5014 // 4. Copy back the results
5015
John Kessenichd3ed90b2018-05-04 11:43:03 -06005016 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005017 std::vector<spv::Builder::AccessChain> lValues;
5018 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005019 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005020 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005021 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005022 // build l-value
5023 builder.clearAccessChain();
5024 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005025 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005026 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005027 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005028 // save l-value
5029 lValues.push_back(builder.getAccessChain());
5030 } else {
5031 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005032 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005033 }
5034 }
5035
5036 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5037 // copy the original into that space.
5038 //
5039 // Also, build up the list of actual arguments to pass in for the call
5040 int lValueCount = 0;
5041 int rValueCount = 0;
5042 std::vector<spv::Id> spvArgs;
5043 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5044 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005045 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005046 builder.setAccessChain(lValues[lValueCount]);
5047 arg = builder.accessChainGetLValue();
5048 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005049 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005050 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005051 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005052 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5053 // need to copy the input into output space
5054 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005055 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005056 builder.clearAccessChain();
5057 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005058 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005059 }
5060 ++lValueCount;
5061 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005062 // process r-value, which involves a copy for a type mismatch
5063 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5064 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5065 builder.clearAccessChain();
5066 builder.setAccessChainLValue(argCopy);
5067 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5068 arg = builder.createLoad(argCopy);
5069 } else
5070 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005071 ++rValueCount;
5072 }
5073 spvArgs.push_back(arg);
5074 }
5075
5076 // 3. Make the call.
5077 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005078 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005079
5080 // 4. Copy back out an "out" arguments.
5081 lValueCount = 0;
5082 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005083 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005084 ++lValueCount;
5085 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005086 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5087 spv::Id copy = builder.createLoad(spvArgs[a]);
5088 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005089 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005090 }
5091 ++lValueCount;
5092 }
5093 }
5094
5095 return result;
5096}
5097
5098// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005099spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005100 spv::Id typeId, spv::Id left, spv::Id right,
5101 glslang::TBasicType typeProxy, bool reduceComparison)
5102{
John Kessenich66011cb2018-03-06 16:12:04 -07005103 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5104 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005105 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005106
5107 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005108 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005109 bool comparison = false;
5110
5111 switch (op) {
5112 case glslang::EOpAdd:
5113 case glslang::EOpAddAssign:
5114 if (isFloat)
5115 binOp = spv::OpFAdd;
5116 else
5117 binOp = spv::OpIAdd;
5118 break;
5119 case glslang::EOpSub:
5120 case glslang::EOpSubAssign:
5121 if (isFloat)
5122 binOp = spv::OpFSub;
5123 else
5124 binOp = spv::OpISub;
5125 break;
5126 case glslang::EOpMul:
5127 case glslang::EOpMulAssign:
5128 if (isFloat)
5129 binOp = spv::OpFMul;
5130 else
5131 binOp = spv::OpIMul;
5132 break;
5133 case glslang::EOpVectorTimesScalar:
5134 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005135 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005136 if (builder.isVector(right))
5137 std::swap(left, right);
5138 assert(builder.isScalar(right));
5139 needMatchingVectors = false;
5140 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005141 } else if (isFloat)
5142 binOp = spv::OpFMul;
5143 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005144 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005145 break;
5146 case glslang::EOpVectorTimesMatrix:
5147 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005148 binOp = spv::OpVectorTimesMatrix;
5149 break;
5150 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005151 binOp = spv::OpMatrixTimesVector;
5152 break;
5153 case glslang::EOpMatrixTimesScalar:
5154 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005155 binOp = spv::OpMatrixTimesScalar;
5156 break;
5157 case glslang::EOpMatrixTimesMatrix:
5158 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005159 binOp = spv::OpMatrixTimesMatrix;
5160 break;
5161 case glslang::EOpOuterProduct:
5162 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005163 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005164 break;
5165
5166 case glslang::EOpDiv:
5167 case glslang::EOpDivAssign:
5168 if (isFloat)
5169 binOp = spv::OpFDiv;
5170 else if (isUnsigned)
5171 binOp = spv::OpUDiv;
5172 else
5173 binOp = spv::OpSDiv;
5174 break;
5175 case glslang::EOpMod:
5176 case glslang::EOpModAssign:
5177 if (isFloat)
5178 binOp = spv::OpFMod;
5179 else if (isUnsigned)
5180 binOp = spv::OpUMod;
5181 else
5182 binOp = spv::OpSMod;
5183 break;
5184 case glslang::EOpRightShift:
5185 case glslang::EOpRightShiftAssign:
5186 if (isUnsigned)
5187 binOp = spv::OpShiftRightLogical;
5188 else
5189 binOp = spv::OpShiftRightArithmetic;
5190 break;
5191 case glslang::EOpLeftShift:
5192 case glslang::EOpLeftShiftAssign:
5193 binOp = spv::OpShiftLeftLogical;
5194 break;
5195 case glslang::EOpAnd:
5196 case glslang::EOpAndAssign:
5197 binOp = spv::OpBitwiseAnd;
5198 break;
5199 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005200 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005201 binOp = spv::OpLogicalAnd;
5202 break;
5203 case glslang::EOpInclusiveOr:
5204 case glslang::EOpInclusiveOrAssign:
5205 binOp = spv::OpBitwiseOr;
5206 break;
5207 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005208 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005209 binOp = spv::OpLogicalOr;
5210 break;
5211 case glslang::EOpExclusiveOr:
5212 case glslang::EOpExclusiveOrAssign:
5213 binOp = spv::OpBitwiseXor;
5214 break;
5215 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005216 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005217 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005218 break;
5219
5220 case glslang::EOpLessThan:
5221 case glslang::EOpGreaterThan:
5222 case glslang::EOpLessThanEqual:
5223 case glslang::EOpGreaterThanEqual:
5224 case glslang::EOpEqual:
5225 case glslang::EOpNotEqual:
5226 case glslang::EOpVectorEqual:
5227 case glslang::EOpVectorNotEqual:
5228 comparison = true;
5229 break;
5230 default:
5231 break;
5232 }
5233
John Kessenich7c1aa102015-10-15 13:29:11 -06005234 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005235 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005236 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005237 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5238 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005239 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005240
5241 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005242 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005243 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005244
qining25262b32016-05-06 17:25:16 -04005245 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005246 decorations.addNoContraction(builder, result);
5247 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005248 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005249 }
5250
5251 if (! comparison)
5252 return 0;
5253
John Kessenich7c1aa102015-10-15 13:29:11 -06005254 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005255
John Kessenich4583b612016-08-07 19:14:22 -06005256 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005257 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5258 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005259 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005260 return result;
5261 }
John Kessenich140f3df2015-06-26 16:58:36 -06005262
5263 switch (op) {
5264 case glslang::EOpLessThan:
5265 if (isFloat)
5266 binOp = spv::OpFOrdLessThan;
5267 else if (isUnsigned)
5268 binOp = spv::OpULessThan;
5269 else
5270 binOp = spv::OpSLessThan;
5271 break;
5272 case glslang::EOpGreaterThan:
5273 if (isFloat)
5274 binOp = spv::OpFOrdGreaterThan;
5275 else if (isUnsigned)
5276 binOp = spv::OpUGreaterThan;
5277 else
5278 binOp = spv::OpSGreaterThan;
5279 break;
5280 case glslang::EOpLessThanEqual:
5281 if (isFloat)
5282 binOp = spv::OpFOrdLessThanEqual;
5283 else if (isUnsigned)
5284 binOp = spv::OpULessThanEqual;
5285 else
5286 binOp = spv::OpSLessThanEqual;
5287 break;
5288 case glslang::EOpGreaterThanEqual:
5289 if (isFloat)
5290 binOp = spv::OpFOrdGreaterThanEqual;
5291 else if (isUnsigned)
5292 binOp = spv::OpUGreaterThanEqual;
5293 else
5294 binOp = spv::OpSGreaterThanEqual;
5295 break;
5296 case glslang::EOpEqual:
5297 case glslang::EOpVectorEqual:
5298 if (isFloat)
5299 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005300 else if (isBool)
5301 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005302 else
5303 binOp = spv::OpIEqual;
5304 break;
5305 case glslang::EOpNotEqual:
5306 case glslang::EOpVectorNotEqual:
5307 if (isFloat)
5308 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005309 else if (isBool)
5310 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005311 else
5312 binOp = spv::OpINotEqual;
5313 break;
5314 default:
5315 break;
5316 }
5317
qining25262b32016-05-06 17:25:16 -04005318 if (binOp != spv::OpNop) {
5319 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005320 decorations.addNoContraction(builder, result);
5321 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005322 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005323 }
John Kessenich140f3df2015-06-26 16:58:36 -06005324
5325 return 0;
5326}
5327
John Kessenich04bb8a02015-12-12 12:28:14 -07005328//
5329// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5330// These can be any of:
5331//
5332// matrix * scalar
5333// scalar * matrix
5334// matrix * matrix linear algebraic
5335// matrix * vector
5336// vector * matrix
5337// matrix * matrix componentwise
5338// matrix op matrix op in {+, -, /}
5339// matrix op scalar op in {+, -, /}
5340// scalar op matrix op in {+, -, /}
5341//
John Kessenichead86222018-03-28 18:01:20 -06005342spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5343 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005344{
5345 bool firstClass = true;
5346
5347 // First, handle first-class matrix operations (* and matrix/scalar)
5348 switch (op) {
5349 case spv::OpFDiv:
5350 if (builder.isMatrix(left) && builder.isScalar(right)) {
5351 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005352 spv::Id resultType = builder.getTypeId(right);
5353 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005354 op = spv::OpMatrixTimesScalar;
5355 } else
5356 firstClass = false;
5357 break;
5358 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005359 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005360 std::swap(left, right);
5361 assert(builder.isScalar(right));
5362 break;
5363 case spv::OpVectorTimesMatrix:
5364 assert(builder.isVector(left));
5365 assert(builder.isMatrix(right));
5366 break;
5367 case spv::OpMatrixTimesVector:
5368 assert(builder.isMatrix(left));
5369 assert(builder.isVector(right));
5370 break;
5371 case spv::OpMatrixTimesMatrix:
5372 assert(builder.isMatrix(left));
5373 assert(builder.isMatrix(right));
5374 break;
5375 default:
5376 firstClass = false;
5377 break;
5378 }
5379
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005380 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5381 firstClass = true;
5382
qining25262b32016-05-06 17:25:16 -04005383 if (firstClass) {
5384 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005385 decorations.addNoContraction(builder, result);
5386 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005387 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005388 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005389
LoopDawg592860c2016-06-09 08:57:35 -06005390 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005391 // The result type of all of them is the same type as the (a) matrix operand.
5392 // The algorithm is to:
5393 // - break the matrix(es) into vectors
5394 // - smear any scalar to a vector
5395 // - do vector operations
5396 // - make a matrix out the vector results
5397 switch (op) {
5398 case spv::OpFAdd:
5399 case spv::OpFSub:
5400 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005401 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005402 case spv::OpFMul:
5403 {
5404 // one time set up...
5405 bool leftMat = builder.isMatrix(left);
5406 bool rightMat = builder.isMatrix(right);
5407 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5408 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5409 spv::Id scalarType = builder.getScalarTypeId(typeId);
5410 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5411 std::vector<spv::Id> results;
5412 spv::Id smearVec = spv::NoResult;
5413 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005414 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005415 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005416 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005417
5418 // do each vector op
5419 for (unsigned int c = 0; c < numCols; ++c) {
5420 std::vector<unsigned int> indexes;
5421 indexes.push_back(c);
5422 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5423 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005424 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005425 decorations.addNoContraction(builder, result);
5426 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005427 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005428 }
5429
5430 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005431 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005432 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005433 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005434 }
5435 default:
5436 assert(0);
5437 return spv::NoResult;
5438 }
5439}
5440
John Kessenichead86222018-03-28 18:01:20 -06005441spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005442 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005443{
5444 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005445 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005446 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005447 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5448 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005449
5450 switch (op) {
5451 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005452 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005453 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005454 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005455 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005456 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005457 unaryOp = spv::OpSNegate;
5458 break;
5459
5460 case glslang::EOpLogicalNot:
5461 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005462 unaryOp = spv::OpLogicalNot;
5463 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005464 case glslang::EOpBitwiseNot:
5465 unaryOp = spv::OpNot;
5466 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005467
John Kessenich140f3df2015-06-26 16:58:36 -06005468 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005469 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005470 break;
5471 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005472 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005473 break;
5474 case glslang::EOpTranspose:
5475 unaryOp = spv::OpTranspose;
5476 break;
5477
5478 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005479 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005482 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005483 break;
5484 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005488 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 break;
5490 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005491 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005492 break;
5493 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005494 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 break;
5496 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005497 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005498 break;
5499 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005500 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005501 break;
5502
5503 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
5506 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005507 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005508 break;
5509 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005510 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005511 break;
5512 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005513 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005514 break;
5515 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005516 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005517 break;
5518 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005519 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005520 break;
5521
5522 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005523 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 break;
5525 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005526 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005527 break;
5528
5529 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005530 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005531 break;
5532 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005533 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005534 break;
5535 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005536 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005537 break;
5538 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005539 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005540 break;
5541 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005542 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005543 break;
5544 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005545 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005546 break;
5547
5548 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005549 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005550 break;
5551 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005552 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005553 break;
5554 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005555 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005556 break;
5557 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005558 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005559 break;
5560 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005561 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005562 break;
5563 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005564 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005565 break;
5566
5567 case glslang::EOpIsNan:
5568 unaryOp = spv::OpIsNan;
5569 break;
5570 case glslang::EOpIsInf:
5571 unaryOp = spv::OpIsInf;
5572 break;
LoopDawg592860c2016-06-09 08:57:35 -06005573 case glslang::EOpIsFinite:
5574 unaryOp = spv::OpIsFinite;
5575 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005576
Rex Xucbc426e2015-12-15 16:03:10 +08005577 case glslang::EOpFloatBitsToInt:
5578 case glslang::EOpFloatBitsToUint:
5579 case glslang::EOpIntBitsToFloat:
5580 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005581 case glslang::EOpDoubleBitsToInt64:
5582 case glslang::EOpDoubleBitsToUint64:
5583 case glslang::EOpInt64BitsToDouble:
5584 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005585 case glslang::EOpFloat16BitsToInt16:
5586 case glslang::EOpFloat16BitsToUint16:
5587 case glslang::EOpInt16BitsToFloat16:
5588 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005589 unaryOp = spv::OpBitcast;
5590 break;
5591
John Kessenich140f3df2015-06-26 16:58:36 -06005592 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005593 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005594 break;
5595 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005596 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005597 break;
5598 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005599 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005600 break;
5601 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005602 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005603 break;
5604 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005605 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005606 break;
5607 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005608 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005609 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005610#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005611 case glslang::EOpPackSnorm4x8:
5612 libCall = spv::GLSLstd450PackSnorm4x8;
5613 break;
5614 case glslang::EOpUnpackSnorm4x8:
5615 libCall = spv::GLSLstd450UnpackSnorm4x8;
5616 break;
5617 case glslang::EOpPackUnorm4x8:
5618 libCall = spv::GLSLstd450PackUnorm4x8;
5619 break;
5620 case glslang::EOpUnpackUnorm4x8:
5621 libCall = spv::GLSLstd450UnpackUnorm4x8;
5622 break;
5623 case glslang::EOpPackDouble2x32:
5624 libCall = spv::GLSLstd450PackDouble2x32;
5625 break;
5626 case glslang::EOpUnpackDouble2x32:
5627 libCall = spv::GLSLstd450UnpackDouble2x32;
5628 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005629#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005630
Rex Xu8ff43de2016-04-22 16:51:45 +08005631 case glslang::EOpPackInt2x32:
5632 case glslang::EOpUnpackInt2x32:
5633 case glslang::EOpPackUint2x32:
5634 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005635 case glslang::EOpPack16:
5636 case glslang::EOpPack32:
5637 case glslang::EOpPack64:
5638 case glslang::EOpUnpack32:
5639 case glslang::EOpUnpack16:
5640 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005641 case glslang::EOpPackInt2x16:
5642 case glslang::EOpUnpackInt2x16:
5643 case glslang::EOpPackUint2x16:
5644 case glslang::EOpUnpackUint2x16:
5645 case glslang::EOpPackInt4x16:
5646 case glslang::EOpUnpackInt4x16:
5647 case glslang::EOpPackUint4x16:
5648 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005649 case glslang::EOpPackFloat2x16:
5650 case glslang::EOpUnpackFloat2x16:
5651 unaryOp = spv::OpBitcast;
5652 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005653
John Kessenich140f3df2015-06-26 16:58:36 -06005654 case glslang::EOpDPdx:
5655 unaryOp = spv::OpDPdx;
5656 break;
5657 case glslang::EOpDPdy:
5658 unaryOp = spv::OpDPdy;
5659 break;
5660 case glslang::EOpFwidth:
5661 unaryOp = spv::OpFwidth;
5662 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005663
John Kessenich140f3df2015-06-26 16:58:36 -06005664 case glslang::EOpAny:
5665 unaryOp = spv::OpAny;
5666 break;
5667 case glslang::EOpAll:
5668 unaryOp = spv::OpAll;
5669 break;
5670
5671 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005672 if (isFloat)
5673 libCall = spv::GLSLstd450FAbs;
5674 else
5675 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005676 break;
5677 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005678 if (isFloat)
5679 libCall = spv::GLSLstd450FSign;
5680 else
5681 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005682 break;
5683
John Kessenicha28f7a72019-08-06 07:00:58 -06005684#ifndef GLSLANG_WEB
5685 case glslang::EOpDPdxFine:
5686 unaryOp = spv::OpDPdxFine;
5687 break;
5688 case glslang::EOpDPdyFine:
5689 unaryOp = spv::OpDPdyFine;
5690 break;
5691 case glslang::EOpFwidthFine:
5692 unaryOp = spv::OpFwidthFine;
5693 break;
5694 case glslang::EOpDPdxCoarse:
5695 unaryOp = spv::OpDPdxCoarse;
5696 break;
5697 case glslang::EOpDPdyCoarse:
5698 unaryOp = spv::OpDPdyCoarse;
5699 break;
5700 case glslang::EOpFwidthCoarse:
5701 unaryOp = spv::OpFwidthCoarse;
5702 break;
5703 case glslang::EOpInterpolateAtCentroid:
5704 if (typeProxy == glslang::EbtFloat16)
5705 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5706 libCall = spv::GLSLstd450InterpolateAtCentroid;
5707 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005708 case glslang::EOpAtomicCounterIncrement:
5709 case glslang::EOpAtomicCounterDecrement:
5710 case glslang::EOpAtomicCounter:
5711 {
5712 // Handle all of the atomics in one place, in createAtomicOperation()
5713 std::vector<spv::Id> operands;
5714 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005715 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005716 }
5717
John Kessenichfc51d282015-08-19 13:34:18 -06005718 case glslang::EOpBitFieldReverse:
5719 unaryOp = spv::OpBitReverse;
5720 break;
5721 case glslang::EOpBitCount:
5722 unaryOp = spv::OpBitCount;
5723 break;
5724 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005725 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005726 break;
5727 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005728 if (isUnsigned)
5729 libCall = spv::GLSLstd450FindUMsb;
5730 else
5731 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005732 break;
5733
Rex Xu574ab042016-04-14 16:53:07 +08005734 case glslang::EOpBallot:
5735 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005736 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005737 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005738 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005739 case glslang::EOpMinInvocations:
5740 case glslang::EOpMaxInvocations:
5741 case glslang::EOpAddInvocations:
5742 case glslang::EOpMinInvocationsNonUniform:
5743 case glslang::EOpMaxInvocationsNonUniform:
5744 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005745 case glslang::EOpMinInvocationsInclusiveScan:
5746 case glslang::EOpMaxInvocationsInclusiveScan:
5747 case glslang::EOpAddInvocationsInclusiveScan:
5748 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5749 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5750 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5751 case glslang::EOpMinInvocationsExclusiveScan:
5752 case glslang::EOpMaxInvocationsExclusiveScan:
5753 case glslang::EOpAddInvocationsExclusiveScan:
5754 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5755 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5756 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005757 {
5758 std::vector<spv::Id> operands;
5759 operands.push_back(operand);
5760 return createInvocationsOperation(op, typeId, operands, typeProxy);
5761 }
John Kessenich66011cb2018-03-06 16:12:04 -07005762 case glslang::EOpSubgroupAll:
5763 case glslang::EOpSubgroupAny:
5764 case glslang::EOpSubgroupAllEqual:
5765 case glslang::EOpSubgroupBroadcastFirst:
5766 case glslang::EOpSubgroupBallot:
5767 case glslang::EOpSubgroupInverseBallot:
5768 case glslang::EOpSubgroupBallotBitCount:
5769 case glslang::EOpSubgroupBallotInclusiveBitCount:
5770 case glslang::EOpSubgroupBallotExclusiveBitCount:
5771 case glslang::EOpSubgroupBallotFindLSB:
5772 case glslang::EOpSubgroupBallotFindMSB:
5773 case glslang::EOpSubgroupAdd:
5774 case glslang::EOpSubgroupMul:
5775 case glslang::EOpSubgroupMin:
5776 case glslang::EOpSubgroupMax:
5777 case glslang::EOpSubgroupAnd:
5778 case glslang::EOpSubgroupOr:
5779 case glslang::EOpSubgroupXor:
5780 case glslang::EOpSubgroupInclusiveAdd:
5781 case glslang::EOpSubgroupInclusiveMul:
5782 case glslang::EOpSubgroupInclusiveMin:
5783 case glslang::EOpSubgroupInclusiveMax:
5784 case glslang::EOpSubgroupInclusiveAnd:
5785 case glslang::EOpSubgroupInclusiveOr:
5786 case glslang::EOpSubgroupInclusiveXor:
5787 case glslang::EOpSubgroupExclusiveAdd:
5788 case glslang::EOpSubgroupExclusiveMul:
5789 case glslang::EOpSubgroupExclusiveMin:
5790 case glslang::EOpSubgroupExclusiveMax:
5791 case glslang::EOpSubgroupExclusiveAnd:
5792 case glslang::EOpSubgroupExclusiveOr:
5793 case glslang::EOpSubgroupExclusiveXor:
5794 case glslang::EOpSubgroupQuadSwapHorizontal:
5795 case glslang::EOpSubgroupQuadSwapVertical:
5796 case glslang::EOpSubgroupQuadSwapDiagonal: {
5797 std::vector<spv::Id> operands;
5798 operands.push_back(operand);
5799 return createSubgroupOperation(op, typeId, operands, typeProxy);
5800 }
Rex Xu9d93a232016-05-05 12:30:44 +08005801 case glslang::EOpMbcnt:
5802 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5803 libCall = spv::MbcntAMD;
5804 break;
5805
5806 case glslang::EOpCubeFaceIndex:
5807 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5808 libCall = spv::CubeFaceIndexAMD;
5809 break;
5810
5811 case glslang::EOpCubeFaceCoord:
5812 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5813 libCall = spv::CubeFaceCoordAMD;
5814 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005815 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005816 unaryOp = spv::OpGroupNonUniformPartitionNV;
5817 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005818 case glslang::EOpConstructReference:
5819 unaryOp = spv::OpBitcast;
5820 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005821#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005822
5823 case glslang::EOpCopyObject:
5824 unaryOp = spv::OpCopyObject;
5825 break;
5826
John Kessenich140f3df2015-06-26 16:58:36 -06005827 default:
5828 return 0;
5829 }
5830
5831 spv::Id id;
5832 if (libCall >= 0) {
5833 std::vector<spv::Id> args;
5834 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005835 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005836 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005837 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005838 }
John Kessenich140f3df2015-06-26 16:58:36 -06005839
John Kessenichb9197c82019-08-11 07:41:45 -06005840 decorations.addNoContraction(builder, id);
5841 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005842 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005843}
5844
John Kessenich7a53f762016-01-20 11:19:27 -07005845// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005846spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5847 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005848{
5849 // Handle unary operations vector by vector.
5850 // The result type is the same type as the original type.
5851 // The algorithm is to:
5852 // - break the matrix into vectors
5853 // - apply the operation to each vector
5854 // - make a matrix out the vector results
5855
5856 // get the types sorted out
5857 int numCols = builder.getNumColumns(operand);
5858 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005859 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5860 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005861 std::vector<spv::Id> results;
5862
5863 // do each vector op
5864 for (int c = 0; c < numCols; ++c) {
5865 std::vector<unsigned int> indexes;
5866 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005867 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5868 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005869 decorations.addNoContraction(builder, destVec);
5870 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005871 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005872 }
5873
5874 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005875 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005876 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005877 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005878}
5879
John Kessenichad7645f2018-06-04 19:11:25 -06005880// For converting integers where both the bitwidth and the signedness could
5881// change, but only do the width change here. The caller is still responsible
5882// for the signedness conversion.
5883spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005884{
John Kessenichad7645f2018-06-04 19:11:25 -06005885 // Get the result type width, based on the type to convert to.
5886 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005887 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005888 case glslang::EOpConvInt16ToUint8:
5889 case glslang::EOpConvIntToUint8:
5890 case glslang::EOpConvInt64ToUint8:
5891 case glslang::EOpConvUint16ToInt8:
5892 case glslang::EOpConvUintToInt8:
5893 case glslang::EOpConvUint64ToInt8:
5894 width = 8;
5895 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005896 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005897 case glslang::EOpConvIntToUint16:
5898 case glslang::EOpConvInt64ToUint16:
5899 case glslang::EOpConvUint8ToInt16:
5900 case glslang::EOpConvUintToInt16:
5901 case glslang::EOpConvUint64ToInt16:
5902 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005903 break;
5904 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005905 case glslang::EOpConvInt16ToUint:
5906 case glslang::EOpConvInt64ToUint:
5907 case glslang::EOpConvUint8ToInt:
5908 case glslang::EOpConvUint16ToInt:
5909 case glslang::EOpConvUint64ToInt:
5910 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005911 break;
5912 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005913 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005914 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005915 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005916 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005917 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005918 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005919 break;
5920
5921 default:
5922 assert(false && "Default missing");
5923 break;
5924 }
5925
John Kessenichad7645f2018-06-04 19:11:25 -06005926 // Get the conversion operation and result type,
5927 // based on the target width, but the source type.
5928 spv::Id type = spv::NoType;
5929 spv::Op convOp = spv::OpNop;
5930 switch(op) {
5931 case glslang::EOpConvInt8ToUint16:
5932 case glslang::EOpConvInt8ToUint:
5933 case glslang::EOpConvInt8ToUint64:
5934 case glslang::EOpConvInt16ToUint8:
5935 case glslang::EOpConvInt16ToUint:
5936 case glslang::EOpConvInt16ToUint64:
5937 case glslang::EOpConvIntToUint8:
5938 case glslang::EOpConvIntToUint16:
5939 case glslang::EOpConvIntToUint64:
5940 case glslang::EOpConvInt64ToUint8:
5941 case glslang::EOpConvInt64ToUint16:
5942 case glslang::EOpConvInt64ToUint:
5943 convOp = spv::OpSConvert;
5944 type = builder.makeIntType(width);
5945 break;
5946 default:
5947 convOp = spv::OpUConvert;
5948 type = builder.makeUintType(width);
5949 break;
5950 }
5951
John Kessenich66011cb2018-03-06 16:12:04 -07005952 if (vectorSize > 0)
5953 type = builder.makeVectorType(type, vectorSize);
5954
John Kessenichad7645f2018-06-04 19:11:25 -06005955 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005956}
5957
John Kessenichead86222018-03-28 18:01:20 -06005958spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5959 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005960{
5961 spv::Op convOp = spv::OpNop;
5962 spv::Id zero = 0;
5963 spv::Id one = 0;
5964
5965 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5966
5967 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005968 case glslang::EOpConvIntToBool:
5969 case glslang::EOpConvUintToBool:
5970 zero = builder.makeUintConstant(0);
5971 zero = makeSmearedConstant(zero, vectorSize);
5972 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005973 case glslang::EOpConvFloatToBool:
5974 zero = builder.makeFloatConstant(0.0F);
5975 zero = makeSmearedConstant(zero, vectorSize);
5976 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005977 case glslang::EOpConvBoolToFloat:
5978 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005979 zero = builder.makeFloatConstant(0.0F);
5980 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005981 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005982
John Kessenich140f3df2015-06-26 16:58:36 -06005983 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005984 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06005985#ifndef GLSLANG_WEB
5986 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08005987 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005988 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005989 } else
5990#endif
5991 {
5992 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005993 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005994 }
Rex Xucabbb782017-03-24 13:41:14 +08005995
John Kessenich140f3df2015-06-26 16:58:36 -06005996 convOp = spv::OpSelect;
5997 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005998
John Kessenich140f3df2015-06-26 16:58:36 -06005999 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006000 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006001#ifndef GLSLANG_WEB
6002 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006003 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006004 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006005 } else
6006#endif
6007 {
6008 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006009 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006010 }
Rex Xucabbb782017-03-24 13:41:14 +08006011
John Kessenich140f3df2015-06-26 16:58:36 -06006012 convOp = spv::OpSelect;
6013 break;
6014
John Kessenich66011cb2018-03-06 16:12:04 -07006015 case glslang::EOpConvInt8ToFloat16:
6016 case glslang::EOpConvInt8ToFloat:
6017 case glslang::EOpConvInt8ToDouble:
6018 case glslang::EOpConvInt16ToFloat16:
6019 case glslang::EOpConvInt16ToFloat:
6020 case glslang::EOpConvInt16ToDouble:
6021 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006022 case glslang::EOpConvIntToFloat:
6023 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006024 case glslang::EOpConvInt64ToFloat:
6025 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006026 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006027 convOp = spv::OpConvertSToF;
6028 break;
6029
John Kessenich66011cb2018-03-06 16:12:04 -07006030 case glslang::EOpConvUint8ToFloat16:
6031 case glslang::EOpConvUint8ToFloat:
6032 case glslang::EOpConvUint8ToDouble:
6033 case glslang::EOpConvUint16ToFloat16:
6034 case glslang::EOpConvUint16ToFloat:
6035 case glslang::EOpConvUint16ToDouble:
6036 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006037 case glslang::EOpConvUintToFloat:
6038 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006039 case glslang::EOpConvUint64ToFloat:
6040 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006041 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006042 convOp = spv::OpConvertUToF;
6043 break;
6044
John Kessenich66011cb2018-03-06 16:12:04 -07006045 case glslang::EOpConvFloat16ToInt8:
6046 case glslang::EOpConvFloatToInt8:
6047 case glslang::EOpConvDoubleToInt8:
6048 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006049 case glslang::EOpConvFloatToInt16:
6050 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006051 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006052 case glslang::EOpConvFloatToInt:
6053 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006054 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006055 case glslang::EOpConvFloatToInt64:
6056 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006057 convOp = spv::OpConvertFToS;
6058 break;
6059
John Kessenich66011cb2018-03-06 16:12:04 -07006060 case glslang::EOpConvUint8ToInt8:
6061 case glslang::EOpConvInt8ToUint8:
6062 case glslang::EOpConvUint16ToInt16:
6063 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006064 case glslang::EOpConvUintToInt:
6065 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006066 case glslang::EOpConvUint64ToInt64:
6067 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006068 if (builder.isInSpecConstCodeGenMode()) {
6069 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006070#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006071 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6072 zero = builder.makeUint8Constant(0);
6073 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006074 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006075 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6076 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006077 } else
6078#endif
6079 {
Rex Xucabbb782017-03-24 13:41:14 +08006080 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006081 }
qining189b2032016-04-12 23:16:20 -04006082 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006083 // Use OpIAdd, instead of OpBitcast to do the conversion when
6084 // generating for OpSpecConstantOp instruction.
6085 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6086 }
6087 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006088 convOp = spv::OpBitcast;
6089 break;
6090
John Kessenich66011cb2018-03-06 16:12:04 -07006091 case glslang::EOpConvFloat16ToUint8:
6092 case glslang::EOpConvFloatToUint8:
6093 case glslang::EOpConvDoubleToUint8:
6094 case glslang::EOpConvFloat16ToUint16:
6095 case glslang::EOpConvFloatToUint16:
6096 case glslang::EOpConvDoubleToUint16:
6097 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006098 case glslang::EOpConvFloatToUint:
6099 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006100 case glslang::EOpConvFloatToUint64:
6101 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006102 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006103 convOp = spv::OpConvertFToU;
6104 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006105
John Kessenich39697cd2019-08-08 10:35:51 -06006106#ifndef GLSLANG_WEB
6107 case glslang::EOpConvInt8ToBool:
6108 case glslang::EOpConvUint8ToBool:
6109 zero = builder.makeUint8Constant(0);
6110 zero = makeSmearedConstant(zero, vectorSize);
6111 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6112 case glslang::EOpConvInt16ToBool:
6113 case glslang::EOpConvUint16ToBool:
6114 zero = builder.makeUint16Constant(0);
6115 zero = makeSmearedConstant(zero, vectorSize);
6116 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6117 case glslang::EOpConvInt64ToBool:
6118 case glslang::EOpConvUint64ToBool:
6119 zero = builder.makeUint64Constant(0);
6120 zero = makeSmearedConstant(zero, vectorSize);
6121 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6122 case glslang::EOpConvDoubleToBool:
6123 zero = builder.makeDoubleConstant(0.0);
6124 zero = makeSmearedConstant(zero, vectorSize);
6125 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6126 case glslang::EOpConvFloat16ToBool:
6127 zero = builder.makeFloat16Constant(0.0F);
6128 zero = makeSmearedConstant(zero, vectorSize);
6129 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6130 case glslang::EOpConvBoolToDouble:
6131 convOp = spv::OpSelect;
6132 zero = builder.makeDoubleConstant(0.0);
6133 one = builder.makeDoubleConstant(1.0);
6134 break;
6135 case glslang::EOpConvBoolToFloat16:
6136 convOp = spv::OpSelect;
6137 zero = builder.makeFloat16Constant(0.0F);
6138 one = builder.makeFloat16Constant(1.0F);
6139 break;
6140 case glslang::EOpConvBoolToInt8:
6141 zero = builder.makeInt8Constant(0);
6142 one = builder.makeInt8Constant(1);
6143 convOp = spv::OpSelect;
6144 break;
6145 case glslang::EOpConvBoolToUint8:
6146 zero = builder.makeUint8Constant(0);
6147 one = builder.makeUint8Constant(1);
6148 convOp = spv::OpSelect;
6149 break;
6150 case glslang::EOpConvBoolToInt16:
6151 zero = builder.makeInt16Constant(0);
6152 one = builder.makeInt16Constant(1);
6153 convOp = spv::OpSelect;
6154 break;
6155 case glslang::EOpConvBoolToUint16:
6156 zero = builder.makeUint16Constant(0);
6157 one = builder.makeUint16Constant(1);
6158 convOp = spv::OpSelect;
6159 break;
6160 case glslang::EOpConvDoubleToFloat:
6161 case glslang::EOpConvFloatToDouble:
6162 case glslang::EOpConvDoubleToFloat16:
6163 case glslang::EOpConvFloat16ToDouble:
6164 case glslang::EOpConvFloatToFloat16:
6165 case glslang::EOpConvFloat16ToFloat:
6166 convOp = spv::OpFConvert;
6167 if (builder.isMatrixType(destType))
6168 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6169 break;
6170
John Kessenich66011cb2018-03-06 16:12:04 -07006171 case glslang::EOpConvInt8ToInt16:
6172 case glslang::EOpConvInt8ToInt:
6173 case glslang::EOpConvInt8ToInt64:
6174 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006175 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006176 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006177 case glslang::EOpConvIntToInt8:
6178 case glslang::EOpConvIntToInt16:
6179 case glslang::EOpConvIntToInt64:
6180 case glslang::EOpConvInt64ToInt8:
6181 case glslang::EOpConvInt64ToInt16:
6182 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006183 convOp = spv::OpSConvert;
6184 break;
6185
John Kessenich66011cb2018-03-06 16:12:04 -07006186 case glslang::EOpConvUint8ToUint16:
6187 case glslang::EOpConvUint8ToUint:
6188 case glslang::EOpConvUint8ToUint64:
6189 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006190 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006191 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006192 case glslang::EOpConvUintToUint8:
6193 case glslang::EOpConvUintToUint16:
6194 case glslang::EOpConvUintToUint64:
6195 case glslang::EOpConvUint64ToUint8:
6196 case glslang::EOpConvUint64ToUint16:
6197 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006198 convOp = spv::OpUConvert;
6199 break;
6200
John Kessenich66011cb2018-03-06 16:12:04 -07006201 case glslang::EOpConvInt8ToUint16:
6202 case glslang::EOpConvInt8ToUint:
6203 case glslang::EOpConvInt8ToUint64:
6204 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006205 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006206 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006207 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006208 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006209 case glslang::EOpConvIntToUint64:
6210 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006211 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006212 case glslang::EOpConvInt64ToUint:
6213 case glslang::EOpConvUint8ToInt16:
6214 case glslang::EOpConvUint8ToInt:
6215 case glslang::EOpConvUint8ToInt64:
6216 case glslang::EOpConvUint16ToInt8:
6217 case glslang::EOpConvUint16ToInt:
6218 case glslang::EOpConvUint16ToInt64:
6219 case glslang::EOpConvUintToInt8:
6220 case glslang::EOpConvUintToInt16:
6221 case glslang::EOpConvUintToInt64:
6222 case glslang::EOpConvUint64ToInt8:
6223 case glslang::EOpConvUint64ToInt16:
6224 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006225 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006226 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006227
6228 if (builder.isInSpecConstCodeGenMode()) {
6229 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006230 switch(op) {
6231 case glslang::EOpConvInt16ToUint8:
6232 case glslang::EOpConvIntToUint8:
6233 case glslang::EOpConvInt64ToUint8:
6234 case glslang::EOpConvUint16ToInt8:
6235 case glslang::EOpConvUintToInt8:
6236 case glslang::EOpConvUint64ToInt8:
6237 zero = builder.makeUint8Constant(0);
6238 break;
6239 case glslang::EOpConvInt8ToUint16:
6240 case glslang::EOpConvIntToUint16:
6241 case glslang::EOpConvInt64ToUint16:
6242 case glslang::EOpConvUint8ToInt16:
6243 case glslang::EOpConvUintToInt16:
6244 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006245 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006246 break;
6247 case glslang::EOpConvInt8ToUint:
6248 case glslang::EOpConvInt16ToUint:
6249 case glslang::EOpConvInt64ToUint:
6250 case glslang::EOpConvUint8ToInt:
6251 case glslang::EOpConvUint16ToInt:
6252 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006253 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006254 break;
6255 case glslang::EOpConvInt8ToUint64:
6256 case glslang::EOpConvInt16ToUint64:
6257 case glslang::EOpConvIntToUint64:
6258 case glslang::EOpConvUint8ToInt64:
6259 case glslang::EOpConvUint16ToInt64:
6260 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006261 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006262 break;
6263 default:
6264 assert(false && "Default missing");
6265 break;
6266 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006267 zero = makeSmearedConstant(zero, vectorSize);
6268 // Use OpIAdd, instead of OpBitcast to do the conversion when
6269 // generating for OpSpecConstantOp instruction.
6270 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6271 }
6272 // For normal run-time conversion instruction, use OpBitcast.
6273 convOp = spv::OpBitcast;
6274 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006275 case glslang::EOpConvUint64ToPtr:
6276 convOp = spv::OpConvertUToPtr;
6277 break;
6278 case glslang::EOpConvPtrToUint64:
6279 convOp = spv::OpConvertPtrToU;
6280 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006281#endif
6282
John Kessenich140f3df2015-06-26 16:58:36 -06006283 default:
6284 break;
6285 }
6286
6287 spv::Id result = 0;
6288 if (convOp == spv::OpNop)
6289 return result;
6290
6291 if (convOp == spv::OpSelect) {
6292 zero = makeSmearedConstant(zero, vectorSize);
6293 one = makeSmearedConstant(one, vectorSize);
6294 result = builder.createTriOp(convOp, destType, operand, one, zero);
6295 } else
6296 result = builder.createUnaryOp(convOp, destType, operand);
6297
John Kessenichead86222018-03-28 18:01:20 -06006298 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006299 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006300 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006301}
6302
6303spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6304{
6305 if (vectorSize == 0)
6306 return constant;
6307
6308 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6309 std::vector<spv::Id> components;
6310 for (int c = 0; c < vectorSize; ++c)
6311 components.push_back(constant);
6312 return builder.makeCompositeConstant(vectorTypeId, components);
6313}
6314
John Kessenich426394d2015-07-23 10:22:48 -06006315// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006316spv::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 -06006317{
6318 spv::Op opCode = spv::OpNop;
6319
6320 switch (op) {
6321 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006322 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006323 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006324 opCode = spv::OpAtomicIAdd;
6325 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006326 case glslang::EOpAtomicCounterSubtract:
6327 opCode = spv::OpAtomicISub;
6328 break;
John Kessenich426394d2015-07-23 10:22:48 -06006329 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006330 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006331 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006332 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006333 break;
6334 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006335 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006336 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006337 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006338 break;
6339 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006340 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006341 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006342 opCode = spv::OpAtomicAnd;
6343 break;
6344 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006345 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006346 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006347 opCode = spv::OpAtomicOr;
6348 break;
6349 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006350 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006351 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006352 opCode = spv::OpAtomicXor;
6353 break;
6354 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006355 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006356 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006357 opCode = spv::OpAtomicExchange;
6358 break;
6359 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006360 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006361 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006362 opCode = spv::OpAtomicCompareExchange;
6363 break;
6364 case glslang::EOpAtomicCounterIncrement:
6365 opCode = spv::OpAtomicIIncrement;
6366 break;
6367 case glslang::EOpAtomicCounterDecrement:
6368 opCode = spv::OpAtomicIDecrement;
6369 break;
6370 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006371 case glslang::EOpImageAtomicLoad:
6372 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006373 opCode = spv::OpAtomicLoad;
6374 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006375 case glslang::EOpAtomicStore:
6376 case glslang::EOpImageAtomicStore:
6377 opCode = spv::OpAtomicStore;
6378 break;
John Kessenich426394d2015-07-23 10:22:48 -06006379 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006380 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006381 break;
6382 }
6383
Rex Xue8fe8b02017-09-26 15:42:56 +08006384 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6385 builder.addCapability(spv::CapabilityInt64Atomics);
6386
John Kessenich426394d2015-07-23 10:22:48 -06006387 // Sort out the operands
6388 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006389 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006390 // - compare-exchange swaps the value and comparator
6391 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006392 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006393 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6394 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6395 spv::Id scopeId;
6396 if (glslangIntermediate->usingVulkanMemoryModel()) {
6397 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6398 } else {
6399 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6400 }
6401 // semantics default to relaxed
John Kessenichb9197c82019-08-11 07:41:45 -06006402 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() ?
6403 spv::MemorySemanticsVolatileMask :
6404 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006405 spv::Id semanticsId2 = semanticsId;
6406
6407 pointerId = operands[0];
6408 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6409 // no additional operands
6410 } else if (opCode == spv::OpAtomicCompareExchange) {
6411 compareId = operands[1];
6412 valueId = operands[2];
6413 if (operands.size() > 3) {
6414 scopeId = operands[3];
6415 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6416 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6417 }
6418 } else if (opCode == spv::OpAtomicLoad) {
6419 if (operands.size() > 1) {
6420 scopeId = operands[1];
6421 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6422 }
6423 } else {
6424 // atomic store or RMW
6425 valueId = operands[1];
6426 if (operands.size() > 2) {
6427 scopeId = operands[2];
6428 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6429 }
Rex Xu04db3f52015-09-16 11:44:02 +08006430 }
John Kessenich426394d2015-07-23 10:22:48 -06006431
Jeff Bolz36831c92018-09-05 10:11:41 -05006432 // Check for capabilities
6433 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006434 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6435 spv::MemorySemanticsMakeVisibleKHRMask |
6436 spv::MemorySemanticsOutputMemoryKHRMask |
6437 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006438 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6439 }
John Kessenich426394d2015-07-23 10:22:48 -06006440
Jeff Bolz36831c92018-09-05 10:11:41 -05006441 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6442 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6443 }
John Kessenich48d6e792017-10-06 21:21:48 -06006444
Jeff Bolz36831c92018-09-05 10:11:41 -05006445 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6446 spvAtomicOperands.push_back(pointerId);
6447 spvAtomicOperands.push_back(scopeId);
6448 spvAtomicOperands.push_back(semanticsId);
6449 if (opCode == spv::OpAtomicCompareExchange) {
6450 spvAtomicOperands.push_back(semanticsId2);
6451 spvAtomicOperands.push_back(valueId);
6452 spvAtomicOperands.push_back(compareId);
6453 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6454 spvAtomicOperands.push_back(valueId);
6455 }
John Kessenich48d6e792017-10-06 21:21:48 -06006456
Jeff Bolz36831c92018-09-05 10:11:41 -05006457 if (opCode == spv::OpAtomicStore) {
6458 builder.createNoResultOp(opCode, spvAtomicOperands);
6459 return 0;
6460 } else {
6461 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6462
6463 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6464 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6465 if (op == glslang::EOpAtomicCounterDecrement)
6466 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6467
6468 return resultId;
6469 }
John Kessenich426394d2015-07-23 10:22:48 -06006470}
6471
John Kessenich91cef522016-05-05 16:45:40 -06006472// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006473spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006474{
John Kessenich66011cb2018-03-06 16:12:04 -07006475 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6476 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006477
Rex Xu51596642016-09-21 18:56:12 +08006478 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006479 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006480 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6481
chaocf200da82016-12-20 12:44:35 -08006482 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6483 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006484 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6485 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006486 } else if (op == glslang::EOpAnyInvocation ||
6487 op == glslang::EOpAllInvocations ||
6488 op == glslang::EOpAllInvocationsEqual) {
6489 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6490 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006491 } else {
6492 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006493 if (op == glslang::EOpMinInvocationsNonUniform ||
6494 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006495 op == glslang::EOpAddInvocationsNonUniform ||
6496 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6497 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6498 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6499 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6500 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6501 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006502 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006503
Rex Xu430ef402016-10-14 17:22:23 +08006504 switch (op) {
6505 case glslang::EOpMinInvocations:
6506 case glslang::EOpMaxInvocations:
6507 case glslang::EOpAddInvocations:
6508 case glslang::EOpMinInvocationsNonUniform:
6509 case glslang::EOpMaxInvocationsNonUniform:
6510 case glslang::EOpAddInvocationsNonUniform:
6511 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006512 break;
6513 case glslang::EOpMinInvocationsInclusiveScan:
6514 case glslang::EOpMaxInvocationsInclusiveScan:
6515 case glslang::EOpAddInvocationsInclusiveScan:
6516 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6517 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6518 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6519 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006520 break;
6521 case glslang::EOpMinInvocationsExclusiveScan:
6522 case glslang::EOpMaxInvocationsExclusiveScan:
6523 case glslang::EOpAddInvocationsExclusiveScan:
6524 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6525 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6526 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6527 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006528 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006529 default:
6530 break;
Rex Xu430ef402016-10-14 17:22:23 +08006531 }
John Kessenich149afc32018-08-14 13:31:43 -06006532 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6533 spvGroupOperands.push_back(scope);
6534 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006535 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006536 spvGroupOperands.push_back(groupOp);
6537 }
Rex Xu51596642016-09-21 18:56:12 +08006538 }
6539
John Kessenich149afc32018-08-14 13:31:43 -06006540 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6541 spv::IdImmediate op = { true, *opIt };
6542 spvGroupOperands.push_back(op);
6543 }
John Kessenich91cef522016-05-05 16:45:40 -06006544
6545 switch (op) {
6546 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006547 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006548 break;
John Kessenich91cef522016-05-05 16:45:40 -06006549 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006550 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006551 break;
John Kessenich91cef522016-05-05 16:45:40 -06006552 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006553 opCode = spv::OpSubgroupAllEqualKHR;
6554 break;
Rex Xu51596642016-09-21 18:56:12 +08006555 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006556 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006557 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006558 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006559 break;
6560 case glslang::EOpReadFirstInvocation:
6561 opCode = spv::OpSubgroupFirstInvocationKHR;
6562 break;
6563 case glslang::EOpBallot:
6564 {
6565 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6566 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6567 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6568 //
6569 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6570 //
6571 spv::Id uintType = builder.makeUintType(32);
6572 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6573 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6574
6575 std::vector<spv::Id> components;
6576 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6577 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6578
6579 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6580 return builder.createUnaryOp(spv::OpBitcast, typeId,
6581 builder.createCompositeConstruct(uvec2Type, components));
6582 }
6583
Rex Xu9d93a232016-05-05 12:30:44 +08006584 case glslang::EOpMinInvocations:
6585 case glslang::EOpMaxInvocations:
6586 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006587 case glslang::EOpMinInvocationsInclusiveScan:
6588 case glslang::EOpMaxInvocationsInclusiveScan:
6589 case glslang::EOpAddInvocationsInclusiveScan:
6590 case glslang::EOpMinInvocationsExclusiveScan:
6591 case glslang::EOpMaxInvocationsExclusiveScan:
6592 case glslang::EOpAddInvocationsExclusiveScan:
6593 if (op == glslang::EOpMinInvocations ||
6594 op == glslang::EOpMinInvocationsInclusiveScan ||
6595 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006596 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006597 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006598 else {
6599 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006600 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006601 else
Rex Xu51596642016-09-21 18:56:12 +08006602 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006603 }
Rex Xu430ef402016-10-14 17:22:23 +08006604 } else if (op == glslang::EOpMaxInvocations ||
6605 op == glslang::EOpMaxInvocationsInclusiveScan ||
6606 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006607 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006608 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006609 else {
6610 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006611 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006612 else
Rex Xu51596642016-09-21 18:56:12 +08006613 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006614 }
6615 } else {
6616 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006617 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006618 else
Rex Xu51596642016-09-21 18:56:12 +08006619 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006620 }
6621
Rex Xu2bbbe062016-08-23 15:41:05 +08006622 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006623 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006624
6625 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006626 case glslang::EOpMinInvocationsNonUniform:
6627 case glslang::EOpMaxInvocationsNonUniform:
6628 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006629 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6630 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6631 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6632 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6633 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6634 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6635 if (op == glslang::EOpMinInvocationsNonUniform ||
6636 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6637 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006638 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006639 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006640 else {
6641 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006642 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006643 else
Rex Xu51596642016-09-21 18:56:12 +08006644 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006645 }
6646 }
Rex Xu430ef402016-10-14 17:22:23 +08006647 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6648 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6649 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006650 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006651 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006652 else {
6653 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006654 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006655 else
Rex Xu51596642016-09-21 18:56:12 +08006656 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006657 }
6658 }
6659 else {
6660 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006661 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006662 else
Rex Xu51596642016-09-21 18:56:12 +08006663 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006664 }
6665
Rex Xu2bbbe062016-08-23 15:41:05 +08006666 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006667 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006668
6669 break;
John Kessenich91cef522016-05-05 16:45:40 -06006670 default:
6671 logger->missingFunctionality("invocation operation");
6672 return spv::NoResult;
6673 }
Rex Xu51596642016-09-21 18:56:12 +08006674
6675 assert(opCode != spv::OpNop);
6676 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006677}
6678
Rex Xu2bbbe062016-08-23 15:41:05 +08006679// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006680spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6681 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006682{
6683 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6684 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006685 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006686 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006687 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6688 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6689 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6690
6691 // Handle group invocation operations scalar by scalar.
6692 // The result type is the same type as the original type.
6693 // The algorithm is to:
6694 // - break the vector into scalars
6695 // - apply the operation to each scalar
6696 // - make a vector out the scalar results
6697
6698 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006699 int numComponents = builder.getNumComponents(operands[0]);
6700 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006701 std::vector<spv::Id> results;
6702
6703 // do each scalar op
6704 for (int comp = 0; comp < numComponents; ++comp) {
6705 std::vector<unsigned int> indexes;
6706 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006707 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6708 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006709 if (op == spv::OpSubgroupReadInvocationKHR) {
6710 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006711 spv::IdImmediate operand = { true, operands[1] };
6712 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006713 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006714 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6715 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006716 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006717 spv::IdImmediate operand = { true, operands[1] };
6718 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006719 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006720 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6721 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006722 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006723 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006724 spvGroupOperands.push_back(scalar);
6725 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006726
Rex Xub7072052016-09-26 15:53:40 +08006727 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006728 }
6729
6730 // put the pieces together
6731 return builder.createCompositeConstruct(typeId, results);
6732}
Rex Xu2bbbe062016-08-23 15:41:05 +08006733
John Kessenich66011cb2018-03-06 16:12:04 -07006734// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006735spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6736 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006737{
6738 // Add the required capabilities.
6739 switch (op) {
6740 case glslang::EOpSubgroupElect:
6741 builder.addCapability(spv::CapabilityGroupNonUniform);
6742 break;
6743 case glslang::EOpSubgroupAll:
6744 case glslang::EOpSubgroupAny:
6745 case glslang::EOpSubgroupAllEqual:
6746 builder.addCapability(spv::CapabilityGroupNonUniform);
6747 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6748 break;
6749 case glslang::EOpSubgroupBroadcast:
6750 case glslang::EOpSubgroupBroadcastFirst:
6751 case glslang::EOpSubgroupBallot:
6752 case glslang::EOpSubgroupInverseBallot:
6753 case glslang::EOpSubgroupBallotBitExtract:
6754 case glslang::EOpSubgroupBallotBitCount:
6755 case glslang::EOpSubgroupBallotInclusiveBitCount:
6756 case glslang::EOpSubgroupBallotExclusiveBitCount:
6757 case glslang::EOpSubgroupBallotFindLSB:
6758 case glslang::EOpSubgroupBallotFindMSB:
6759 builder.addCapability(spv::CapabilityGroupNonUniform);
6760 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6761 break;
6762 case glslang::EOpSubgroupShuffle:
6763 case glslang::EOpSubgroupShuffleXor:
6764 builder.addCapability(spv::CapabilityGroupNonUniform);
6765 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6766 break;
6767 case glslang::EOpSubgroupShuffleUp:
6768 case glslang::EOpSubgroupShuffleDown:
6769 builder.addCapability(spv::CapabilityGroupNonUniform);
6770 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6771 break;
6772 case glslang::EOpSubgroupAdd:
6773 case glslang::EOpSubgroupMul:
6774 case glslang::EOpSubgroupMin:
6775 case glslang::EOpSubgroupMax:
6776 case glslang::EOpSubgroupAnd:
6777 case glslang::EOpSubgroupOr:
6778 case glslang::EOpSubgroupXor:
6779 case glslang::EOpSubgroupInclusiveAdd:
6780 case glslang::EOpSubgroupInclusiveMul:
6781 case glslang::EOpSubgroupInclusiveMin:
6782 case glslang::EOpSubgroupInclusiveMax:
6783 case glslang::EOpSubgroupInclusiveAnd:
6784 case glslang::EOpSubgroupInclusiveOr:
6785 case glslang::EOpSubgroupInclusiveXor:
6786 case glslang::EOpSubgroupExclusiveAdd:
6787 case glslang::EOpSubgroupExclusiveMul:
6788 case glslang::EOpSubgroupExclusiveMin:
6789 case glslang::EOpSubgroupExclusiveMax:
6790 case glslang::EOpSubgroupExclusiveAnd:
6791 case glslang::EOpSubgroupExclusiveOr:
6792 case glslang::EOpSubgroupExclusiveXor:
6793 builder.addCapability(spv::CapabilityGroupNonUniform);
6794 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6795 break;
6796 case glslang::EOpSubgroupClusteredAdd:
6797 case glslang::EOpSubgroupClusteredMul:
6798 case glslang::EOpSubgroupClusteredMin:
6799 case glslang::EOpSubgroupClusteredMax:
6800 case glslang::EOpSubgroupClusteredAnd:
6801 case glslang::EOpSubgroupClusteredOr:
6802 case glslang::EOpSubgroupClusteredXor:
6803 builder.addCapability(spv::CapabilityGroupNonUniform);
6804 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6805 break;
6806 case glslang::EOpSubgroupQuadBroadcast:
6807 case glslang::EOpSubgroupQuadSwapHorizontal:
6808 case glslang::EOpSubgroupQuadSwapVertical:
6809 case glslang::EOpSubgroupQuadSwapDiagonal:
6810 builder.addCapability(spv::CapabilityGroupNonUniform);
6811 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6812 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006813 case glslang::EOpSubgroupPartitionedAdd:
6814 case glslang::EOpSubgroupPartitionedMul:
6815 case glslang::EOpSubgroupPartitionedMin:
6816 case glslang::EOpSubgroupPartitionedMax:
6817 case glslang::EOpSubgroupPartitionedAnd:
6818 case glslang::EOpSubgroupPartitionedOr:
6819 case glslang::EOpSubgroupPartitionedXor:
6820 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6821 case glslang::EOpSubgroupPartitionedInclusiveMul:
6822 case glslang::EOpSubgroupPartitionedInclusiveMin:
6823 case glslang::EOpSubgroupPartitionedInclusiveMax:
6824 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6825 case glslang::EOpSubgroupPartitionedInclusiveOr:
6826 case glslang::EOpSubgroupPartitionedInclusiveXor:
6827 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6828 case glslang::EOpSubgroupPartitionedExclusiveMul:
6829 case glslang::EOpSubgroupPartitionedExclusiveMin:
6830 case glslang::EOpSubgroupPartitionedExclusiveMax:
6831 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6832 case glslang::EOpSubgroupPartitionedExclusiveOr:
6833 case glslang::EOpSubgroupPartitionedExclusiveXor:
6834 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6835 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6836 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006837 default: assert(0 && "Unhandled subgroup operation!");
6838 }
6839
6840 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6841 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6842 const bool isBool = typeProxy == glslang::EbtBool;
6843
6844 spv::Op opCode = spv::OpNop;
6845
6846 // Figure out which opcode to use.
6847 switch (op) {
6848 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6849 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6850 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6851 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6852 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6853 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6854 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6855 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6856 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6857 case glslang::EOpSubgroupBallotBitCount:
6858 case glslang::EOpSubgroupBallotInclusiveBitCount:
6859 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6860 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6861 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6862 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6863 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6864 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6865 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6866 case glslang::EOpSubgroupAdd:
6867 case glslang::EOpSubgroupInclusiveAdd:
6868 case glslang::EOpSubgroupExclusiveAdd:
6869 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006870 case glslang::EOpSubgroupPartitionedAdd:
6871 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6872 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006873 if (isFloat) {
6874 opCode = spv::OpGroupNonUniformFAdd;
6875 } else {
6876 opCode = spv::OpGroupNonUniformIAdd;
6877 }
6878 break;
6879 case glslang::EOpSubgroupMul:
6880 case glslang::EOpSubgroupInclusiveMul:
6881 case glslang::EOpSubgroupExclusiveMul:
6882 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006883 case glslang::EOpSubgroupPartitionedMul:
6884 case glslang::EOpSubgroupPartitionedInclusiveMul:
6885 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006886 if (isFloat) {
6887 opCode = spv::OpGroupNonUniformFMul;
6888 } else {
6889 opCode = spv::OpGroupNonUniformIMul;
6890 }
6891 break;
6892 case glslang::EOpSubgroupMin:
6893 case glslang::EOpSubgroupInclusiveMin:
6894 case glslang::EOpSubgroupExclusiveMin:
6895 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006896 case glslang::EOpSubgroupPartitionedMin:
6897 case glslang::EOpSubgroupPartitionedInclusiveMin:
6898 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006899 if (isFloat) {
6900 opCode = spv::OpGroupNonUniformFMin;
6901 } else if (isUnsigned) {
6902 opCode = spv::OpGroupNonUniformUMin;
6903 } else {
6904 opCode = spv::OpGroupNonUniformSMin;
6905 }
6906 break;
6907 case glslang::EOpSubgroupMax:
6908 case glslang::EOpSubgroupInclusiveMax:
6909 case glslang::EOpSubgroupExclusiveMax:
6910 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006911 case glslang::EOpSubgroupPartitionedMax:
6912 case glslang::EOpSubgroupPartitionedInclusiveMax:
6913 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006914 if (isFloat) {
6915 opCode = spv::OpGroupNonUniformFMax;
6916 } else if (isUnsigned) {
6917 opCode = spv::OpGroupNonUniformUMax;
6918 } else {
6919 opCode = spv::OpGroupNonUniformSMax;
6920 }
6921 break;
6922 case glslang::EOpSubgroupAnd:
6923 case glslang::EOpSubgroupInclusiveAnd:
6924 case glslang::EOpSubgroupExclusiveAnd:
6925 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006926 case glslang::EOpSubgroupPartitionedAnd:
6927 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6928 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006929 if (isBool) {
6930 opCode = spv::OpGroupNonUniformLogicalAnd;
6931 } else {
6932 opCode = spv::OpGroupNonUniformBitwiseAnd;
6933 }
6934 break;
6935 case glslang::EOpSubgroupOr:
6936 case glslang::EOpSubgroupInclusiveOr:
6937 case glslang::EOpSubgroupExclusiveOr:
6938 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006939 case glslang::EOpSubgroupPartitionedOr:
6940 case glslang::EOpSubgroupPartitionedInclusiveOr:
6941 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006942 if (isBool) {
6943 opCode = spv::OpGroupNonUniformLogicalOr;
6944 } else {
6945 opCode = spv::OpGroupNonUniformBitwiseOr;
6946 }
6947 break;
6948 case glslang::EOpSubgroupXor:
6949 case glslang::EOpSubgroupInclusiveXor:
6950 case glslang::EOpSubgroupExclusiveXor:
6951 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006952 case glslang::EOpSubgroupPartitionedXor:
6953 case glslang::EOpSubgroupPartitionedInclusiveXor:
6954 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006955 if (isBool) {
6956 opCode = spv::OpGroupNonUniformLogicalXor;
6957 } else {
6958 opCode = spv::OpGroupNonUniformBitwiseXor;
6959 }
6960 break;
6961 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6962 case glslang::EOpSubgroupQuadSwapHorizontal:
6963 case glslang::EOpSubgroupQuadSwapVertical:
6964 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6965 default: assert(0 && "Unhandled subgroup operation!");
6966 }
6967
John Kessenich149afc32018-08-14 13:31:43 -06006968 // get the right Group Operation
6969 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006970 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006971 default:
6972 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006973 case glslang::EOpSubgroupBallotBitCount:
6974 case glslang::EOpSubgroupAdd:
6975 case glslang::EOpSubgroupMul:
6976 case glslang::EOpSubgroupMin:
6977 case glslang::EOpSubgroupMax:
6978 case glslang::EOpSubgroupAnd:
6979 case glslang::EOpSubgroupOr:
6980 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006981 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006982 break;
6983 case glslang::EOpSubgroupBallotInclusiveBitCount:
6984 case glslang::EOpSubgroupInclusiveAdd:
6985 case glslang::EOpSubgroupInclusiveMul:
6986 case glslang::EOpSubgroupInclusiveMin:
6987 case glslang::EOpSubgroupInclusiveMax:
6988 case glslang::EOpSubgroupInclusiveAnd:
6989 case glslang::EOpSubgroupInclusiveOr:
6990 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006991 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006992 break;
6993 case glslang::EOpSubgroupBallotExclusiveBitCount:
6994 case glslang::EOpSubgroupExclusiveAdd:
6995 case glslang::EOpSubgroupExclusiveMul:
6996 case glslang::EOpSubgroupExclusiveMin:
6997 case glslang::EOpSubgroupExclusiveMax:
6998 case glslang::EOpSubgroupExclusiveAnd:
6999 case glslang::EOpSubgroupExclusiveOr:
7000 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007001 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007002 break;
7003 case glslang::EOpSubgroupClusteredAdd:
7004 case glslang::EOpSubgroupClusteredMul:
7005 case glslang::EOpSubgroupClusteredMin:
7006 case glslang::EOpSubgroupClusteredMax:
7007 case glslang::EOpSubgroupClusteredAnd:
7008 case glslang::EOpSubgroupClusteredOr:
7009 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007010 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007011 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007012 case glslang::EOpSubgroupPartitionedAdd:
7013 case glslang::EOpSubgroupPartitionedMul:
7014 case glslang::EOpSubgroupPartitionedMin:
7015 case glslang::EOpSubgroupPartitionedMax:
7016 case glslang::EOpSubgroupPartitionedAnd:
7017 case glslang::EOpSubgroupPartitionedOr:
7018 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007019 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007020 break;
7021 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7022 case glslang::EOpSubgroupPartitionedInclusiveMul:
7023 case glslang::EOpSubgroupPartitionedInclusiveMin:
7024 case glslang::EOpSubgroupPartitionedInclusiveMax:
7025 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7026 case glslang::EOpSubgroupPartitionedInclusiveOr:
7027 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007028 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007029 break;
7030 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7031 case glslang::EOpSubgroupPartitionedExclusiveMul:
7032 case glslang::EOpSubgroupPartitionedExclusiveMin:
7033 case glslang::EOpSubgroupPartitionedExclusiveMax:
7034 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7035 case glslang::EOpSubgroupPartitionedExclusiveOr:
7036 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007037 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007038 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007039 }
7040
John Kessenich149afc32018-08-14 13:31:43 -06007041 // build the instruction
7042 std::vector<spv::IdImmediate> spvGroupOperands;
7043
7044 // Every operation begins with the Execution Scope operand.
7045 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7046 spvGroupOperands.push_back(executionScope);
7047
7048 // Next, for all operations that use a Group Operation, push that as an operand.
7049 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007050 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007051 spvGroupOperands.push_back(groupOperand);
7052 }
7053
John Kessenich66011cb2018-03-06 16:12:04 -07007054 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007055 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7056 spv::IdImmediate operand = { true, *opIt };
7057 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007058 }
7059
7060 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007061 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007062 switch (op) {
7063 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007064 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7065 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7066 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7067 }
7068 if (directionId != spv::NoResult) {
7069 spv::IdImmediate direction = { true, directionId };
7070 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007071 }
7072
7073 return builder.createOp(opCode, typeId, spvGroupOperands);
7074}
7075
John Kessenich5e4b1242015-08-06 22:53:06 -06007076spv::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 -06007077{
John Kessenich66011cb2018-03-06 16:12:04 -07007078 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7079 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007080
John Kessenich140f3df2015-06-26 16:58:36 -06007081 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007082 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007083 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007084 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007085 spv::Id typeId0 = 0;
7086 if (consumedOperands > 0)
7087 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007088 spv::Id typeId1 = 0;
7089 if (consumedOperands > 1)
7090 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007091 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007092
7093 switch (op) {
7094 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007095 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007096 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007097 else if (isUnsigned)
7098 libCall = spv::GLSLstd450UMin;
7099 else
7100 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007101 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007102 break;
7103 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007104 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007105 break;
7106 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007107 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007108 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007109 else if (isUnsigned)
7110 libCall = spv::GLSLstd450UMax;
7111 else
7112 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007113 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007114 break;
7115 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007116 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007117 break;
7118 case glslang::EOpDot:
7119 opCode = spv::OpDot;
7120 break;
7121 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007122 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007123 break;
7124
7125 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007126 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007127 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007128 else if (isUnsigned)
7129 libCall = spv::GLSLstd450UClamp;
7130 else
7131 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007132 builder.promoteScalar(precision, operands.front(), operands[1]);
7133 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007134 break;
7135 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007136 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7137 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007138 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007139 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007140 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007141 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007142 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007143 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007144 break;
7145 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007146 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007147 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007148 break;
7149 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007150 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007151 builder.promoteScalar(precision, operands[0], operands[2]);
7152 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007153 break;
7154
7155 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007156 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007157 break;
7158 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007159 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007160 break;
7161 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007162 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007163 break;
7164 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007165 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007166 break;
7167 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007168 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007169 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007170#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007171 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007172 if (typeProxy == glslang::EbtFloat16)
7173 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007174 libCall = spv::GLSLstd450InterpolateAtSample;
7175 break;
7176 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007177 if (typeProxy == glslang::EbtFloat16)
7178 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007179 libCall = spv::GLSLstd450InterpolateAtOffset;
7180 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007181 case glslang::EOpAddCarry:
7182 opCode = spv::OpIAddCarry;
7183 typeId = builder.makeStructResultType(typeId0, typeId0);
7184 consumedOperands = 2;
7185 break;
7186 case glslang::EOpSubBorrow:
7187 opCode = spv::OpISubBorrow;
7188 typeId = builder.makeStructResultType(typeId0, typeId0);
7189 consumedOperands = 2;
7190 break;
7191 case glslang::EOpUMulExtended:
7192 opCode = spv::OpUMulExtended;
7193 typeId = builder.makeStructResultType(typeId0, typeId0);
7194 consumedOperands = 2;
7195 break;
7196 case glslang::EOpIMulExtended:
7197 opCode = spv::OpSMulExtended;
7198 typeId = builder.makeStructResultType(typeId0, typeId0);
7199 consumedOperands = 2;
7200 break;
7201 case glslang::EOpBitfieldExtract:
7202 if (isUnsigned)
7203 opCode = spv::OpBitFieldUExtract;
7204 else
7205 opCode = spv::OpBitFieldSExtract;
7206 break;
7207 case glslang::EOpBitfieldInsert:
7208 opCode = spv::OpBitFieldInsert;
7209 break;
7210
7211 case glslang::EOpFma:
7212 libCall = spv::GLSLstd450Fma;
7213 break;
7214 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007215 {
7216 libCall = spv::GLSLstd450FrexpStruct;
7217 assert(builder.isPointerType(typeId1));
7218 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007219 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007220 if (width == 16)
7221 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7222 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007223 if (builder.getNumComponents(operands[0]) == 1)
7224 frexpIntType = builder.makeIntegerType(width, true);
7225 else
7226 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7227 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7228 consumedOperands = 1;
7229 }
John Kessenich55e7d112015-11-15 21:33:39 -07007230 break;
7231 case glslang::EOpLdexp:
7232 libCall = spv::GLSLstd450Ldexp;
7233 break;
7234
Rex Xu574ab042016-04-14 16:53:07 +08007235 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007236 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007237
John Kessenich66011cb2018-03-06 16:12:04 -07007238 case glslang::EOpSubgroupBroadcast:
7239 case glslang::EOpSubgroupBallotBitExtract:
7240 case glslang::EOpSubgroupShuffle:
7241 case glslang::EOpSubgroupShuffleXor:
7242 case glslang::EOpSubgroupShuffleUp:
7243 case glslang::EOpSubgroupShuffleDown:
7244 case glslang::EOpSubgroupClusteredAdd:
7245 case glslang::EOpSubgroupClusteredMul:
7246 case glslang::EOpSubgroupClusteredMin:
7247 case glslang::EOpSubgroupClusteredMax:
7248 case glslang::EOpSubgroupClusteredAnd:
7249 case glslang::EOpSubgroupClusteredOr:
7250 case glslang::EOpSubgroupClusteredXor:
7251 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007252 case glslang::EOpSubgroupPartitionedAdd:
7253 case glslang::EOpSubgroupPartitionedMul:
7254 case glslang::EOpSubgroupPartitionedMin:
7255 case glslang::EOpSubgroupPartitionedMax:
7256 case glslang::EOpSubgroupPartitionedAnd:
7257 case glslang::EOpSubgroupPartitionedOr:
7258 case glslang::EOpSubgroupPartitionedXor:
7259 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7260 case glslang::EOpSubgroupPartitionedInclusiveMul:
7261 case glslang::EOpSubgroupPartitionedInclusiveMin:
7262 case glslang::EOpSubgroupPartitionedInclusiveMax:
7263 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7264 case glslang::EOpSubgroupPartitionedInclusiveOr:
7265 case glslang::EOpSubgroupPartitionedInclusiveXor:
7266 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7267 case glslang::EOpSubgroupPartitionedExclusiveMul:
7268 case glslang::EOpSubgroupPartitionedExclusiveMin:
7269 case glslang::EOpSubgroupPartitionedExclusiveMax:
7270 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7271 case glslang::EOpSubgroupPartitionedExclusiveOr:
7272 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007273 return createSubgroupOperation(op, typeId, operands, typeProxy);
7274
Rex Xu9d93a232016-05-05 12:30:44 +08007275 case glslang::EOpSwizzleInvocations:
7276 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7277 libCall = spv::SwizzleInvocationsAMD;
7278 break;
7279 case glslang::EOpSwizzleInvocationsMasked:
7280 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7281 libCall = spv::SwizzleInvocationsMaskedAMD;
7282 break;
7283 case glslang::EOpWriteInvocation:
7284 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7285 libCall = spv::WriteInvocationAMD;
7286 break;
7287
7288 case glslang::EOpMin3:
7289 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7290 if (isFloat)
7291 libCall = spv::FMin3AMD;
7292 else {
7293 if (isUnsigned)
7294 libCall = spv::UMin3AMD;
7295 else
7296 libCall = spv::SMin3AMD;
7297 }
7298 break;
7299 case glslang::EOpMax3:
7300 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7301 if (isFloat)
7302 libCall = spv::FMax3AMD;
7303 else {
7304 if (isUnsigned)
7305 libCall = spv::UMax3AMD;
7306 else
7307 libCall = spv::SMax3AMD;
7308 }
7309 break;
7310 case glslang::EOpMid3:
7311 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7312 if (isFloat)
7313 libCall = spv::FMid3AMD;
7314 else {
7315 if (isUnsigned)
7316 libCall = spv::UMid3AMD;
7317 else
7318 libCall = spv::SMid3AMD;
7319 }
7320 break;
7321
7322 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007323 if (typeProxy == glslang::EbtFloat16)
7324 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007325 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7326 libCall = spv::InterpolateAtVertexAMD;
7327 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007328 case glslang::EOpBarrier:
7329 {
7330 // This is for the extended controlBarrier function, with four operands.
7331 // The unextended barrier() goes through createNoArgOperation.
7332 assert(operands.size() == 4);
7333 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7334 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7335 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7336 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007337 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7338 spv::MemorySemanticsMakeVisibleKHRMask |
7339 spv::MemorySemanticsOutputMemoryKHRMask |
7340 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007341 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7342 }
7343 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7344 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7345 }
7346 return 0;
7347 }
7348 break;
7349 case glslang::EOpMemoryBarrier:
7350 {
7351 // This is for the extended memoryBarrier function, with three operands.
7352 // The unextended memoryBarrier() goes through createNoArgOperation.
7353 assert(operands.size() == 3);
7354 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7355 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7356 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007357 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7358 spv::MemorySemanticsMakeVisibleKHRMask |
7359 spv::MemorySemanticsOutputMemoryKHRMask |
7360 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007361 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7362 }
7363 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7364 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7365 }
7366 return 0;
7367 }
7368 break;
Chao Chen3c366992018-09-19 11:41:59 -07007369
Chao Chenb50c02e2018-09-19 11:42:24 -07007370 case glslang::EOpReportIntersectionNV:
7371 {
7372 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007373 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007374 }
7375 break;
7376 case glslang::EOpTraceNV:
7377 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007378 builder.createNoResultOp(spv::OpTraceNV, operands);
7379 return 0;
7380 }
7381 break;
7382 case glslang::EOpExecuteCallableNV:
7383 {
7384 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007385 return 0;
7386 }
7387 break;
Chao Chen3c366992018-09-19 11:41:59 -07007388 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7389 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7390 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007391 case glslang::EOpCooperativeMatrixMulAdd:
7392 opCode = spv::OpCooperativeMatrixMulAddNV;
7393 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007394#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007395 default:
7396 return 0;
7397 }
7398
7399 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007400 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007401 // Use an extended instruction from the standard library.
7402 // Construct the call arguments, without modifying the original operands vector.
7403 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7404 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007405 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007406 } else if (opCode == spv::OpDot && !isFloat) {
7407 // int dot(int, int)
7408 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7409 const int componentCount = builder.getNumComponents(operands[0]);
7410 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7411 builder.setPrecision(mulOp, precision);
7412 id = builder.createCompositeExtract(mulOp, typeId, 0);
7413 for (int i = 1; i < componentCount; ++i) {
7414 builder.setPrecision(id, precision);
7415 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7416 }
John Kessenich2359bd02015-12-06 19:29:11 -07007417 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007418 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007419 case 0:
7420 // should all be handled by visitAggregate and createNoArgOperation
7421 assert(0);
7422 return 0;
7423 case 1:
7424 // should all be handled by createUnaryOperation
7425 assert(0);
7426 return 0;
7427 case 2:
7428 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7429 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007430 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007431 // anything 3 or over doesn't have l-value operands, so all should be consumed
7432 assert(consumedOperands == operands.size());
7433 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007434 break;
7435 }
7436 }
7437
John Kessenichb9197c82019-08-11 07:41:45 -06007438#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007439 // Decode the return types that were structures
7440 switch (op) {
7441 case glslang::EOpAddCarry:
7442 case glslang::EOpSubBorrow:
7443 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7444 id = builder.createCompositeExtract(id, typeId0, 0);
7445 break;
7446 case glslang::EOpUMulExtended:
7447 case glslang::EOpIMulExtended:
7448 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7449 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7450 break;
7451 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007452 {
7453 assert(operands.size() == 2);
7454 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7455 // "exp" is floating-point type (from HLSL intrinsic)
7456 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7457 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7458 builder.createStore(member1, operands[1]);
7459 } else
7460 // "exp" is integer type (from GLSL built-in function)
7461 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7462 id = builder.createCompositeExtract(id, typeId0, 0);
7463 }
John Kessenich55e7d112015-11-15 21:33:39 -07007464 break;
7465 default:
7466 break;
7467 }
John Kessenichb9197c82019-08-11 07:41:45 -06007468#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007469
John Kessenich32cfd492016-02-02 12:37:46 -07007470 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007471}
7472
Rex Xu9d93a232016-05-05 12:30:44 +08007473// Intrinsics with no arguments (or no return value, and no precision).
7474spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007475{
John Kessenich155d3512019-08-08 23:29:20 -06007476#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05007477 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7478 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007479
7480 switch (op) {
7481 case glslang::EOpEmitVertex:
7482 builder.createNoResultOp(spv::OpEmitVertex);
7483 return 0;
7484 case glslang::EOpEndPrimitive:
7485 builder.createNoResultOp(spv::OpEndPrimitive);
7486 return 0;
7487 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007488 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007489 if (glslangIntermediate->usingVulkanMemoryModel()) {
7490 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7491 spv::MemorySemanticsOutputMemoryKHRMask |
7492 spv::MemorySemanticsAcquireReleaseMask);
7493 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7494 } else {
7495 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7496 }
John Kessenich82979362017-12-11 04:02:24 -07007497 } else {
7498 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7499 spv::MemorySemanticsWorkgroupMemoryMask |
7500 spv::MemorySemanticsAcquireReleaseMask);
7501 }
John Kessenich140f3df2015-06-26 16:58:36 -06007502 return 0;
7503 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007504 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7505 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007506 return 0;
7507 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007508 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7509 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007510 return 0;
7511 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007512 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7513 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007514 return 0;
7515 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007516 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7517 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007518 return 0;
7519 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007520 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7521 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007522 return 0;
7523 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007524 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7525 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007526 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007527 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007528 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007529 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007530 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007531 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007532 case glslang::EOpDeviceMemoryBarrier:
7533 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7534 spv::MemorySemanticsImageMemoryMask |
7535 spv::MemorySemanticsAcquireReleaseMask);
7536 return 0;
7537 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7538 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7539 spv::MemorySemanticsImageMemoryMask |
7540 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007541 return 0;
7542 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007543 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7544 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007545 return 0;
7546 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007547 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7548 spv::MemorySemanticsWorkgroupMemoryMask |
7549 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007550 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007551 case glslang::EOpSubgroupBarrier:
7552 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7553 spv::MemorySemanticsAcquireReleaseMask);
7554 return spv::NoResult;
7555 case glslang::EOpSubgroupMemoryBarrier:
7556 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7557 spv::MemorySemanticsAcquireReleaseMask);
7558 return spv::NoResult;
7559 case glslang::EOpSubgroupMemoryBarrierBuffer:
7560 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7561 spv::MemorySemanticsAcquireReleaseMask);
7562 return spv::NoResult;
7563 case glslang::EOpSubgroupMemoryBarrierImage:
7564 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7565 spv::MemorySemanticsAcquireReleaseMask);
7566 return spv::NoResult;
7567 case glslang::EOpSubgroupMemoryBarrierShared:
7568 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7569 spv::MemorySemanticsAcquireReleaseMask);
7570 return spv::NoResult;
7571 case glslang::EOpSubgroupElect: {
7572 std::vector<spv::Id> operands;
7573 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7574 }
Rex Xu9d93a232016-05-05 12:30:44 +08007575 case glslang::EOpTime:
7576 {
7577 std::vector<spv::Id> args; // Dummy arguments
7578 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7579 return builder.setPrecision(id, precision);
7580 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007581 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007582 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007583 return 0;
7584 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007585 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007586 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007587
7588 case glslang::EOpBeginInvocationInterlock:
7589 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7590 return 0;
7591 case glslang::EOpEndInvocationInterlock:
7592 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7593 return 0;
7594
Jeff Bolzba6170b2019-07-01 09:23:23 -05007595 case glslang::EOpIsHelperInvocation:
7596 {
7597 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007598 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7599 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7600 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007601 }
7602
amhagan91fb0092019-07-10 21:14:38 -04007603 case glslang::EOpReadClockSubgroupKHR: {
7604 std::vector<spv::Id> args;
7605 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7606 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7607 builder.addCapability(spv::CapabilityShaderClockKHR);
7608 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7609 }
7610
7611 case glslang::EOpReadClockDeviceKHR: {
7612 std::vector<spv::Id> args;
7613 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7614 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7615 builder.addCapability(spv::CapabilityShaderClockKHR);
7616 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7617 }
John Kessenich140f3df2015-06-26 16:58:36 -06007618 default:
John Kessenich155d3512019-08-08 23:29:20 -06007619 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007620 }
John Kessenich155d3512019-08-08 23:29:20 -06007621#endif
7622
7623 logger->missingFunctionality("unknown operation with no arguments");
7624
7625 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007626}
7627
7628spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7629{
John Kessenich2f273362015-07-18 22:34:27 -06007630 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007631 spv::Id id;
7632 if (symbolValues.end() != iter) {
7633 id = iter->second;
7634 return id;
7635 }
7636
7637 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007638 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7639 auto forcedType = getForcedType(builtIn, symbol->getType());
7640 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007641 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007642 if (forcedType.second != spv::NoType)
7643 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007644
Rex Xuc884b4a2016-06-29 15:03:44 +08007645 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007646 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7647 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7648 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007649#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007650 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007651 if (symbol->getQualifier().hasComponent())
7652 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7653 if (symbol->getQualifier().hasIndex())
7654 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007655#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007656 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007657 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007658 // atomic counters use this:
7659 if (symbol->getQualifier().hasOffset())
7660 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007661 }
7662
scygan2c864272016-05-18 18:09:17 +02007663 if (symbol->getQualifier().hasLocation())
7664 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007665 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007666 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007667 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007668 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007669 }
John Kessenich140f3df2015-06-26 16:58:36 -06007670 if (symbol->getQualifier().hasSet())
7671 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007672 else if (IsDescriptorResource(symbol->getType())) {
7673 // default to 0
7674 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7675 }
John Kessenich140f3df2015-06-26 16:58:36 -06007676 if (symbol->getQualifier().hasBinding())
7677 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007678 else if (IsDescriptorResource(symbol->getType())) {
7679 // default to 0
7680 builder.addDecoration(id, spv::DecorationBinding, 0);
7681 }
John Kessenich6c292d32016-02-15 20:58:50 -07007682 if (symbol->getQualifier().hasAttachment())
7683 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007684 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007685 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007686 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007687 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007688 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7689 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7690 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7691 }
7692 if (symbol->getQualifier().hasXfbOffset())
7693 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007694 }
7695
John Kessenichb9197c82019-08-11 07:41:45 -06007696 // add built-in variable decoration
7697 if (builtIn != spv::BuiltInMax) {
7698 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7699 }
7700
7701#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007702 if (symbol->getType().isImage()) {
7703 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007704 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007705 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007706 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007707 }
7708
John Kessenich5611c6d2018-04-05 11:25:02 -06007709 // nonuniform
7710 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7711
chaoc0ad6a4e2016-12-19 16:29:34 -08007712 if (builtIn == spv::BuiltInSampleMask) {
7713 spv::Decoration decoration;
7714 // GL_NV_sample_mask_override_coverage extension
7715 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007716 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007717 else
7718 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007719 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007720 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007721 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007722 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7723 }
7724 }
chaoc771d89f2017-01-13 01:10:53 -08007725 else if (builtIn == spv::BuiltInLayer) {
7726 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007727 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007728 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007729 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7730 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7731 }
John Kessenichb41bff62017-08-11 13:07:17 -06007732 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007733 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7734 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007735 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7736 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7737 }
7738 }
7739
chaoc6e5acae2016-12-20 13:28:52 -08007740 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007741 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007742 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007743 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7744 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007745 if (symbol->getQualifier().pervertexNV) {
7746 builder.addDecoration(id, spv::DecorationPerVertexNV);
7747 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7748 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7749 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007750
John Kessenich5d610ee2018-03-07 18:05:55 -07007751 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7752 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7753 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7754 symbol->getType().getQualifier().semanticName);
7755 }
7756
John Kessenich7015bd62019-08-01 03:28:08 -06007757 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007758 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7759 }
John Kessenichb9197c82019-08-11 07:41:45 -06007760#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007761
John Kessenich140f3df2015-06-26 16:58:36 -06007762 return id;
7763}
7764
John Kessenicha28f7a72019-08-06 07:00:58 -06007765#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007766// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7767void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7768{
7769 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007770 if (qualifier.perPrimitiveNV) {
7771 // Need to add capability/extension for fragment shader.
7772 // Mesh shader already adds this by default.
7773 if (glslangIntermediate->getStage() == EShLangFragment) {
7774 builder.addCapability(spv::CapabilityMeshShadingNV);
7775 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7776 }
Chao Chen3c366992018-09-19 11:41:59 -07007777 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007778 }
Chao Chen3c366992018-09-19 11:41:59 -07007779 if (qualifier.perViewNV)
7780 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7781 if (qualifier.perTaskNV)
7782 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7783 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007784 if (qualifier.perPrimitiveNV) {
7785 // Need to add capability/extension for fragment shader.
7786 // Mesh shader already adds this by default.
7787 if (glslangIntermediate->getStage() == EShLangFragment) {
7788 builder.addCapability(spv::CapabilityMeshShadingNV);
7789 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7790 }
Chao Chen3c366992018-09-19 11:41:59 -07007791 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007792 }
Chao Chen3c366992018-09-19 11:41:59 -07007793 if (qualifier.perViewNV)
7794 builder.addDecoration(id, spv::DecorationPerViewNV);
7795 if (qualifier.perTaskNV)
7796 builder.addDecoration(id, spv::DecorationPerTaskNV);
7797 }
7798}
7799#endif
7800
John Kessenich55e7d112015-11-15 21:33:39 -07007801// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007802// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007803//
7804// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7805//
7806// Recursively walk the nodes. The nodes form a tree whose leaves are
7807// regular constants, which themselves are trees that createSpvConstant()
7808// recursively walks. So, this function walks the "top" of the tree:
7809// - emit specialization constant-building instructions for specConstant
7810// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007811spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007812{
John Kessenich7cc0e282016-03-20 00:46:02 -06007813 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007814
qining4f4bb812016-04-03 23:55:17 -04007815 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007816 if (! node.getQualifier().specConstant) {
7817 // hand off to the non-spec-constant path
7818 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7819 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007820 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007821 nextConst, false);
7822 }
7823
7824 // We now know we have a specialization constant to build
7825
John Kessenich155d3512019-08-08 23:29:20 -06007826#ifndef GLSLANG_WEB
John Kessenichd94c0032016-05-30 19:29:40 -06007827 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007828 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7829 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7830 std::vector<spv::Id> dimConstId;
7831 for (int dim = 0; dim < 3; ++dim) {
7832 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7833 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007834 if (specConst) {
7835 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7836 glslangIntermediate->getLocalSizeSpecId(dim));
7837 }
qining4f4bb812016-04-03 23:55:17 -04007838 }
7839 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7840 }
John Kessenich155d3512019-08-08 23:29:20 -06007841#endif
qining4f4bb812016-04-03 23:55:17 -04007842
7843 // An AST node labelled as specialization constant should be a symbol node.
7844 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7845 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007846 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007847 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007848 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7849 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7850 // will set the builder into spec constant op instruction generating mode.
7851 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007852 result = accessChainLoad(sub_tree->getType());
7853 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007854 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007855 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007856 } else {
7857 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007858 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007859 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007860 builder.addName(result, sn->getName().c_str());
7861 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007862 }
qining4f4bb812016-04-03 23:55:17 -04007863
7864 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7865 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007866 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007867 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007868}
7869
John Kessenich140f3df2015-06-26 16:58:36 -06007870// Use 'consts' as the flattened glslang source of scalar constants to recursively
7871// build the aggregate SPIR-V constant.
7872//
7873// If there are not enough elements present in 'consts', 0 will be substituted;
7874// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7875//
qining08408382016-03-21 09:51:37 -04007876spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007877{
7878 // vector of constants for SPIR-V
7879 std::vector<spv::Id> spvConsts;
7880
7881 // Type is used for struct and array constants
7882 spv::Id typeId = convertGlslangToSpvType(glslangType);
7883
7884 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007885 glslang::TType elementType(glslangType, 0);
7886 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007887 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007888 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007889 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007890 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007891 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007892 } else if (glslangType.isCoopMat()) {
7893 glslang::TType componentType(glslangType.getBasicType());
7894 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007895 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007896 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7897 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007898 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007899 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007900 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7901 bool zero = nextConst >= consts.size();
7902 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007903 case glslang::EbtInt:
7904 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7905 break;
7906 case glslang::EbtUint:
7907 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7908 break;
7909 case glslang::EbtFloat:
7910 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7911 break;
7912 case glslang::EbtBool:
7913 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7914 break;
7915#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007916 case glslang::EbtInt8:
7917 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7918 break;
7919 case glslang::EbtUint8:
7920 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7921 break;
7922 case glslang::EbtInt16:
7923 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7924 break;
7925 case glslang::EbtUint16:
7926 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7927 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007928 case glslang::EbtInt64:
7929 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7930 break;
7931 case glslang::EbtUint64:
7932 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7933 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007934 case glslang::EbtDouble:
7935 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7936 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007937 case glslang::EbtFloat16:
7938 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7939 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007940#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007941 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007942 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007943 break;
7944 }
7945 ++nextConst;
7946 }
7947 } else {
7948 // we have a non-aggregate (scalar) constant
7949 bool zero = nextConst >= consts.size();
7950 spv::Id scalar = 0;
7951 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007952 case glslang::EbtInt:
7953 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7954 break;
7955 case glslang::EbtUint:
7956 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7957 break;
7958 case glslang::EbtFloat:
7959 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7960 break;
7961 case glslang::EbtBool:
7962 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7963 break;
7964#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007965 case glslang::EbtInt8:
7966 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7967 break;
7968 case glslang::EbtUint8:
7969 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7970 break;
7971 case glslang::EbtInt16:
7972 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7973 break;
7974 case glslang::EbtUint16:
7975 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7976 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007977 case glslang::EbtInt64:
7978 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7979 break;
7980 case glslang::EbtUint64:
7981 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7982 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007983 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007984 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007985 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007986 case glslang::EbtFloat16:
7987 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7988 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007989 case glslang::EbtReference:
7990 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7991 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7992 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007993#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007994 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007995 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007996 break;
7997 }
7998 ++nextConst;
7999 return scalar;
8000 }
8001
8002 return builder.makeCompositeConstant(typeId, spvConsts);
8003}
8004
John Kessenich7c1aa102015-10-15 13:29:11 -06008005// Return true if the node is a constant or symbol whose reading has no
8006// non-trivial observable cost or effect.
8007bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8008{
8009 // don't know what this is
8010 if (node == nullptr)
8011 return false;
8012
8013 // a constant is safe
8014 if (node->getAsConstantUnion() != nullptr)
8015 return true;
8016
8017 // not a symbol means non-trivial
8018 if (node->getAsSymbolNode() == nullptr)
8019 return false;
8020
8021 // a symbol, depends on what's being read
8022 switch (node->getType().getQualifier().storage) {
8023 case glslang::EvqTemporary:
8024 case glslang::EvqGlobal:
8025 case glslang::EvqIn:
8026 case glslang::EvqInOut:
8027 case glslang::EvqConst:
8028 case glslang::EvqConstReadOnly:
8029 case glslang::EvqUniform:
8030 return true;
8031 default:
8032 return false;
8033 }
qining25262b32016-05-06 17:25:16 -04008034}
John Kessenich7c1aa102015-10-15 13:29:11 -06008035
8036// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008037// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008038// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008039// Return true if trivial.
8040bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8041{
8042 if (node == nullptr)
8043 return false;
8044
John Kessenich84cc15f2017-05-24 16:44:47 -06008045 // count non scalars as trivial, as well as anything coming from HLSL
8046 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008047 return true;
8048
John Kessenich7c1aa102015-10-15 13:29:11 -06008049 // symbols and constants are trivial
8050 if (isTrivialLeaf(node))
8051 return true;
8052
8053 // otherwise, it needs to be a simple operation or one or two leaf nodes
8054
8055 // not a simple operation
8056 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8057 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8058 if (binaryNode == nullptr && unaryNode == nullptr)
8059 return false;
8060
8061 // not on leaf nodes
8062 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8063 return false;
8064
8065 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8066 return false;
8067 }
8068
8069 switch (node->getAsOperator()->getOp()) {
8070 case glslang::EOpLogicalNot:
8071 case glslang::EOpConvIntToBool:
8072 case glslang::EOpConvUintToBool:
8073 case glslang::EOpConvFloatToBool:
8074 case glslang::EOpConvDoubleToBool:
8075 case glslang::EOpEqual:
8076 case glslang::EOpNotEqual:
8077 case glslang::EOpLessThan:
8078 case glslang::EOpGreaterThan:
8079 case glslang::EOpLessThanEqual:
8080 case glslang::EOpGreaterThanEqual:
8081 case glslang::EOpIndexDirect:
8082 case glslang::EOpIndexDirectStruct:
8083 case glslang::EOpLogicalXor:
8084 case glslang::EOpAny:
8085 case glslang::EOpAll:
8086 return true;
8087 default:
8088 return false;
8089 }
8090}
8091
8092// Emit short-circuiting code, where 'right' is never evaluated unless
8093// the left side is true (for &&) or false (for ||).
8094spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8095{
8096 spv::Id boolTypeId = builder.makeBoolType();
8097
8098 // emit left operand
8099 builder.clearAccessChain();
8100 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008101 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008102
8103 // Operands to accumulate OpPhi operands
8104 std::vector<spv::Id> phiOperands;
8105 // accumulate left operand's phi information
8106 phiOperands.push_back(leftId);
8107 phiOperands.push_back(builder.getBuildPoint()->getId());
8108
8109 // Make the two kinds of operation symmetric with a "!"
8110 // || => emit "if (! left) result = right"
8111 // && => emit "if ( left) result = right"
8112 //
8113 // TODO: this runtime "not" for || could be avoided by adding functionality
8114 // to 'builder' to have an "else" without an "then"
8115 if (op == glslang::EOpLogicalOr)
8116 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8117
8118 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008119 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008120
8121 // emit right operand as the "then" part of the "if"
8122 builder.clearAccessChain();
8123 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008124 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008125
8126 // accumulate left operand's phi information
8127 phiOperands.push_back(rightId);
8128 phiOperands.push_back(builder.getBuildPoint()->getId());
8129
8130 // finish the "if"
8131 ifBuilder.makeEndIf();
8132
8133 // phi together the two results
8134 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8135}
8136
John Kessenicha28f7a72019-08-06 07:00:58 -06008137#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008138// Return type Id of the imported set of extended instructions corresponds to the name.
8139// Import this set if it has not been imported yet.
8140spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8141{
8142 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8143 return extBuiltinMap[name];
8144 else {
Rex Xu51596642016-09-21 18:56:12 +08008145 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008146 spv::Id extBuiltins = builder.import(name);
8147 extBuiltinMap[name] = extBuiltins;
8148 return extBuiltins;
8149 }
8150}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008151#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008152
John Kessenich140f3df2015-06-26 16:58:36 -06008153}; // end anonymous namespace
8154
8155namespace glslang {
8156
John Kessenich68d78fd2015-07-12 19:28:10 -06008157void GetSpirvVersion(std::string& version)
8158{
John Kessenich9e55f632015-07-15 10:03:39 -06008159 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008160 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008161 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008162 version = buf;
8163}
8164
John Kessenicha372a3e2017-11-02 22:32:14 -06008165// For low-order part of the generator's magic number. Bump up
8166// when there is a change in the style (e.g., if SSA form changes,
8167// or a different instruction sequence to do something gets used).
8168int GetSpirvGeneratorVersion()
8169{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008170 // return 1; // start
8171 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008172 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008173 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008174 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008175 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8176 // versions 4 and 6 each generate OpArrayLength as it has long been done
8177 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008178}
8179
John Kessenich140f3df2015-06-26 16:58:36 -06008180// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008181void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008182{
8183 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008184 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008185 if (out.fail())
8186 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008187 for (int i = 0; i < (int)spirv.size(); ++i) {
8188 unsigned int word = spirv[i];
8189 out.write((const char*)&word, 4);
8190 }
8191 out.close();
8192}
8193
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008194// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008195void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008196{
John Kessenich155d3512019-08-08 23:29:20 -06008197#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008198 std::ofstream out;
8199 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008200 if (out.fail())
8201 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008202 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008203 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008204 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008205 if (varName != nullptr) {
8206 out << "\t #pragma once" << std::endl;
8207 out << "const uint32_t " << varName << "[] = {" << std::endl;
8208 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008209 const int WORDS_PER_LINE = 8;
8210 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8211 out << "\t";
8212 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8213 const unsigned int word = spirv[i + j];
8214 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8215 if (i + j + 1 < (int)spirv.size()) {
8216 out << ",";
8217 }
8218 }
8219 out << std::endl;
8220 }
Flavio15017db2017-02-15 14:29:33 -08008221 if (varName != nullptr) {
8222 out << "};";
8223 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008224 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008225#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008226}
8227
John Kessenich140f3df2015-06-26 16:58:36 -06008228//
8229// Set up the glslang traversal
8230//
John Kessenich4e11b612018-08-30 16:56:59 -06008231void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008232{
Lei Zhang17535f72016-05-04 15:55:59 -04008233 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008234 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008235}
8236
John Kessenich4e11b612018-08-30 16:56:59 -06008237void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008238 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008239{
John Kessenich140f3df2015-06-26 16:58:36 -06008240 TIntermNode* root = intermediate.getTreeRoot();
8241
8242 if (root == 0)
8243 return;
8244
John Kessenich4e11b612018-08-30 16:56:59 -06008245 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008246 if (options == nullptr)
8247 options = &defaultOptions;
8248
John Kessenich4e11b612018-08-30 16:56:59 -06008249 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008250
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008251 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008252 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008253 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008254 it.dumpSpv(spirv);
8255
GregFfb03a552018-03-29 11:49:14 -06008256#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008257 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8258 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008259 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8260 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008261 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008262 prelegalization = false;
8263 }
John Kessenich717c80a2018-08-23 15:17:10 -06008264
John Kessenich4e11b612018-08-30 16:56:59 -06008265 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008266 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008267
John Kessenich717c80a2018-08-23 15:17:10 -06008268 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008269 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008270
GregFcd1f1692017-09-21 18:40:22 -06008271#endif
8272
John Kessenich4e11b612018-08-30 16:56:59 -06008273 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008274}
8275
8276}; // end namespace glslang