blob: 762a292e3b55002fde8c63710f612698aaf39cb0 [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
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400103 void addNoContraction(spv::Builder&, spv::Id) const { }
104 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600105#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400106 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); }
John Kessenichb9197c82019-08-11 07:41:45 -0600108 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 Kessenich9c14f772019-06-17 08:38:35 -0600220 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
221 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500222 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600223
John Kessenich121853f2017-05-31 17:11:16 -0600224 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600226 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700227 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 int sequenceDepth;
229
Lei Zhang17535f72016-05-04 15:55:59 -0400230 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400231
John Kessenich140f3df2015-06-26 16:58:36 -0600232 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
233 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700234 bool inEntryPoint;
235 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700236 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 -0700237 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600238 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600239 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600240 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800241 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600242
John Kessenich2f273362015-07-18 22:34:27 -0600243 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600244 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600245 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700246 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700247 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
248 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600249 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700250 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600251 // Map pointee types for EbtReference to their forward pointers
252 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600253 // Type forcing, for when SPIR-V wants a different type than the AST,
254 // requiring local translation to and from SPIR-V type on every access.
255 // Maps <builtin-variable-id -> AST-required-type-id>
256 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600257};
258
259//
260// Helper functions for translating glslang representations to SPIR-V enumerants.
261//
262
263// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700264spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600265{
John Kessenich155d3512019-08-08 23:29:20 -0600266#ifdef GLSLANG_WEB
267 return spv::SourceLanguageESSL;
268#endif
269
John Kessenich66e2faf2016-03-12 18:34:36 -0700270 switch (source) {
271 case glslang::EShSourceGlsl:
272 switch (profile) {
273 case ENoProfile:
274 case ECoreProfile:
275 case ECompatibilityProfile:
276 return spv::SourceLanguageGLSL;
277 case EEsProfile:
278 return spv::SourceLanguageESSL;
279 default:
280 return spv::SourceLanguageUnknown;
281 }
282 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600283 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
285 return spv::SourceLanguageUnknown;
286 }
287}
288
289// Translate glslang language (stage) to SPIR-V execution model.
290spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
291{
292 switch (stage) {
293 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600294 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600295 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600296#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600297 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
298 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
299 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700300 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
301 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
302 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
303 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
304 case EShLangMissNV: return spv::ExecutionModelMissNV;
305 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700306 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
307 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
308#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700310 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600311 return spv::ExecutionModelFragment;
312 }
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang sampler type to SPIR-V dimensionality.
316spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
317{
318 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700319 case glslang::Esd1D: return spv::Dim1D;
320 case glslang::Esd2D: return spv::Dim2D;
321 case glslang::Esd3D: return spv::Dim3D;
322 case glslang::EsdCube: return spv::DimCube;
323 case glslang::EsdRect: return spv::DimRect;
324 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700325 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700327 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::Dim2D;
329 }
330}
331
John Kessenichf6640762016-08-01 19:44:00 -0600332// Translate glslang precision to SPIR-V precision decorations.
333spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600334{
John Kessenichf6640762016-08-01 19:44:00 -0600335 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700336 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600337 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 default:
339 return spv::NoPrecision;
340 }
341}
342
John Kessenichf6640762016-08-01 19:44:00 -0600343// Translate glslang type to SPIR-V precision decorations.
344spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
345{
346 return TranslatePrecisionDecoration(type.getQualifier().precision);
347}
348
John Kessenich140f3df2015-06-26 16:58:36 -0600349// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600350spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600351{
352 if (type.getBasicType() == glslang::EbtBlock) {
353 switch (type.getQualifier().storage) {
354 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600355 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 case glslang::EvqVaryingIn: return spv::DecorationBlock;
357 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600358#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700359 case glslang::EvqPayloadNV: return spv::DecorationBlock;
360 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
361 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700362 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
363 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700364#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600365 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700366 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600367 break;
368 }
369 }
370
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372}
373
Rex Xu1da878f2016-02-21 20:59:01 +0800374// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500375void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800376{
John Kessenichb9197c82019-08-11 07:41:45 -0600377#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500378 if (!useVulkanMemoryModel) {
379 if (qualifier.coherent)
380 memory.push_back(spv::DecorationCoherent);
381 if (qualifier.volatil) {
382 memory.push_back(spv::DecorationVolatile);
383 memory.push_back(spv::DecorationCoherent);
384 }
John Kessenich14b85d32018-06-04 15:36:03 -0600385 }
Rex Xu1da878f2016-02-21 20:59:01 +0800386 if (qualifier.restrict)
387 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600388 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800389 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600390 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800391 memory.push_back(spv::DecorationNonReadable);
John Kessenichb9197c82019-08-11 07:41:45 -0600392#endif
Rex Xu1da878f2016-02-21 20:59:01 +0800393}
394
John Kessenich140f3df2015-06-26 16:58:36 -0600395// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700396spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
398 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700399 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::ElmRowMajor:
401 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700402 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700404 default:
405 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 }
408 } else {
409 switch (type.getBasicType()) {
410 default:
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600412 break;
413 case glslang::EbtBlock:
414 switch (type.getQualifier().storage) {
415 case glslang::EvqUniform:
416 case glslang::EvqBuffer:
417 switch (type.getQualifier().layoutPacking) {
418 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
420 default:
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 case glslang::EvqVaryingIn:
424 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700425 if (type.getQualifier().isTaskMemory()) {
426 switch (type.getQualifier().layoutPacking) {
427 case glslang::ElpShared: return spv::DecorationGLSLShared;
428 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
429 default: break;
430 }
431 } else {
432 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
433 }
John Kessenich4016e382016-07-15 11:53:56 -0600434 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600435#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700436 case glslang::EvqPayloadNV:
437 case glslang::EvqPayloadInNV:
438 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700439 case glslang::EvqCallableDataNV:
440 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700441 return spv::DecorationMax;
442#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600443 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700444 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600446 }
447 }
448 }
449}
450
451// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600452// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700453// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800454spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600455{
Rex Xubbceed72016-05-21 09:40:44 +0800456 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700457 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600459 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700460 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700461 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600462 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600463 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800464 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800465 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800466 }
Rex Xubbceed72016-05-21 09:40:44 +0800467 else
John Kessenich4016e382016-07-15 11:53:56 -0600468 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800469}
470
471// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600472// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800473// should be applied.
474spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
475{
John Kessenichb9197c82019-08-11 07:41:45 -0600476 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600478#ifndef GLSLANG_WEB
479 else if (qualifier.patch)
480 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700481 else if (qualifier.sample) {
482 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600483 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600484 }
485#endif
486
487 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600488}
489
John Kessenich92187592016-02-01 13:45:25 -0700490// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700491spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600492{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700493 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600494 return spv::DecorationInvariant;
495 else
John Kessenich4016e382016-07-15 11:53:56 -0600496 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600497}
498
qining9220dbb2016-05-04 17:34:38 -0400499// If glslang type is noContraction, return SPIR-V NoContraction decoration.
500spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
501{
John Kessenichb9197c82019-08-11 07:41:45 -0600502#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600503 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400504 return spv::DecorationNoContraction;
505 else
John Kessenichb9197c82019-08-11 07:41:45 -0600506#endif
John Kessenich4016e382016-07-15 11:53:56 -0600507 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400508}
509
John Kessenich5611c6d2018-04-05 11:25:02 -0600510// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
511spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
512{
John Kessenichb9197c82019-08-11 07:41:45 -0600513#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600514 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600515 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600516 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
517 return spv::DecorationNonUniformEXT;
518 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600519#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600520 return spv::DecorationMax;
521}
522
John Kessenichb9197c82019-08-11 07:41:45 -0600523spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
524 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500525{
Jeff Bolz36831c92018-09-05 10:11:41 -0500526 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600527
528#ifndef GLSLANG_WEB
529 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
530 return mask;
531
Jeff Bolz36831c92018-09-05 10:11:41 -0500532 if (coherentFlags.volatil ||
533 coherentFlags.coherent ||
534 coherentFlags.devicecoherent ||
535 coherentFlags.queuefamilycoherent ||
536 coherentFlags.workgroupcoherent ||
537 coherentFlags.subgroupcoherent) {
538 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
539 spv::MemoryAccessMakePointerVisibleKHRMask;
540 }
541 if (coherentFlags.nonprivate) {
542 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
543 }
544 if (coherentFlags.volatil) {
545 mask = mask | spv::MemoryAccessVolatileMask;
546 }
547 if (mask != spv::MemoryAccessMaskNone) {
548 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
549 }
John Kessenichb9197c82019-08-11 07:41:45 -0600550#endif
551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 return mask;
553}
554
John Kessenichb9197c82019-08-11 07:41:45 -0600555spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
556 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500557{
Jeff Bolz36831c92018-09-05 10:11:41 -0500558 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600559
560#ifndef GLSLANG_WEB
561 if (!glslangIntermediate->usingVulkanMemoryModel())
562 return mask;
563
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 if (coherentFlags.volatil ||
565 coherentFlags.coherent ||
566 coherentFlags.devicecoherent ||
567 coherentFlags.queuefamilycoherent ||
568 coherentFlags.workgroupcoherent ||
569 coherentFlags.subgroupcoherent) {
570 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
571 spv::ImageOperandsMakeTexelVisibleKHRMask;
572 }
573 if (coherentFlags.nonprivate) {
574 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
575 }
576 if (coherentFlags.volatil) {
577 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
578 }
579 if (mask != spv::ImageOperandsMaskNone) {
580 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
581 }
John Kessenichb9197c82019-08-11 07:41:45 -0600582#endif
583
Jeff Bolz36831c92018-09-05 10:11:41 -0500584 return mask;
585}
586
587spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
588{
John Kessenichb9197c82019-08-11 07:41:45 -0600589 spv::Builder::AccessChain::CoherentFlags flags = {};
590#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 flags.coherent = type.getQualifier().coherent;
592 flags.devicecoherent = type.getQualifier().devicecoherent;
593 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
594 // shared variables are implicitly workgroupcoherent in GLSL.
595 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
596 type.getQualifier().storage == glslang::EvqShared;
597 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600598 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500599 // *coherent variables are implicitly nonprivate in GLSL
600 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500601 flags.subgroupcoherent ||
602 flags.workgroupcoherent ||
603 flags.queuefamilycoherent ||
604 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600605 flags.coherent ||
606 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600608#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500609 return flags;
610}
611
John Kessenichb9197c82019-08-11 07:41:45 -0600612spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
613 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500614{
John Kessenichb9197c82019-08-11 07:41:45 -0600615 spv::Scope scope = spv::ScopeMax;
616
617#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600618 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500619 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
620 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
621 } else if (coherentFlags.devicecoherent) {
622 scope = spv::ScopeDevice;
623 } else if (coherentFlags.queuefamilycoherent) {
624 scope = spv::ScopeQueueFamilyKHR;
625 } else if (coherentFlags.workgroupcoherent) {
626 scope = spv::ScopeWorkgroup;
627 } else if (coherentFlags.subgroupcoherent) {
628 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500629 }
630 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
631 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
632 }
John Kessenichb9197c82019-08-11 07:41:45 -0600633#endif
634
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 return scope;
636}
637
David Netoa901ffe2016-06-08 14:11:40 +0100638// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
639// associated capabilities when required. For some built-in variables, a capability
640// is generated only when using the variable in an executable instruction, but not when
641// just declaring a struct member variable with it. This is true for PointSize,
642// ClipDistance, and CullDistance.
643spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600644{
645 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700646 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600647#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600648 // Defer adding the capability until the built-in is actually used.
649 if (! memberDeclaration) {
650 switch (glslangIntermediate->getStage()) {
651 case EShLangGeometry:
652 builder.addCapability(spv::CapabilityGeometryPointSize);
653 break;
654 case EShLangTessControl:
655 case EShLangTessEvaluation:
656 builder.addCapability(spv::CapabilityTessellationPointSize);
657 break;
658 default:
659 break;
660 }
John Kessenich92187592016-02-01 13:45:25 -0700661 }
John Kessenich155d3512019-08-08 23:29:20 -0600662#endif
John Kessenich92187592016-02-01 13:45:25 -0700663 return spv::BuiltInPointSize;
664
John Kessenicha28f7a72019-08-06 07:00:58 -0600665 case glslang::EbvPosition: return spv::BuiltInPosition;
666 case glslang::EbvVertexId: return spv::BuiltInVertexId;
667 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
668 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
669 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
670
671 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
672 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
673 case glslang::EbvFace: return spv::BuiltInFrontFacing;
674 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
675
676#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600677 // These *Distance capabilities logically belong here, but if the member is declared and
678 // then never used, consumers of SPIR-V prefer the capability not be declared.
679 // They are now generated when used, rather than here when declared.
680 // Potentially, the specification should be more clear what the minimum
681 // use needed is to trigger the capability.
682 //
John Kessenich92187592016-02-01 13:45:25 -0700683 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100684 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800685 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700686 return spv::BuiltInClipDistance;
687
688 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100689 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800690 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700691 return spv::BuiltInCullDistance;
692
693 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600694 builder.addCapability(spv::CapabilityMultiViewport);
695 if (glslangIntermediate->getStage() == EShLangVertex ||
696 glslangIntermediate->getStage() == EShLangTessControl ||
697 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800698
John Kessenich8317e6c2019-08-18 23:58:08 -0600699 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600700 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800701 }
John Kessenich92187592016-02-01 13:45:25 -0700702 return spv::BuiltInViewportIndex;
703
John Kessenich5e801132016-02-15 11:09:46 -0700704 case glslang::EbvSampleId:
705 builder.addCapability(spv::CapabilitySampleRateShading);
706 return spv::BuiltInSampleId;
707
708 case glslang::EbvSamplePosition:
709 builder.addCapability(spv::CapabilitySampleRateShading);
710 return spv::BuiltInSamplePosition;
711
712 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700713 return spv::BuiltInSampleMask;
714
John Kessenich78a45572016-07-08 14:05:15 -0600715 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700716 if (glslangIntermediate->getStage() == EShLangMeshNV) {
717 return spv::BuiltInLayer;
718 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600719 builder.addCapability(spv::CapabilityGeometry);
720 if (glslangIntermediate->getStage() == EShLangVertex ||
721 glslangIntermediate->getStage() == EShLangTessControl ||
722 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800723
John Kessenich8317e6c2019-08-18 23:58:08 -0600724 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600725 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800726 }
John Kessenich78a45572016-07-08 14:05:15 -0600727 return spv::BuiltInLayer;
728
John Kessenichda581a22015-10-14 14:10:30 -0600729 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600730 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800731 builder.addCapability(spv::CapabilityDrawParameters);
732 return spv::BuiltInBaseVertex;
733
John Kessenichda581a22015-10-14 14:10:30 -0600734 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600735 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800736 builder.addCapability(spv::CapabilityDrawParameters);
737 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200738
John Kessenichda581a22015-10-14 14:10:30 -0600739 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600740 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800741 builder.addCapability(spv::CapabilityDrawParameters);
742 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200743
744 case glslang::EbvPrimitiveId:
745 if (glslangIntermediate->getStage() == EShLangFragment)
746 builder.addCapability(spv::CapabilityGeometry);
747 return spv::BuiltInPrimitiveId;
748
Rex Xu37cdcee2017-06-29 17:46:34 +0800749 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800750 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
751 builder.addCapability(spv::CapabilityStencilExportEXT);
752 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800753
John Kessenich140f3df2015-06-26 16:58:36 -0600754 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600755 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
756 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
757 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
758 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600759 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
760 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
761 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
762 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
763 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
764 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
765 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800766
Rex Xu574ab042016-04-14 16:53:07 +0800767 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800768 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800769 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
770 return spv::BuiltInSubgroupSize;
771
Rex Xu574ab042016-04-14 16:53:07 +0800772 case glslang::EbvSubGroupInvocation:
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::BuiltInSubgroupLocalInvocationId;
776
Rex Xu574ab042016-04-14 16:53:07 +0800777 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800778 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
779 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600780 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800781
Rex Xu574ab042016-04-14 16:53:07 +0800782 case glslang::EbvSubGroupGeMask:
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::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800786
Rex Xu574ab042016-04-14 16:53:07 +0800787 case glslang::EbvSubGroupGtMask:
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::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800791
Rex Xu574ab042016-04-14 16:53:07 +0800792 case glslang::EbvSubGroupLeMask:
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::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800796
Rex Xu574ab042016-04-14 16:53:07 +0800797 case glslang::EbvSubGroupLtMask:
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::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800801
John Kessenich66011cb2018-03-06 16:12:04 -0700802 case glslang::EbvNumSubgroups:
803 builder.addCapability(spv::CapabilityGroupNonUniform);
804 return spv::BuiltInNumSubgroups;
805
806 case glslang::EbvSubgroupID:
807 builder.addCapability(spv::CapabilityGroupNonUniform);
808 return spv::BuiltInSubgroupId;
809
810 case glslang::EbvSubgroupSize2:
811 builder.addCapability(spv::CapabilityGroupNonUniform);
812 return spv::BuiltInSubgroupSize;
813
814 case glslang::EbvSubgroupInvocation2:
815 builder.addCapability(spv::CapabilityGroupNonUniform);
816 return spv::BuiltInSubgroupLocalInvocationId;
817
818 case glslang::EbvSubgroupEqMask2:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
821 return spv::BuiltInSubgroupEqMask;
822
823 case glslang::EbvSubgroupGeMask2:
824 builder.addCapability(spv::CapabilityGroupNonUniform);
825 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
826 return spv::BuiltInSubgroupGeMask;
827
828 case glslang::EbvSubgroupGtMask2:
829 builder.addCapability(spv::CapabilityGroupNonUniform);
830 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
831 return spv::BuiltInSubgroupGtMask;
832
833 case glslang::EbvSubgroupLeMask2:
834 builder.addCapability(spv::CapabilityGroupNonUniform);
835 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
836 return spv::BuiltInSubgroupLeMask;
837
838 case glslang::EbvSubgroupLtMask2:
839 builder.addCapability(spv::CapabilityGroupNonUniform);
840 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
841 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600842
Rex Xu17ff3432016-10-14 17:41:45 +0800843 case glslang::EbvBaryCoordNoPersp:
844 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
845 return spv::BuiltInBaryCoordNoPerspAMD;
846
847 case glslang::EbvBaryCoordNoPerspCentroid:
848 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
849 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
850
851 case glslang::EbvBaryCoordNoPerspSample:
852 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
853 return spv::BuiltInBaryCoordNoPerspSampleAMD;
854
855 case glslang::EbvBaryCoordSmooth:
856 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
857 return spv::BuiltInBaryCoordSmoothAMD;
858
859 case glslang::EbvBaryCoordSmoothCentroid:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordSmoothCentroidAMD;
862
863 case glslang::EbvBaryCoordSmoothSample:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordSmoothSampleAMD;
866
867 case glslang::EbvBaryCoordPullModel:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800870
John Kessenich6c8aaac2017-02-27 01:20:51 -0700871 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600872 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700873 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700874 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700875
876 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600877 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700878 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700879 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700880
Daniel Koch5154db52018-11-26 10:01:58 -0500881 case glslang::EbvFragSizeEXT:
882 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
883 builder.addCapability(spv::CapabilityFragmentDensityEXT);
884 return spv::BuiltInFragSizeEXT;
885
886 case glslang::EbvFragInvocationCountEXT:
887 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
888 builder.addCapability(spv::CapabilityFragmentDensityEXT);
889 return spv::BuiltInFragInvocationCountEXT;
890
chaoc771d89f2017-01-13 01:10:53 -0800891 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800892 if (!memberDeclaration) {
893 builder.addExtension(spv::E_SPV_NV_viewport_array2);
894 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
895 }
chaoc771d89f2017-01-13 01:10:53 -0800896 return spv::BuiltInViewportMaskNV;
897 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800898 if (!memberDeclaration) {
899 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
900 builder.addCapability(spv::CapabilityShaderStereoViewNV);
901 }
chaoc771d89f2017-01-13 01:10:53 -0800902 return spv::BuiltInSecondaryPositionNV;
903 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800904 if (!memberDeclaration) {
905 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
906 builder.addCapability(spv::CapabilityShaderStereoViewNV);
907 }
chaoc771d89f2017-01-13 01:10:53 -0800908 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800909 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800910 if (!memberDeclaration) {
911 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
912 builder.addCapability(spv::CapabilityPerViewAttributesNV);
913 }
chaocdf3956c2017-02-14 14:52:34 -0800914 return spv::BuiltInPositionPerViewNV;
915 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800916 if (!memberDeclaration) {
917 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
918 builder.addCapability(spv::CapabilityPerViewAttributesNV);
919 }
chaocdf3956c2017-02-14 14:52:34 -0800920 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700921 case glslang::EbvFragFullyCoveredNV:
922 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
923 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
924 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700925 case glslang::EbvFragmentSizeNV:
926 builder.addExtension(spv::E_SPV_NV_shading_rate);
927 builder.addCapability(spv::CapabilityShadingRateNV);
928 return spv::BuiltInFragmentSizeNV;
929 case glslang::EbvInvocationsPerPixelNV:
930 builder.addExtension(spv::E_SPV_NV_shading_rate);
931 builder.addCapability(spv::CapabilityShadingRateNV);
932 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700933
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700935 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700936 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700937 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700938 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700939 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700940 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700941 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700942 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700943 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700944 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700945 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700946 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700947 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700948 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700949 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700950 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700951 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700952 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700953 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700954 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700955 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700956 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700957 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700958 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700959 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700960 return spv::BuiltInWorldToObjectNV;
961 case glslang::EbvIncomingRayFlagsNV:
962 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400963
964 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700965 case glslang::EbvBaryCoordNV:
966 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
967 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
968 return spv::BuiltInBaryCoordNV;
969 case glslang::EbvBaryCoordNoPerspNV:
970 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
971 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
972 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400973
974 // mesh shaders
975 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700976 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400977 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700978 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400979 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700980 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400981 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700982 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400983 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700984 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400985 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700986 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400987 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700988 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700990 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400991
992 // sm builtins
993 case glslang::EbvWarpsPerSM:
994 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
995 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
996 return spv::BuiltInWarpsPerSMNV;
997 case glslang::EbvSMCount:
998 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
999 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1000 return spv::BuiltInSMCountNV;
1001 case glslang::EbvWarpID:
1002 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1003 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1004 return spv::BuiltInWarpIDNV;
1005 case glslang::EbvSMID:
1006 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1007 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1008 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001009#endif
1010
Rex Xu3e783f92017-02-22 16:44:48 +08001011 default:
1012 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001013 }
1014}
1015
Rex Xufc618912015-09-09 16:42:49 +08001016// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001017spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001018{
1019 assert(type.getBasicType() == glslang::EbtSampler);
1020
John Kessenichb9197c82019-08-11 07:41:45 -06001021#ifdef GLSLANG_WEB
1022 return spv::ImageFormatUnknown;
1023#endif
1024
John Kessenich5d0fa972016-02-15 11:57:00 -07001025 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001026 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001027 case glslang::ElfRg32f:
1028 case glslang::ElfRg16f:
1029 case glslang::ElfR11fG11fB10f:
1030 case glslang::ElfR16f:
1031 case glslang::ElfRgba16:
1032 case glslang::ElfRgb10A2:
1033 case glslang::ElfRg16:
1034 case glslang::ElfRg8:
1035 case glslang::ElfR16:
1036 case glslang::ElfR8:
1037 case glslang::ElfRgba16Snorm:
1038 case glslang::ElfRg16Snorm:
1039 case glslang::ElfRg8Snorm:
1040 case glslang::ElfR16Snorm:
1041 case glslang::ElfR8Snorm:
1042
1043 case glslang::ElfRg32i:
1044 case glslang::ElfRg16i:
1045 case glslang::ElfRg8i:
1046 case glslang::ElfR16i:
1047 case glslang::ElfR8i:
1048
1049 case glslang::ElfRgb10a2ui:
1050 case glslang::ElfRg32ui:
1051 case glslang::ElfRg16ui:
1052 case glslang::ElfRg8ui:
1053 case glslang::ElfR16ui:
1054 case glslang::ElfR8ui:
1055 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1056 break;
1057
1058 default:
1059 break;
1060 }
1061
1062 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001063 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001064 case glslang::ElfNone: return spv::ImageFormatUnknown;
1065 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1066 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1067 case glslang::ElfR32f: return spv::ImageFormatR32f;
1068 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1069 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1070 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1071 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1072 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1073 case glslang::ElfR16f: return spv::ImageFormatR16f;
1074 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1075 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1076 case glslang::ElfRg16: return spv::ImageFormatRg16;
1077 case glslang::ElfRg8: return spv::ImageFormatRg8;
1078 case glslang::ElfR16: return spv::ImageFormatR16;
1079 case glslang::ElfR8: return spv::ImageFormatR8;
1080 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1081 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1082 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1083 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1084 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1085 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1086 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1087 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1088 case glslang::ElfR32i: return spv::ImageFormatR32i;
1089 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1090 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1091 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1092 case glslang::ElfR16i: return spv::ImageFormatR16i;
1093 case glslang::ElfR8i: return spv::ImageFormatR8i;
1094 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1095 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1096 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1097 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1098 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1099 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1100 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1101 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1102 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1103 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001104 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001105 }
1106}
1107
John Kesseniche18fd202018-01-30 11:01:39 -07001108spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001109{
John Kesseniche18fd202018-01-30 11:01:39 -07001110 if (selectionNode.getFlatten())
1111 return spv::SelectionControlFlattenMask;
1112 if (selectionNode.getDontFlatten())
1113 return spv::SelectionControlDontFlattenMask;
1114 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001115}
1116
John Kesseniche18fd202018-01-30 11:01:39 -07001117spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001118{
John Kesseniche18fd202018-01-30 11:01:39 -07001119 if (switchNode.getFlatten())
1120 return spv::SelectionControlFlattenMask;
1121 if (switchNode.getDontFlatten())
1122 return spv::SelectionControlDontFlattenMask;
1123 return spv::SelectionControlMaskNone;
1124}
1125
John Kessenicha2858d92018-01-31 08:11:18 -07001126// return a non-0 dependency if the dependency argument must be set
1127spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001128 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001129{
1130 spv::LoopControlMask control = spv::LoopControlMaskNone;
1131
1132 if (loopNode.getDontUnroll())
1133 control = control | spv::LoopControlDontUnrollMask;
1134 if (loopNode.getUnroll())
1135 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001136 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001137 control = control | spv::LoopControlDependencyInfiniteMask;
1138 else if (loopNode.getLoopDependency() > 0) {
1139 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001140 operands.push_back((unsigned int)loopNode.getLoopDependency());
1141 }
1142 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1143 if (loopNode.getMinIterations() > 0) {
1144 control = control | spv::LoopControlMinIterationsMask;
1145 operands.push_back(loopNode.getMinIterations());
1146 }
1147 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1148 control = control | spv::LoopControlMaxIterationsMask;
1149 operands.push_back(loopNode.getMaxIterations());
1150 }
1151 if (loopNode.getIterationMultiple() > 1) {
1152 control = control | spv::LoopControlIterationMultipleMask;
1153 operands.push_back(loopNode.getIterationMultiple());
1154 }
1155 if (loopNode.getPeelCount() > 0) {
1156 control = control | spv::LoopControlPeelCountMask;
1157 operands.push_back(loopNode.getPeelCount());
1158 }
1159 if (loopNode.getPartialCount() > 0) {
1160 control = control | spv::LoopControlPartialCountMask;
1161 operands.push_back(loopNode.getPartialCount());
1162 }
John Kessenicha2858d92018-01-31 08:11:18 -07001163 }
John Kesseniche18fd202018-01-30 11:01:39 -07001164
1165 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001166}
1167
John Kessenicha5c5fb62017-05-05 05:09:58 -06001168// Translate glslang type to SPIR-V storage class.
1169spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1170{
1171 if (type.getQualifier().isPipeInput())
1172 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001173 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001174 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001175
1176 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001177 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001178 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001179 return spv::StorageClassAtomicCounter;
1180 if (type.containsOpaque())
1181 return spv::StorageClassUniformConstant;
1182 }
1183
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001184 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001185 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001186 return spv::StorageClassShaderRecordBufferNV;
1187 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001188
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001190 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001191 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001192 }
1193
1194 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001195 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001196 return spv::StorageClassPushConstant;
1197 if (type.getBasicType() == glslang::EbtBlock)
1198 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001199 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001200 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001201
1202 switch (type.getQualifier().storage) {
John Kessenichbed4e4f2017-09-08 02:38:07 -06001203 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1204 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1205 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenicha28f7a72019-08-06 07:00:58 -06001206#ifndef GLSLANG_WEB
John Kessenichdeec1932019-08-13 08:00:30 -06001207 case glslang::EvqShared: return spv::StorageClassWorkgroup;
Ashwin Leleff1783d2018-10-22 16:41:44 -07001208 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1209 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1210 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1211 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1212 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001213#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001214 default:
1215 assert(0);
1216 break;
1217 }
1218
1219 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001220}
1221
John Kessenich5611c6d2018-04-05 11:25:02 -06001222// Add capabilities pertaining to how an array is indexed.
1223void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1224 const glslang::TType& indexType)
1225{
John Kessenichb9197c82019-08-11 07:41:45 -06001226#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001227 if (indexType.getQualifier().isNonUniform()) {
1228 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001229 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001230 if (baseType.getBasicType() == glslang::EbtSampler) {
1231 if (baseType.getQualifier().hasAttachment())
1232 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001233 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001234 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001235 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001236 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1237 else if (baseType.isImage())
1238 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1239 else if (baseType.isTexture())
1240 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1241 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1242 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1243 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1244 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1245 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1246 }
1247 } else {
1248 // assume a dynamically uniform index
1249 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001250 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001251 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001253 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001254 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001255 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001256 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001257 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001258 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001259 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001260 }
1261 }
John Kessenichb9197c82019-08-11 07:41:45 -06001262#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001263}
1264
qining25262b32016-05-06 17:25:16 -04001265// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001266// descriptor set.
1267bool IsDescriptorResource(const glslang::TType& type)
1268{
John Kessenichf7497e22016-03-08 21:36:22 -07001269 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001270 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001271 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001272 ! type.getQualifier().isShaderRecordNV() &&
1273 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001274
1275 // non block...
1276 // basically samplerXXX/subpass/sampler/texture are all included
1277 // if they are the global-scope-class, not the function parameter
1278 // (or local, if they ever exist) class.
1279 if (type.getBasicType() == glslang::EbtSampler)
1280 return type.getQualifier().isUniformOrBuffer();
1281
1282 // None of the above.
1283 return false;
1284}
1285
John Kesseniche0b6cad2015-12-24 10:30:13 -07001286void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1287{
1288 if (child.layoutMatrix == glslang::ElmNone)
1289 child.layoutMatrix = parent.layoutMatrix;
1290
1291 if (parent.invariant)
1292 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001293 if (parent.flat)
1294 child.flat = true;
1295 if (parent.centroid)
1296 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001297#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001298 if (parent.nopersp)
1299 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001300 if (parent.explicitInterp)
1301 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001302 if (parent.perPrimitiveNV)
1303 child.perPrimitiveNV = true;
1304 if (parent.perViewNV)
1305 child.perViewNV = true;
1306 if (parent.perTaskNV)
1307 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001308 if (parent.patch)
1309 child.patch = true;
1310 if (parent.sample)
1311 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001312 if (parent.coherent)
1313 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001314 if (parent.devicecoherent)
1315 child.devicecoherent = true;
1316 if (parent.queuefamilycoherent)
1317 child.queuefamilycoherent = true;
1318 if (parent.workgroupcoherent)
1319 child.workgroupcoherent = true;
1320 if (parent.subgroupcoherent)
1321 child.subgroupcoherent = true;
1322 if (parent.nonprivate)
1323 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001324 if (parent.volatil)
1325 child.volatil = true;
1326 if (parent.restrict)
1327 child.restrict = true;
1328 if (parent.readonly)
1329 child.readonly = true;
1330 if (parent.writeonly)
1331 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001332#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001333}
1334
John Kessenichf2b7f332016-09-01 17:05:23 -06001335bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001336{
John Kessenich7b9fa252016-01-21 18:56:57 -07001337 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001338 // - struct members might inherit from a struct declaration
1339 // (note that non-block structs don't explicitly inherit,
1340 // only implicitly, meaning no decoration involved)
1341 // - affect decorations on the struct members
1342 // (note smooth does not, and expecting something like volatile
1343 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001344 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001345 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001346}
1347
John Kessenich140f3df2015-06-26 16:58:36 -06001348//
1349// Implement the TGlslangToSpvTraverser class.
1350//
1351
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001352TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001353 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1354 : TIntermTraverser(true, false, true),
1355 options(options),
1356 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001357 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001358 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001359 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001360 glslangIntermediate(glslangIntermediate),
1361 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001362{
1363 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1364
1365 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001366 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1367 glslangIntermediate->getVersion());
1368
John Kessenich121853f2017-05-31 17:11:16 -06001369 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001370 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001371 builder.setSourceFile(glslangIntermediate->getSourceFile());
1372
1373 // Set the source shader's text. If for SPV version 1.0, include
1374 // a preamble in comments stating the OpModuleProcessed instructions.
1375 // Otherwise, emit those as actual instructions.
1376 std::string text;
1377 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1378 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001379 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001380 text.append("// OpModuleProcessed ");
1381 text.append(processes[p]);
1382 text.append("\n");
1383 } else
1384 builder.addModuleProcessed(processes[p]);
1385 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001386 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001387 text.append("#line 1\n");
1388 text.append(glslangIntermediate->getSourceText());
1389 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001390 // Pass name and text for all included files
1391 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1392 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1393 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001394 }
John Kessenich140f3df2015-06-26 16:58:36 -06001395 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001396
1397 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1398 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1399
1400 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1401 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001402 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001403 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1404 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001405 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001406 memoryModel = spv::MemoryModelVulkanKHR;
1407 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001408 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001409 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001410 builder.setMemoryModel(addressingModel, memoryModel);
1411
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001412 if (glslangIntermediate->usingVariablePointers()) {
1413 builder.addCapability(spv::CapabilityVariablePointers);
1414 }
1415
John Kessenicheee9d532016-09-19 18:09:30 -06001416 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1417 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001418
1419 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001420 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1421 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001422 builder.addSourceExtension(it->c_str());
1423
1424 // Add the top-level modes for this shader.
1425
John Kessenich92187592016-02-01 13:45:25 -07001426 if (glslangIntermediate->getXfbMode()) {
1427 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001429 }
John Kessenich140f3df2015-06-26 16:58:36 -06001430
1431 unsigned int mode;
1432 switch (glslangIntermediate->getStage()) {
1433 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001434 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001435 break;
1436
John Kessenicha28f7a72019-08-06 07:00:58 -06001437 case EShLangFragment:
1438 builder.addCapability(spv::CapabilityShader);
1439 if (glslangIntermediate->getPixelCenterInteger())
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1441
1442 if (glslangIntermediate->getOriginUpperLeft())
1443 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1444 else
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1446
1447 if (glslangIntermediate->getEarlyFragmentTests())
1448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1449
1450 if (glslangIntermediate->getPostDepthCoverage()) {
1451 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1452 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1453 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1454 }
1455
John Kessenichb9197c82019-08-11 07:41:45 -06001456 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1457 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1458
1459#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001460 switch(glslangIntermediate->getDepth()) {
1461 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1462 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1463 default: mode = spv::ExecutionModeMax; break;
1464 }
1465 if (mode != spv::ExecutionModeMax)
1466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001467 switch (glslangIntermediate->getInterlockOrdering()) {
1468 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1469 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1470 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1471 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1472 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1473 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1474 default: mode = spv::ExecutionModeMax; break;
1475 }
1476 if (mode != spv::ExecutionModeMax) {
1477 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1478 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1479 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1480 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1481 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1482 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1483 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1484 } else {
1485 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1486 }
1487 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1488 }
John Kessenichb9197c82019-08-11 07:41:45 -06001489#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001490 break;
1491
John Kessenicha28f7a72019-08-06 07:00:58 -06001492 case EShLangCompute:
1493 builder.addCapability(spv::CapabilityShader);
1494 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1495 glslangIntermediate->getLocalSize(1),
1496 glslangIntermediate->getLocalSize(2));
John Kessenich51ed01c2019-10-10 11:40:11 -06001497#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001498 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1499 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1500 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1501 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1502 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1503 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1504 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1505 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1506 }
John Kessenich51ed01c2019-10-10 11:40:11 -06001507#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001508 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001509#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001510 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001511 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001512 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001513
steve-lunarge7412492017-03-23 11:56:07 -06001514 glslang::TLayoutGeometry primitive;
1515
1516 if (glslangIntermediate->getStage() == EShLangTessControl) {
1517 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1518 primitive = glslangIntermediate->getOutputPrimitive();
1519 } else {
1520 primitive = glslangIntermediate->getInputPrimitive();
1521 }
1522
1523 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001524 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1525 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1526 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001527 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001528 }
John Kessenich4016e382016-07-15 11:53:56 -06001529 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001530 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1531
John Kesseniche6903322015-10-13 16:29:02 -06001532 switch (glslangIntermediate->getVertexSpacing()) {
1533 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1534 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1535 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001536 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001537 }
John Kessenich4016e382016-07-15 11:53:56 -06001538 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001539 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1540
1541 switch (glslangIntermediate->getVertexOrder()) {
1542 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1543 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001544 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001545 }
John Kessenich4016e382016-07-15 11:53:56 -06001546 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001547 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1548
1549 if (glslangIntermediate->getPointMode())
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001551 break;
1552
1553 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001554 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001555 switch (glslangIntermediate->getInputPrimitive()) {
1556 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1557 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1558 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001559 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001560 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001561 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001562 }
John Kessenich4016e382016-07-15 11:53:56 -06001563 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001564 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001565
John Kessenich140f3df2015-06-26 16:58:36 -06001566 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1567
1568 switch (glslangIntermediate->getOutputPrimitive()) {
1569 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1570 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1571 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001572 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001573 }
John Kessenich4016e382016-07-15 11:53:56 -06001574 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001575 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1576 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1577 break;
1578
Chao Chenb50c02e2018-09-19 11:42:24 -07001579 case EShLangRayGenNV:
1580 case EShLangIntersectNV:
1581 case EShLangAnyHitNV:
1582 case EShLangClosestHitNV:
1583 case EShLangMissNV:
1584 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001585 builder.addCapability(spv::CapabilityRayTracingNV);
1586 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001587 break;
Chao Chen3c366992018-09-19 11:41:59 -07001588 case EShLangTaskNV:
1589 case EShLangMeshNV:
1590 builder.addCapability(spv::CapabilityMeshShadingNV);
1591 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1592 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1593 glslangIntermediate->getLocalSize(1),
1594 glslangIntermediate->getLocalSize(2));
1595 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1596 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1598
1599 switch (glslangIntermediate->getOutputPrimitive()) {
1600 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1601 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1602 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1603 default: mode = spv::ExecutionModeMax; break;
1604 }
1605 if (mode != spv::ExecutionModeMax)
1606 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1607 }
1608 break;
1609#endif
1610
John Kessenich140f3df2015-06-26 16:58:36 -06001611 default:
1612 break;
1613 }
John Kessenich140f3df2015-06-26 16:58:36 -06001614}
1615
John Kessenichfca82622016-11-26 13:23:20 -07001616// Finish creating SPV, after the traversal is complete.
1617void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001618{
John Kessenichf04c51b2018-08-03 15:56:12 -06001619 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001620 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001621 builder.setBuildPoint(shaderEntry->getLastBlock());
1622 builder.leaveFunction();
1623 }
1624
John Kessenich7ba63412015-12-20 17:37:07 -07001625 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001626 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1627 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001628
John Kessenich23d27752019-07-28 02:12:10 -06001629#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001630 // Add capabilities, extensions, remove unneeded decorations, etc.,
1631 // based on the resulting SPIR-V.
1632 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001633#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001634}
1635
John Kessenichfca82622016-11-26 13:23:20 -07001636// Write the SPV into 'out'.
1637void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001638{
John Kessenichfca82622016-11-26 13:23:20 -07001639 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001640}
1641
1642//
1643// Implement the traversal functions.
1644//
1645// Return true from interior nodes to have the external traversal
1646// continue on to children. Return false if children were
1647// already processed.
1648//
1649
1650//
qining25262b32016-05-06 17:25:16 -04001651// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001652// - uniform/input reads
1653// - output writes
1654// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1655// - something simple that degenerates into the last bullet
1656//
1657void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1658{
qining75d1d802016-04-06 14:42:01 -04001659 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1660 if (symbol->getType().getQualifier().isSpecConstant())
1661 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1662
John Kessenich140f3df2015-06-26 16:58:36 -06001663 // getSymbolId() will set up all the IO decorations on the first call.
1664 // Formal function parameters were mapped during makeFunctions().
1665 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001666
John Kessenich7ba63412015-12-20 17:37:07 -07001667 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001668 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001669 // Consider adding to the OpEntryPoint interface list.
1670 // Only looking at structures if they have at least one member.
1671 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1672 spv::StorageClass sc = builder.getStorageClass(id);
1673 // Before SPIR-V 1.4, we only want to include Input and Output.
1674 // Starting with SPIR-V 1.4, we want all globals.
1675 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1676 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001677 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001678 }
John Kessenich5f77d862017-09-19 11:09:59 -06001679 }
John Kessenich9c14f772019-06-17 08:38:35 -06001680
1681 // If the SPIR-V type is required to be different than the AST type,
1682 // translate now from the SPIR-V type to the AST type, for the consuming
1683 // operation.
1684 // Note this turns it from an l-value to an r-value.
1685 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1686 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1687 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001688 }
1689
1690 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001691 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001692 // Prepare to generate code for the access
1693
1694 // L-value chains will be computed left to right. We're on the symbol now,
1695 // which is the left-most part of the access chain, so now is "clear" time,
1696 // followed by setting the base.
1697 builder.clearAccessChain();
1698
1699 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001700 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001701 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001702 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001703 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001704 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001705 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001706 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001707 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1708 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001709 builder.setAccessChainRValue(id);
1710 else
1711 builder.setAccessChainLValue(id);
1712 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001713
John Kessenichb9197c82019-08-11 07:41:45 -06001714#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001715 // Process linkage-only nodes for any special additional interface work.
1716 if (linkageOnly) {
1717 if (glslangIntermediate->getHlslFunctionality1()) {
1718 // Map implicit counter buffers to their originating buffers, which should have been
1719 // seen by now, given earlier pruning of unused counters, and preservation of order
1720 // of declaration.
1721 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1722 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1723 // Save possible originating buffers for counter buffers, keyed by
1724 // making the potential counter-buffer name.
1725 std::string keyName = symbol->getName().c_str();
1726 keyName = glslangIntermediate->addCounterBufferName(keyName);
1727 counterOriginator[keyName] = symbol;
1728 } else {
1729 // Handle a counter buffer, by finding the saved originating buffer.
1730 std::string keyName = symbol->getName().c_str();
1731 auto it = counterOriginator.find(keyName);
1732 if (it != counterOriginator.end()) {
1733 id = getSymbolId(it->second);
1734 if (id != spv::NoResult) {
1735 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001736 if (counterId != spv::NoResult) {
1737 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001738 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001739 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001740 }
1741 }
1742 }
1743 }
1744 }
1745 }
John Kessenich155d3512019-08-08 23:29:20 -06001746#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001747}
1748
1749bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1750{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001751 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001752
qining40887662016-04-03 22:20:42 -04001753 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1754 if (node->getType().getQualifier().isSpecConstant())
1755 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1756
John Kessenich140f3df2015-06-26 16:58:36 -06001757 // First, handle special cases
1758 switch (node->getOp()) {
1759 case glslang::EOpAssign:
1760 case glslang::EOpAddAssign:
1761 case glslang::EOpSubAssign:
1762 case glslang::EOpMulAssign:
1763 case glslang::EOpVectorTimesMatrixAssign:
1764 case glslang::EOpVectorTimesScalarAssign:
1765 case glslang::EOpMatrixTimesScalarAssign:
1766 case glslang::EOpMatrixTimesMatrixAssign:
1767 case glslang::EOpDivAssign:
1768 case glslang::EOpModAssign:
1769 case glslang::EOpAndAssign:
1770 case glslang::EOpInclusiveOrAssign:
1771 case glslang::EOpExclusiveOrAssign:
1772 case glslang::EOpLeftShiftAssign:
1773 case glslang::EOpRightShiftAssign:
1774 // A bin-op assign "a += b" means the same thing as "a = a + b"
1775 // where a is evaluated before b. For a simple assignment, GLSL
1776 // says to evaluate the left before the right. So, always, left
1777 // node then right node.
1778 {
1779 // get the left l-value, save it away
1780 builder.clearAccessChain();
1781 node->getLeft()->traverse(this);
1782 spv::Builder::AccessChain lValue = builder.getAccessChain();
1783
1784 // evaluate the right
1785 builder.clearAccessChain();
1786 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001787 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001788
1789 if (node->getOp() != glslang::EOpAssign) {
1790 // the left is also an r-value
1791 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001792 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001793
1794 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001795 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001796 TranslateNoContractionDecoration(node->getType().getQualifier()),
1797 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001798 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001799 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1800 node->getType().getBasicType());
1801
1802 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001803 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001804 }
1805
1806 // store the result
1807 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001808 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001809
1810 // assignments are expressions having an rValue after they are evaluated...
1811 builder.clearAccessChain();
1812 builder.setAccessChainRValue(rValue);
1813 }
1814 return false;
1815 case glslang::EOpIndexDirect:
1816 case glslang::EOpIndexDirectStruct:
1817 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001818 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001819 // Get the left part of the access chain.
1820 node->getLeft()->traverse(this);
1821
1822 // Add the next element in the chain
1823
David Netoa901ffe2016-06-08 14:11:40 +01001824 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001825 if (! node->getLeft()->getType().isArray() &&
1826 node->getLeft()->getType().isVector() &&
1827 node->getOp() == glslang::EOpIndexDirect) {
1828 // This is essentially a hard-coded vector swizzle of size 1,
1829 // so short circuit the access-chain stuff with a swizzle.
1830 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001831 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001832 int dummySize;
1833 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1834 TranslateCoherent(node->getLeft()->getType()),
1835 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001836 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001837
1838 // Load through a block reference is performed with a dot operator that
1839 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1840 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001841 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001842 !node->getLeft()->getType().isArray() &&
1843 node->getOp() == glslang::EOpIndexDirectStruct)
1844 {
1845 spv::Id left = accessChainLoad(node->getLeft()->getType());
1846 builder.clearAccessChain();
1847 builder.setAccessChainLValue(left);
1848 }
1849
David Netoa901ffe2016-06-08 14:11:40 +01001850 int spvIndex = glslangIndex;
1851 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1852 node->getOp() == glslang::EOpIndexDirectStruct)
1853 {
1854 // This may be, e.g., an anonymous block-member selection, which generally need
1855 // index remapping due to hidden members in anonymous blocks.
1856 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1857 assert(remapper.size() > 0);
1858 spvIndex = remapper[glslangIndex];
1859 }
John Kessenichebb50532016-05-16 19:22:05 -06001860
David Netoa901ffe2016-06-08 14:11:40 +01001861 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001862 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001863
1864 // Add capabilities here for accessing PointSize and clip/cull distance.
1865 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001866 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001867 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001868 }
1869 }
1870 return false;
1871 case glslang::EOpIndexIndirect:
1872 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001873 // Array, matrix, or vector indirection with variable index.
1874 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001875 // matrices are arrays of vectors, so will also work for a matrix.
1876 // Will use the access chain's 'component' for variable index into a vector.
1877
1878 // This adapter is building access chains left to right.
1879 // Set up the access chain to the left.
1880 node->getLeft()->traverse(this);
1881
1882 // save it so that computing the right side doesn't trash it
1883 spv::Builder::AccessChain partial = builder.getAccessChain();
1884
1885 // compute the next index in the chain
1886 builder.clearAccessChain();
1887 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001888 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001889
John Kessenich5611c6d2018-04-05 11:25:02 -06001890 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1891
John Kessenich140f3df2015-06-26 16:58:36 -06001892 // restore the saved access chain
1893 builder.setAccessChain(partial);
1894
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001895 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1896 int dummySize;
1897 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1898 TranslateCoherent(node->getLeft()->getType()),
1899 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1900 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001901 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001902 }
1903 return false;
1904 case glslang::EOpVectorSwizzle:
1905 {
1906 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001907 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001908 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001909 int dummySize;
1910 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1911 TranslateCoherent(node->getLeft()->getType()),
1912 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001913 }
1914 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001915 case glslang::EOpMatrixSwizzle:
1916 logger->missingFunctionality("matrix swizzle");
1917 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001918 case glslang::EOpLogicalOr:
1919 case glslang::EOpLogicalAnd:
1920 {
1921
1922 // These may require short circuiting, but can sometimes be done as straight
1923 // binary operations. The right operand must be short circuited if it has
1924 // side effects, and should probably be if it is complex.
1925 if (isTrivial(node->getRight()->getAsTyped()))
1926 break; // handle below as a normal binary operation
1927 // otherwise, we need to do dynamic short circuiting on the right operand
1928 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1929 builder.clearAccessChain();
1930 builder.setAccessChainRValue(result);
1931 }
1932 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001933 default:
1934 break;
1935 }
1936
1937 // Assume generic binary op...
1938
John Kessenich32cfd492016-02-02 12:37:46 -07001939 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001940 builder.clearAccessChain();
1941 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001942 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001943
John Kessenich32cfd492016-02-02 12:37:46 -07001944 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001945 builder.clearAccessChain();
1946 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001947 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001948
John Kessenich32cfd492016-02-02 12:37:46 -07001949 // get result
John Kessenichead86222018-03-28 18:01:20 -06001950 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001951 TranslateNoContractionDecoration(node->getType().getQualifier()),
1952 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001953 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001954 convertGlslangToSpvType(node->getType()), left, right,
1955 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001956
John Kessenich50e57562015-12-21 21:21:11 -07001957 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001958 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001959 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001960 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001961 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001962 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001963 return false;
1964 }
John Kessenich140f3df2015-06-26 16:58:36 -06001965}
1966
John Kessenich9c14f772019-06-17 08:38:35 -06001967// Figure out what, if any, type changes are needed when accessing a specific built-in.
1968// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1969// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1970std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1971 const glslang::TType& glslangType)
1972{
1973 switch(builtIn)
1974 {
1975 case spv::BuiltInSubgroupEqMask:
1976 case spv::BuiltInSubgroupGeMask:
1977 case spv::BuiltInSubgroupGtMask:
1978 case spv::BuiltInSubgroupLeMask:
1979 case spv::BuiltInSubgroupLtMask: {
1980 // these require changing a 64-bit scaler -> a vector of 32-bit components
1981 if (glslangType.isVector())
1982 break;
1983 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1984 builder.makeUintType(64));
1985 return ret;
1986 }
1987 default:
1988 break;
1989 }
1990
1991 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1992 return ret;
1993}
1994
1995// For an object previously identified (see getForcedType() and forceType)
1996// as needing type translations, do the translation needed for a load, turning
1997// an L-value into in R-value.
1998spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1999{
2000 const auto forceIt = forceType.find(object);
2001 if (forceIt == forceType.end())
2002 return object;
2003
2004 spv::Id desiredTypeId = forceIt->second;
2005 spv::Id objectTypeId = builder.getTypeId(object);
2006 assert(builder.isPointerType(objectTypeId));
2007 objectTypeId = builder.getContainedTypeId(objectTypeId);
2008 if (builder.isVectorType(objectTypeId) &&
2009 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2010 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2011 // handle 32-bit v.xy* -> 64-bit
2012 builder.clearAccessChain();
2013 builder.setAccessChainLValue(object);
2014 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2015 std::vector<spv::Id> components;
2016 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2017 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2018
2019 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2020 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2021 builder.createCompositeConstruct(vecType, components));
2022 } else {
2023 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2024 }
2025 } else {
2026 logger->missingFunctionality("forcing non 32-bit vector type");
2027 }
2028
2029 return object;
2030}
2031
John Kessenich140f3df2015-06-26 16:58:36 -06002032bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2033{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002034 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002035
qining40887662016-04-03 22:20:42 -04002036 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2037 if (node->getType().getQualifier().isSpecConstant())
2038 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2039
John Kessenichfc51d282015-08-19 13:34:18 -06002040 spv::Id result = spv::NoResult;
2041
2042 // try texturing first
2043 result = createImageTextureFunctionCall(node);
2044 if (result != spv::NoResult) {
2045 builder.clearAccessChain();
2046 builder.setAccessChainRValue(result);
2047
2048 return false; // done with this node
2049 }
2050
2051 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002052
2053 if (node->getOp() == glslang::EOpArrayLength) {
2054 // Quite special; won't want to evaluate the operand.
2055
John Kessenich5611c6d2018-04-05 11:25:02 -06002056 // Currently, the front-end does not allow .length() on an array until it is sized,
2057 // except for the last block membeor of an SSBO.
2058 // TODO: If this changes, link-time sized arrays might show up here, and need their
2059 // size extracted.
2060
John Kessenichc9a80832015-09-12 12:17:44 -06002061 // Normal .length() would have been constant folded by the front-end.
2062 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002063 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002064
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002065 spv::Id length;
2066 if (node->getOperand()->getType().isCoopMat()) {
2067 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2068
2069 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2070 assert(builder.isCooperativeMatrixType(typeId));
2071
2072 length = builder.createCooperativeMatrixLength(typeId);
2073 } else {
2074 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2075 block->traverse(this);
2076 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2077 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2078 }
John Kessenichc9a80832015-09-12 12:17:44 -06002079
John Kessenich8c869672018-11-28 07:01:37 -07002080 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2081 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2082 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002083 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2084 if (builder.isInSpecConstCodeGenMode()) {
2085 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2086 } else {
2087 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2088 }
2089 }
John Kessenich8c869672018-11-28 07:01:37 -07002090
John Kessenichc9a80832015-09-12 12:17:44 -06002091 builder.clearAccessChain();
2092 builder.setAccessChainRValue(length);
2093
2094 return false;
2095 }
2096
John Kessenichfc51d282015-08-19 13:34:18 -06002097 // Start by evaluating the operand
2098
John Kessenich8c8505c2016-07-26 12:50:38 -06002099 // Does it need a swizzle inversion? If so, evaluation is inverted;
2100 // operate first on the swizzle base, then apply the swizzle.
2101 spv::Id invertedType = spv::NoType;
2102 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2103 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2104 invertedType = getInvertedSwizzleType(*node->getOperand());
2105
John Kessenich140f3df2015-06-26 16:58:36 -06002106 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002107 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002108 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002109 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002110 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002111 operandNode = node->getOperand();
2112
2113 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002114
Rex Xufc618912015-09-09 16:42:49 +08002115 spv::Id operand = spv::NoResult;
2116
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002117 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2118
John Kessenichfb4f2332019-08-09 03:49:15 -06002119#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002120 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2121 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002122 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002123 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002124 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002125 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2126 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2127 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002128#endif
2129 {
John Kessenich32cfd492016-02-02 12:37:46 -07002130 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002131 }
John Kessenich140f3df2015-06-26 16:58:36 -06002132
John Kessenichead86222018-03-28 18:01:20 -06002133 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002134 TranslateNoContractionDecoration(node->getType().getQualifier()),
2135 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002136
2137 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002138 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002139 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002140
2141 // if not, then possibly an operation
2142 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002143 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002144
2145 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002146 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002147 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002148 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002149 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002150
John Kessenich140f3df2015-06-26 16:58:36 -06002151 builder.clearAccessChain();
2152 builder.setAccessChainRValue(result);
2153
2154 return false; // done with this node
2155 }
2156
2157 // it must be a special case, check...
2158 switch (node->getOp()) {
2159 case glslang::EOpPostIncrement:
2160 case glslang::EOpPostDecrement:
2161 case glslang::EOpPreIncrement:
2162 case glslang::EOpPreDecrement:
2163 {
2164 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002165 spv::Id one = 0;
2166 if (node->getBasicType() == glslang::EbtFloat)
2167 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002168#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002169 else if (node->getBasicType() == glslang::EbtDouble)
2170 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002171 else if (node->getBasicType() == glslang::EbtFloat16)
2172 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002173 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2174 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002175 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2176 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002177 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2178 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002179#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002180 else
2181 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002182 glslang::TOperator op;
2183 if (node->getOp() == glslang::EOpPreIncrement ||
2184 node->getOp() == glslang::EOpPostIncrement)
2185 op = glslang::EOpAdd;
2186 else
2187 op = glslang::EOpSub;
2188
John Kessenichead86222018-03-28 18:01:20 -06002189 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002190 convertGlslangToSpvType(node->getType()), operand, one,
2191 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002192 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002193
2194 // The result of operation is always stored, but conditionally the
2195 // consumed result. The consumed result is always an r-value.
2196 builder.accessChainStore(result);
2197 builder.clearAccessChain();
2198 if (node->getOp() == glslang::EOpPreIncrement ||
2199 node->getOp() == glslang::EOpPreDecrement)
2200 builder.setAccessChainRValue(result);
2201 else
2202 builder.setAccessChainRValue(operand);
2203 }
2204
2205 return false;
2206
John Kessenich155d3512019-08-08 23:29:20 -06002207#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002208 case glslang::EOpEmitStreamVertex:
2209 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2210 return false;
2211 case glslang::EOpEndStreamPrimitive:
2212 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2213 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002214#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002215
2216 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002217 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002218 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002219 }
John Kessenich140f3df2015-06-26 16:58:36 -06002220}
2221
Jeff Bolz53134492019-06-25 13:31:10 -05002222// Construct a composite object, recursively copying members if their types don't match
2223spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2224{
2225 for (int c = 0; c < (int)constituents.size(); ++c) {
2226 spv::Id& constituent = constituents[c];
2227 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2228 spv::Id rType = builder.getTypeId(constituent);
2229 if (lType != rType) {
2230 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2231 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2232 } else if (builder.isStructType(rType)) {
2233 std::vector<spv::Id> rTypeConstituents;
2234 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2235 for (int i = 0; i < numrTypeConstituents; ++i) {
2236 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2237 }
2238 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2239 } else {
2240 assert(builder.isArrayType(rType));
2241 std::vector<spv::Id> rTypeConstituents;
2242 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2243
2244 spv::Id elementRType = builder.getContainedTypeId(rType);
2245 for (int i = 0; i < numrTypeConstituents; ++i) {
2246 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2247 }
2248 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2249 }
2250 }
2251 }
2252 return builder.createCompositeConstruct(resultTypeId, constituents);
2253}
2254
John Kessenich140f3df2015-06-26 16:58:36 -06002255bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2256{
qining27e04a02016-04-14 16:40:20 -04002257 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2258 if (node->getType().getQualifier().isSpecConstant())
2259 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2260
John Kessenichfc51d282015-08-19 13:34:18 -06002261 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002262 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2263 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002264
2265 // try texturing
2266 result = createImageTextureFunctionCall(node);
2267 if (result != spv::NoResult) {
2268 builder.clearAccessChain();
2269 builder.setAccessChainRValue(result);
2270
2271 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002272 }
2273#ifndef GLSLANG_WEB
2274 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002275 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002276 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002277 // "imageStore" is a special case, which has no result
2278 return false;
2279 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002280#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002281
John Kessenich140f3df2015-06-26 16:58:36 -06002282 glslang::TOperator binOp = glslang::EOpNull;
2283 bool reduceComparison = true;
2284 bool isMatrix = false;
2285 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002286 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002287
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002288 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2289
John Kessenich140f3df2015-06-26 16:58:36 -06002290 assert(node->getOp());
2291
John Kessenichf6640762016-08-01 19:44:00 -06002292 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002293
2294 switch (node->getOp()) {
2295 case glslang::EOpSequence:
2296 {
2297 if (preVisit)
2298 ++sequenceDepth;
2299 else
2300 --sequenceDepth;
2301
2302 if (sequenceDepth == 1) {
2303 // If this is the parent node of all the functions, we want to see them
2304 // early, so all call points have actual SPIR-V functions to reference.
2305 // In all cases, still let the traverser visit the children for us.
2306 makeFunctions(node->getAsAggregate()->getSequence());
2307
John Kessenich6fccb3c2016-09-19 16:01:41 -06002308 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002309 // anything else gets there, so visit out of order, doing them all now.
2310 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2311
John Kessenich6a60c2f2016-12-08 21:01:59 -07002312 // 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 -06002313 // so do them manually.
2314 visitFunctions(node->getAsAggregate()->getSequence());
2315
2316 return false;
2317 }
2318
2319 return true;
2320 }
2321 case glslang::EOpLinkerObjects:
2322 {
2323 if (visit == glslang::EvPreVisit)
2324 linkageOnly = true;
2325 else
2326 linkageOnly = false;
2327
2328 return true;
2329 }
2330 case glslang::EOpComma:
2331 {
2332 // processing from left to right naturally leaves the right-most
2333 // lying around in the access chain
2334 glslang::TIntermSequence& glslangOperands = node->getSequence();
2335 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2336 glslangOperands[i]->traverse(this);
2337
2338 return false;
2339 }
2340 case glslang::EOpFunction:
2341 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002342 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002343 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002344 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002345 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002346 } else {
2347 handleFunctionEntry(node);
2348 }
2349 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002350 if (inEntryPoint)
2351 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002352 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002353 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002354 }
2355
2356 return true;
2357 case glslang::EOpParameters:
2358 // Parameters will have been consumed by EOpFunction processing, but not
2359 // the body, so we still visited the function node's children, making this
2360 // child redundant.
2361 return false;
2362 case glslang::EOpFunctionCall:
2363 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002364 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002365 if (node->isUserDefined())
2366 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002367 // 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 -07002368 if (result) {
2369 builder.clearAccessChain();
2370 builder.setAccessChainRValue(result);
2371 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002372 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002373
2374 return false;
2375 }
2376 case glslang::EOpConstructMat2x2:
2377 case glslang::EOpConstructMat2x3:
2378 case glslang::EOpConstructMat2x4:
2379 case glslang::EOpConstructMat3x2:
2380 case glslang::EOpConstructMat3x3:
2381 case glslang::EOpConstructMat3x4:
2382 case glslang::EOpConstructMat4x2:
2383 case glslang::EOpConstructMat4x3:
2384 case glslang::EOpConstructMat4x4:
2385 case glslang::EOpConstructDMat2x2:
2386 case glslang::EOpConstructDMat2x3:
2387 case glslang::EOpConstructDMat2x4:
2388 case glslang::EOpConstructDMat3x2:
2389 case glslang::EOpConstructDMat3x3:
2390 case glslang::EOpConstructDMat3x4:
2391 case glslang::EOpConstructDMat4x2:
2392 case glslang::EOpConstructDMat4x3:
2393 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002394 case glslang::EOpConstructIMat2x2:
2395 case glslang::EOpConstructIMat2x3:
2396 case glslang::EOpConstructIMat2x4:
2397 case glslang::EOpConstructIMat3x2:
2398 case glslang::EOpConstructIMat3x3:
2399 case glslang::EOpConstructIMat3x4:
2400 case glslang::EOpConstructIMat4x2:
2401 case glslang::EOpConstructIMat4x3:
2402 case glslang::EOpConstructIMat4x4:
2403 case glslang::EOpConstructUMat2x2:
2404 case glslang::EOpConstructUMat2x3:
2405 case glslang::EOpConstructUMat2x4:
2406 case glslang::EOpConstructUMat3x2:
2407 case glslang::EOpConstructUMat3x3:
2408 case glslang::EOpConstructUMat3x4:
2409 case glslang::EOpConstructUMat4x2:
2410 case glslang::EOpConstructUMat4x3:
2411 case glslang::EOpConstructUMat4x4:
2412 case glslang::EOpConstructBMat2x2:
2413 case glslang::EOpConstructBMat2x3:
2414 case glslang::EOpConstructBMat2x4:
2415 case glslang::EOpConstructBMat3x2:
2416 case glslang::EOpConstructBMat3x3:
2417 case glslang::EOpConstructBMat3x4:
2418 case glslang::EOpConstructBMat4x2:
2419 case glslang::EOpConstructBMat4x3:
2420 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002421 case glslang::EOpConstructF16Mat2x2:
2422 case glslang::EOpConstructF16Mat2x3:
2423 case glslang::EOpConstructF16Mat2x4:
2424 case glslang::EOpConstructF16Mat3x2:
2425 case glslang::EOpConstructF16Mat3x3:
2426 case glslang::EOpConstructF16Mat3x4:
2427 case glslang::EOpConstructF16Mat4x2:
2428 case glslang::EOpConstructF16Mat4x3:
2429 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002430 isMatrix = true;
2431 // fall through
2432 case glslang::EOpConstructFloat:
2433 case glslang::EOpConstructVec2:
2434 case glslang::EOpConstructVec3:
2435 case glslang::EOpConstructVec4:
2436 case glslang::EOpConstructDouble:
2437 case glslang::EOpConstructDVec2:
2438 case glslang::EOpConstructDVec3:
2439 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002440 case glslang::EOpConstructFloat16:
2441 case glslang::EOpConstructF16Vec2:
2442 case glslang::EOpConstructF16Vec3:
2443 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002444 case glslang::EOpConstructBool:
2445 case glslang::EOpConstructBVec2:
2446 case glslang::EOpConstructBVec3:
2447 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002448 case glslang::EOpConstructInt8:
2449 case glslang::EOpConstructI8Vec2:
2450 case glslang::EOpConstructI8Vec3:
2451 case glslang::EOpConstructI8Vec4:
2452 case glslang::EOpConstructUint8:
2453 case glslang::EOpConstructU8Vec2:
2454 case glslang::EOpConstructU8Vec3:
2455 case glslang::EOpConstructU8Vec4:
2456 case glslang::EOpConstructInt16:
2457 case glslang::EOpConstructI16Vec2:
2458 case glslang::EOpConstructI16Vec3:
2459 case glslang::EOpConstructI16Vec4:
2460 case glslang::EOpConstructUint16:
2461 case glslang::EOpConstructU16Vec2:
2462 case glslang::EOpConstructU16Vec3:
2463 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002464 case glslang::EOpConstructInt:
2465 case glslang::EOpConstructIVec2:
2466 case glslang::EOpConstructIVec3:
2467 case glslang::EOpConstructIVec4:
2468 case glslang::EOpConstructUint:
2469 case glslang::EOpConstructUVec2:
2470 case glslang::EOpConstructUVec3:
2471 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002472 case glslang::EOpConstructInt64:
2473 case glslang::EOpConstructI64Vec2:
2474 case glslang::EOpConstructI64Vec3:
2475 case glslang::EOpConstructI64Vec4:
2476 case glslang::EOpConstructUint64:
2477 case glslang::EOpConstructU64Vec2:
2478 case glslang::EOpConstructU64Vec3:
2479 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002480 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002481 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002482 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002483 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002484 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002485 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002486 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002487 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002488 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002489 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002490 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002491 else if (node->getOp() == glslang::EOpConstructStruct ||
2492 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2493 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002494 std::vector<spv::Id> constituents;
2495 for (int c = 0; c < (int)arguments.size(); ++c)
2496 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002497 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002498 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002499 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002500 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002501 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002502
2503 builder.clearAccessChain();
2504 builder.setAccessChainRValue(constructed);
2505
2506 return false;
2507 }
2508
2509 // These six are component-wise compares with component-wise results.
2510 // Forward on to createBinaryOperation(), requesting a vector result.
2511 case glslang::EOpLessThan:
2512 case glslang::EOpGreaterThan:
2513 case glslang::EOpLessThanEqual:
2514 case glslang::EOpGreaterThanEqual:
2515 case glslang::EOpVectorEqual:
2516 case glslang::EOpVectorNotEqual:
2517 {
2518 // Map the operation to a binary
2519 binOp = node->getOp();
2520 reduceComparison = false;
2521 switch (node->getOp()) {
2522 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2523 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2524 default: binOp = node->getOp(); break;
2525 }
2526
2527 break;
2528 }
2529 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002530 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002531 binOp = glslang::EOpMul;
2532 break;
2533 case glslang::EOpOuterProduct:
2534 // two vectors multiplied to make a matrix
2535 binOp = glslang::EOpOuterProduct;
2536 break;
2537 case glslang::EOpDot:
2538 {
qining25262b32016-05-06 17:25:16 -04002539 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002540 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002541 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002542 binOp = glslang::EOpMul;
2543 break;
2544 }
2545 case glslang::EOpMod:
2546 // when an aggregate, this is the floating-point mod built-in function,
2547 // which can be emitted by the one in createBinaryOperation()
2548 binOp = glslang::EOpMod;
2549 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002550
2551#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002552 case glslang::EOpEmitVertex:
2553 case glslang::EOpEndPrimitive:
2554 case glslang::EOpBarrier:
2555 case glslang::EOpMemoryBarrier:
2556 case glslang::EOpMemoryBarrierAtomicCounter:
2557 case glslang::EOpMemoryBarrierBuffer:
2558 case glslang::EOpMemoryBarrierImage:
2559 case glslang::EOpMemoryBarrierShared:
2560 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002561 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002562 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002563 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002564 case glslang::EOpWorkgroupMemoryBarrier:
2565 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002566 case glslang::EOpSubgroupBarrier:
2567 case glslang::EOpSubgroupMemoryBarrier:
2568 case glslang::EOpSubgroupMemoryBarrierBuffer:
2569 case glslang::EOpSubgroupMemoryBarrierImage:
2570 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002571 noReturnValue = true;
2572 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2573 break;
2574
Jeff Bolz36831c92018-09-05 10:11:41 -05002575 case glslang::EOpAtomicStore:
2576 noReturnValue = true;
2577 // fallthrough
2578 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002579 case glslang::EOpAtomicAdd:
2580 case glslang::EOpAtomicMin:
2581 case glslang::EOpAtomicMax:
2582 case glslang::EOpAtomicAnd:
2583 case glslang::EOpAtomicOr:
2584 case glslang::EOpAtomicXor:
2585 case glslang::EOpAtomicExchange:
2586 case glslang::EOpAtomicCompSwap:
2587 atomic = true;
2588 break;
2589
John Kessenich0d0c6d32017-07-23 16:08:26 -06002590 case glslang::EOpAtomicCounterAdd:
2591 case glslang::EOpAtomicCounterSubtract:
2592 case glslang::EOpAtomicCounterMin:
2593 case glslang::EOpAtomicCounterMax:
2594 case glslang::EOpAtomicCounterAnd:
2595 case glslang::EOpAtomicCounterOr:
2596 case glslang::EOpAtomicCounterXor:
2597 case glslang::EOpAtomicCounterExchange:
2598 case glslang::EOpAtomicCounterCompSwap:
2599 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2600 builder.addCapability(spv::CapabilityAtomicStorageOps);
2601 atomic = true;
2602 break;
2603
Chao Chenb50c02e2018-09-19 11:42:24 -07002604 case glslang::EOpIgnoreIntersectionNV:
2605 case glslang::EOpTerminateRayNV:
2606 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002607 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002608 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2609 noReturnValue = true;
2610 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002611 case glslang::EOpCooperativeMatrixLoad:
2612 case glslang::EOpCooperativeMatrixStore:
2613 noReturnValue = true;
2614 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002615 case glslang::EOpBeginInvocationInterlock:
2616 case glslang::EOpEndInvocationInterlock:
2617 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2618 noReturnValue = true;
2619 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002620#endif
Chao Chen3c366992018-09-19 11:41:59 -07002621
John Kessenich140f3df2015-06-26 16:58:36 -06002622 default:
2623 break;
2624 }
2625
2626 //
2627 // See if it maps to a regular operation.
2628 //
John Kessenich140f3df2015-06-26 16:58:36 -06002629 if (binOp != glslang::EOpNull) {
2630 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2631 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2632 assert(left && right);
2633
2634 builder.clearAccessChain();
2635 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002636 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002637
2638 builder.clearAccessChain();
2639 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002640 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002641
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002642 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002643 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002644 TranslateNoContractionDecoration(node->getType().getQualifier()),
2645 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002646 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002647 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002648 left->getType().getBasicType(), reduceComparison);
2649
2650 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002651 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002652 builder.clearAccessChain();
2653 builder.setAccessChainRValue(result);
2654
2655 return false;
2656 }
2657
John Kessenich426394d2015-07-23 10:22:48 -06002658 //
2659 // Create the list of operands.
2660 //
John Kessenich140f3df2015-06-26 16:58:36 -06002661 glslang::TIntermSequence& glslangOperands = node->getSequence();
2662 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002663 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002664 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002665 // special case l-value operands; there are just a few
2666 bool lvalue = false;
2667 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002668 case glslang::EOpModf:
2669 if (arg == 1)
2670 lvalue = true;
2671 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002672#ifndef GLSLANG_WEB
2673 case glslang::EOpFrexp:
2674 if (arg == 1)
2675 lvalue = true;
2676 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002677 case glslang::EOpInterpolateAtSample:
2678 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002679 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002680 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002681 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002682
2683 // Does it need a swizzle inversion? If so, evaluation is inverted;
2684 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002685 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002686 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2687 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2688 }
Rex Xu7a26c172015-12-08 17:12:09 +08002689 break;
Rex Xud4782c12015-09-06 16:30:11 +08002690 case glslang::EOpAtomicAdd:
2691 case glslang::EOpAtomicMin:
2692 case glslang::EOpAtomicMax:
2693 case glslang::EOpAtomicAnd:
2694 case glslang::EOpAtomicOr:
2695 case glslang::EOpAtomicXor:
2696 case glslang::EOpAtomicExchange:
2697 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002698 case glslang::EOpAtomicLoad:
2699 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002700 case glslang::EOpAtomicCounterAdd:
2701 case glslang::EOpAtomicCounterSubtract:
2702 case glslang::EOpAtomicCounterMin:
2703 case glslang::EOpAtomicCounterMax:
2704 case glslang::EOpAtomicCounterAnd:
2705 case glslang::EOpAtomicCounterOr:
2706 case glslang::EOpAtomicCounterXor:
2707 case glslang::EOpAtomicCounterExchange:
2708 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002709 if (arg == 0)
2710 lvalue = true;
2711 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002712 case glslang::EOpAddCarry:
2713 case glslang::EOpSubBorrow:
2714 if (arg == 2)
2715 lvalue = true;
2716 break;
2717 case glslang::EOpUMulExtended:
2718 case glslang::EOpIMulExtended:
2719 if (arg >= 2)
2720 lvalue = true;
2721 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002722 case glslang::EOpCooperativeMatrixLoad:
2723 if (arg == 0 || arg == 1)
2724 lvalue = true;
2725 break;
2726 case glslang::EOpCooperativeMatrixStore:
2727 if (arg == 1)
2728 lvalue = true;
2729 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002730#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002731 default:
2732 break;
2733 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002734 builder.clearAccessChain();
2735 if (invertedType != spv::NoType && arg == 0)
2736 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2737 else
2738 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002739
John Kessenichb9197c82019-08-11 07:41:45 -06002740#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002741 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2742 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2743
2744 if (arg == 1) {
2745 // fold "element" parameter into the access chain
2746 spv::Builder::AccessChain save = builder.getAccessChain();
2747 builder.clearAccessChain();
2748 glslangOperands[2]->traverse(this);
2749
2750 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2751
2752 builder.setAccessChain(save);
2753
2754 // Point to the first element of the array.
2755 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002756 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002757
2758 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2759 unsigned int alignment = builder.getAccessChain().alignment;
2760
2761 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2762 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2763 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2764 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2765 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2766 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2767 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2768 }
2769
2770 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2771
2772 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2773 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2774 }
2775
2776 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2777 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2778 }
2779 } else if (arg == 2) {
2780 continue;
2781 }
2782 }
John Kessenichb9197c82019-08-11 07:41:45 -06002783#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002784
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002785 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002786 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002787 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2788 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2789 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002790 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002791 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002792 }
John Kessenich140f3df2015-06-26 16:58:36 -06002793 }
John Kessenich426394d2015-07-23 10:22:48 -06002794
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002795 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002796#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002797 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2798 std::vector<spv::IdImmediate> idImmOps;
2799
2800 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2801 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2802 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2803 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2804 // get the pointee type
2805 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2806 assert(builder.isCooperativeMatrixType(typeId));
2807 // do the op
2808 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2809 // store the result to the pointer (out param 'm')
2810 builder.createStore(result, operands[0]);
2811 result = 0;
2812 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2813 std::vector<spv::IdImmediate> idImmOps;
2814
2815 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2816 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2817 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2818 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2819 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2820
2821 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2822 result = 0;
2823 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002824 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002825 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenichb9197c82019-08-11 07:41:45 -06002826 } else
2827#endif
2828 {
John Kessenich426394d2015-07-23 10:22:48 -06002829 // Pass through to generic operations.
2830 switch (glslangOperands.size()) {
2831 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002832 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002833 break;
2834 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002835 {
2836 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002837 TranslateNoContractionDecoration(node->getType().getQualifier()),
2838 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002839 result = createUnaryOperation(
2840 node->getOp(), decorations,
2841 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002842 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002843 }
John Kessenich426394d2015-07-23 10:22:48 -06002844 break;
2845 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002846 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002847 break;
2848 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002849 if (invertedType)
2850 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002851 }
2852
2853 if (noReturnValue)
2854 return false;
2855
2856 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002857 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002858 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002859 } else {
2860 builder.clearAccessChain();
2861 builder.setAccessChainRValue(result);
2862 return false;
2863 }
2864}
2865
John Kessenich433e9ff2017-01-26 20:31:11 -07002866// This path handles both if-then-else and ?:
2867// The if-then-else has a node type of void, while
2868// ?: has either a void or a non-void node type
2869//
2870// Leaving the result, when not void:
2871// GLSL only has r-values as the result of a :?, but
2872// if we have an l-value, that can be more efficient if it will
2873// become the base of a complex r-value expression, because the
2874// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002875bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2876{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002877 // see if OpSelect can handle it
2878 const auto isOpSelectable = [&]() {
2879 if (node->getBasicType() == glslang::EbtVoid)
2880 return false;
2881 // OpSelect can do all other types starting with SPV 1.4
2882 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2883 // pre-1.4, only scalars and vectors can be handled
2884 if ((!node->getType().isScalar() && !node->getType().isVector()))
2885 return false;
2886 }
2887 return true;
2888 };
2889
John Kessenich4bee5312018-02-20 21:29:05 -07002890 // See if it simple and safe, or required, to execute both sides.
2891 // Crucially, side effects must be either semantically required or avoided,
2892 // and there are performance trade-offs.
2893 // Return true if required or a good idea (and safe) to execute both sides,
2894 // false otherwise.
2895 const auto bothSidesPolicy = [&]() -> bool {
2896 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002897 if (node->getTrueBlock() == nullptr ||
2898 node->getFalseBlock() == nullptr)
2899 return false;
2900
John Kessenich4bee5312018-02-20 21:29:05 -07002901 // required? (unless we write additional code to look for side effects
2902 // and make performance trade-offs if none are present)
2903 if (!node->getShortCircuit())
2904 return true;
2905
2906 // if not required to execute both, decide based on performance/practicality...
2907
John Kessenich0c1e71a2019-01-10 18:23:06 +07002908 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002909 return false;
2910
John Kessenich433e9ff2017-01-26 20:31:11 -07002911 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2912 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2913
2914 // return true if a single operand to ? : is okay for OpSelect
2915 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002916 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002917 };
2918
2919 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2920 operandOkay(node->getFalseBlock()->getAsTyped());
2921 };
2922
John Kessenich4bee5312018-02-20 21:29:05 -07002923 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2924 // emit the condition before doing anything with selection
2925 node->getCondition()->traverse(this);
2926 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2927
2928 // Find a way of executing both sides and selecting the right result.
2929 const auto executeBothSides = [&]() -> void {
2930 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002931 node->getTrueBlock()->traverse(this);
2932 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2933 node->getFalseBlock()->traverse(this);
2934 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2935
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002936 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002937
John Kessenich4bee5312018-02-20 21:29:05 -07002938 // done if void
2939 if (node->getBasicType() == glslang::EbtVoid)
2940 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002941
John Kessenich4bee5312018-02-20 21:29:05 -07002942 // emit code to select between trueValue and falseValue
2943
2944 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002945 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002946 // Emit OpSelect for this selection.
2947
2948 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002949 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2950 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002951 condition = builder.smearScalar(spv::NoPrecision, condition,
2952 builder.makeVectorType(builder.makeBoolType(),
2953 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002954 }
John Kessenich4bee5312018-02-20 21:29:05 -07002955
2956 // OpSelect
2957 result = builder.createTriOp(spv::OpSelect,
2958 convertGlslangToSpvType(node->getType()), condition,
2959 trueValue, falseValue);
2960
2961 builder.clearAccessChain();
2962 builder.setAccessChainRValue(result);
2963 } else {
2964 // We need control flow to select the result.
2965 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2966 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2967
2968 // Selection control:
2969 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2970
2971 // make an "if" based on the value created by the condition
2972 spv::Builder::If ifBuilder(condition, control, builder);
2973
2974 // emit the "then" statement
2975 builder.createStore(trueValue, result);
2976 ifBuilder.makeBeginElse();
2977 // emit the "else" statement
2978 builder.createStore(falseValue, result);
2979
2980 // finish off the control flow
2981 ifBuilder.makeEndIf();
2982
2983 builder.clearAccessChain();
2984 builder.setAccessChainLValue(result);
2985 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002986 };
2987
John Kessenich4bee5312018-02-20 21:29:05 -07002988 // Execute the one side needed, as per the condition
2989 const auto executeOneSide = [&]() {
2990 // Always emit control flow.
2991 if (node->getBasicType() != glslang::EbtVoid)
2992 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002993
John Kessenich4bee5312018-02-20 21:29:05 -07002994 // Selection control:
2995 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2996
2997 // make an "if" based on the value created by the condition
2998 spv::Builder::If ifBuilder(condition, control, builder);
2999
3000 // emit the "then" statement
3001 if (node->getTrueBlock() != nullptr) {
3002 node->getTrueBlock()->traverse(this);
3003 if (result != spv::NoResult)
3004 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3005 }
3006
3007 if (node->getFalseBlock() != nullptr) {
3008 ifBuilder.makeBeginElse();
3009 // emit the "else" statement
3010 node->getFalseBlock()->traverse(this);
3011 if (result != spv::NoResult)
3012 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3013 }
3014
3015 // finish off the control flow
3016 ifBuilder.makeEndIf();
3017
3018 if (result != spv::NoResult) {
3019 builder.clearAccessChain();
3020 builder.setAccessChainLValue(result);
3021 }
3022 };
3023
3024 // Try for OpSelect (or a requirement to execute both sides)
3025 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003026 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3027 if (node->getType().getQualifier().isSpecConstant())
3028 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003029 executeBothSides();
3030 } else
3031 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003032
3033 return false;
3034}
3035
3036bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3037{
3038 // emit and get the condition before doing anything with switch
3039 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003040 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003041
Rex Xu57e65922017-07-04 23:23:40 +08003042 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003043 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003044
John Kessenich140f3df2015-06-26 16:58:36 -06003045 // browse the children to sort out code segments
3046 int defaultSegment = -1;
3047 std::vector<TIntermNode*> codeSegments;
3048 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3049 std::vector<int> caseValues;
3050 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3051 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3052 TIntermNode* child = *c;
3053 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003054 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003055 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003056 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003057 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3058 } else
3059 codeSegments.push_back(child);
3060 }
3061
qining25262b32016-05-06 17:25:16 -04003062 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003063 // statements between the last case and the end of the switch statement
3064 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3065 (int)codeSegments.size() == defaultSegment)
3066 codeSegments.push_back(nullptr);
3067
3068 // make the switch statement
3069 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003070 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003071
3072 // emit all the code in the segments
3073 breakForLoop.push(false);
3074 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3075 builder.nextSwitchSegment(segmentBlocks, s);
3076 if (codeSegments[s])
3077 codeSegments[s]->traverse(this);
3078 else
3079 builder.addSwitchBreak();
3080 }
3081 breakForLoop.pop();
3082
3083 builder.endSwitch(segmentBlocks);
3084
3085 return false;
3086}
3087
3088void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3089{
3090 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003091 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003092
3093 builder.clearAccessChain();
3094 builder.setAccessChainRValue(constant);
3095}
3096
3097bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3098{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003099 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003100 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003101
3102 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003103 std::vector<unsigned int> operands;
3104 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003105
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003106 // Spec requires back edges to target header blocks, and every header block
3107 // must dominate its merge block. Make a header block first to ensure these
3108 // conditions are met. By definition, it will contain OpLoopMerge, followed
3109 // by a block-ending branch. But we don't want to put any other body/test
3110 // instructions in it, since the body/test may have arbitrary instructions,
3111 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003112 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003113 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003114 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003115 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003116 spv::Block& test = builder.makeNewBlock();
3117 builder.createBranch(&test);
3118
3119 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003120 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003121 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003122 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3123
3124 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003125 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003126 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003127 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003128 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003129 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003130
3131 builder.setBuildPoint(&blocks.continue_target);
3132 if (node->getTerminal())
3133 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003134 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003135 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003136 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003137 builder.createBranch(&blocks.body);
3138
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003139 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003140 builder.setBuildPoint(&blocks.body);
3141 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003142 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003143 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003144 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003145
3146 builder.setBuildPoint(&blocks.continue_target);
3147 if (node->getTerminal())
3148 node->getTerminal()->traverse(this);
3149 if (node->getTest()) {
3150 node->getTest()->traverse(this);
3151 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003152 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003153 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003154 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003155 // TODO: unless there was a break/return/discard instruction
3156 // somewhere in the body, this is an infinite loop, so we should
3157 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003158 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003159 }
John Kessenich140f3df2015-06-26 16:58:36 -06003160 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003161 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003162 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003163 return false;
3164}
3165
3166bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3167{
3168 if (node->getExpression())
3169 node->getExpression()->traverse(this);
3170
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003171 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003172
John Kessenich140f3df2015-06-26 16:58:36 -06003173 switch (node->getFlowOp()) {
3174 case glslang::EOpKill:
3175 builder.makeDiscard();
3176 break;
3177 case glslang::EOpBreak:
3178 if (breakForLoop.top())
3179 builder.createLoopExit();
3180 else
3181 builder.addSwitchBreak();
3182 break;
3183 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003184 builder.createLoopContinue();
3185 break;
3186 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003187 if (node->getExpression()) {
3188 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3189 spv::Id returnId = accessChainLoad(glslangReturnType);
3190 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3191 builder.clearAccessChain();
3192 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3193 builder.setAccessChainLValue(copyId);
3194 multiTypeStore(glslangReturnType, returnId);
3195 returnId = builder.createLoad(copyId);
3196 }
3197 builder.makeReturn(false, returnId);
3198 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003199 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003200
3201 builder.clearAccessChain();
3202 break;
3203
John Kessenichb9197c82019-08-11 07:41:45 -06003204#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003205 case glslang::EOpDemote:
3206 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3207 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3208 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3209 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003210#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003211
John Kessenich140f3df2015-06-26 16:58:36 -06003212 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003213 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003214 break;
3215 }
3216
3217 return false;
3218}
3219
John Kessenich9c14f772019-06-17 08:38:35 -06003220spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003221{
qining25262b32016-05-06 17:25:16 -04003222 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003223 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003224 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003225 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003226 spv::Id result = createSpvConstant(*node);
3227 if (result != spv::NoResult)
3228 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003229 }
3230
3231 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003232 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003233 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3234 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003235
John Kessenichb9197c82019-08-11 07:41:45 -06003236 const bool contains16BitType = node->getType().contains16BitFloat() ||
3237 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003238 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003239 switch (storageClass) {
3240 case spv::StorageClassInput:
3241 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003242 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003243 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003244 break;
John Kessenich18310872018-05-14 22:08:53 -06003245 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003246 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003247 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3248 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003249 else
3250 builder.addCapability(spv::CapabilityStorageUniform16);
3251 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003252#ifndef GLSLANG_WEB
3253 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003254 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003255 builder.addCapability(spv::CapabilityStoragePushConstant16);
3256 break;
John Kessenich18310872018-05-14 22:08:53 -06003257 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003258 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003259 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003260 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3261 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003262#endif
John Kessenich18310872018-05-14 22:08:53 -06003263 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003264 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003265 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003266 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003267 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003268 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003269 }
3270 }
Rex Xuf89ad982017-04-07 23:22:33 +08003271
John Kessenichb9197c82019-08-11 07:41:45 -06003272 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003273 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003274 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003275 builder.addCapability(spv::CapabilityStoragePushConstant8);
3276 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003277 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003278 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003279 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003280 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003281 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003282 } else {
3283 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003284 }
3285 }
3286
John Kessenich140f3df2015-06-26 16:58:36 -06003287 const char* name = node->getName().c_str();
3288 if (glslang::IsAnonymous(name))
3289 name = "";
3290
3291 return builder.createVariable(storageClass, spvType, name);
3292}
3293
3294// Return type Id of the sampled type.
3295spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3296{
3297 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003298 case glslang::EbtInt: return builder.makeIntType(32);
3299 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003300 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003301#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003302 case glslang::EbtFloat16:
3303 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3304 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3305 return builder.makeFloatType(16);
3306#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003307 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003308 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003309 return builder.makeFloatType(32);
3310 }
3311}
3312
John Kessenich8c8505c2016-07-26 12:50:38 -06003313// If node is a swizzle operation, return the type that should be used if
3314// the swizzle base is first consumed by another operation, before the swizzle
3315// is applied.
3316spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3317{
John Kessenichecba76f2017-01-06 00:34:48 -07003318 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003319 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3320 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3321 else
3322 return spv::NoType;
3323}
3324
3325// When inverting a swizzle with a parent op, this function
3326// will apply the swizzle operation to a completed parent operation.
3327spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3328{
3329 std::vector<unsigned> swizzle;
3330 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3331 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3332}
3333
John Kessenich8c8505c2016-07-26 12:50:38 -06003334// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3335void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3336{
3337 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3338 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3339 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3340}
3341
John Kessenich3ac051e2015-12-20 11:29:16 -07003342// Convert from a glslang type to an SPV type, by calling into a
3343// recursive version of this function. This establishes the inherited
3344// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003345spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003346{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003347 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003348}
3349
3350// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003351// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003352// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003353spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003354 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3355 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003356{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003357 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003358
3359 switch (type.getBasicType()) {
3360 case glslang::EbtVoid:
3361 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003362 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003364 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003365 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3366 // a 32-bit int where non-0 means true.
3367 if (explicitLayout != glslang::ElpNone)
3368 spvType = builder.makeUintType(32);
3369 else
3370 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003371 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003372 case glslang::EbtInt:
3373 spvType = builder.makeIntType(32);
3374 break;
3375 case glslang::EbtUint:
3376 spvType = builder.makeUintType(32);
3377 break;
3378 case glslang::EbtFloat:
3379 spvType = builder.makeFloatType(32);
3380 break;
3381#ifndef GLSLANG_WEB
3382 case glslang::EbtDouble:
3383 spvType = builder.makeFloatType(64);
3384 break;
3385 case glslang::EbtFloat16:
3386 spvType = builder.makeFloatType(16);
3387 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003388 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003389 spvType = builder.makeIntType(8);
3390 break;
3391 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003392 spvType = builder.makeUintType(8);
3393 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003394 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003395 spvType = builder.makeIntType(16);
3396 break;
3397 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003398 spvType = builder.makeUintType(16);
3399 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003400 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003401 spvType = builder.makeIntType(64);
3402 break;
3403 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003404 spvType = builder.makeUintType(64);
3405 break;
John Kessenich426394d2015-07-23 10:22:48 -06003406 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003407 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003408 spvType = builder.makeUintType(32);
3409 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003410 case glslang::EbtAccStructNV:
3411 spvType = builder.makeAccelerationStructureNVType();
3412 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003413 case glslang::EbtReference:
3414 {
3415 // Make the forward pointer, then recurse to convert the structure type, then
3416 // patch up the forward pointer with a real pointer type.
3417 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3418 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3419 forwardPointers[type.getReferentType()] = forwardId;
3420 }
3421 spvType = forwardPointers[type.getReferentType()];
3422 if (!forwardReferenceOnly) {
3423 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3424 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3425 forwardPointers[type.getReferentType()],
3426 referentType);
3427 }
3428 }
3429 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003430#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003431 case glslang::EbtSampler:
3432 {
3433 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003434 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003435 spvType = builder.makeSamplerType();
3436 } else {
3437 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003438 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3439 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3440 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3441 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003442 // already has both image and sampler, make the combined type
3443 spvType = builder.makeSampledImageType(spvType);
3444 }
John Kessenich55e7d112015-11-15 21:33:39 -07003445 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003446 }
John Kessenich140f3df2015-06-26 16:58:36 -06003447 break;
3448 case glslang::EbtStruct:
3449 case glslang::EbtBlock:
3450 {
3451 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003452 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003453
3454 // Try to share structs for different layouts, but not yet for other
3455 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003456 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003457 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003458 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003459 break;
3460
3461 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003462 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003463 memberRemapper[glslangMembers].resize(glslangMembers->size());
3464 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003465 }
3466 break;
3467 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003468 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003469 break;
3470 }
3471
3472 if (type.isMatrix())
3473 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3474 else {
3475 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3476 if (type.getVectorSize() > 1)
3477 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3478 }
3479
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003480 if (type.isCoopMat()) {
3481 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3482 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3483 if (type.getBasicType() == glslang::EbtFloat16)
3484 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003485 if (type.getBasicType() == glslang::EbtUint8 ||
3486 type.getBasicType() == glslang::EbtInt8) {
3487 builder.addCapability(spv::CapabilityInt8);
3488 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003489
3490 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3491 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3492 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3493
3494 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3495 }
3496
John Kessenich140f3df2015-06-26 16:58:36 -06003497 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003498 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3499
John Kessenichc9a80832015-09-12 12:17:44 -06003500 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003501 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003502 // We need to decorate array strides for types needing explicit layout, except blocks.
3503 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003504 // Use a dummy glslang type for querying internal strides of
3505 // arrays of arrays, but using just a one-dimensional array.
3506 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003507 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3508 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003509
3510 // Will compute the higher-order strides here, rather than making a whole
3511 // pile of types and doing repetitive recursion on their contents.
3512 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3513 }
John Kessenichf8842e52016-01-04 19:22:56 -07003514
3515 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003516 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003517 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003518 if (stride > 0)
3519 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003520 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003521 }
3522 } else {
3523 // single-dimensional array, and don't yet have stride
3524
John Kessenichf8842e52016-01-04 19:22:56 -07003525 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003526 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3527 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003528 }
John Kessenich31ed4832015-09-09 17:51:38 -06003529
John Kessenichead86222018-03-28 18:01:20 -06003530 // Do the outer dimension, which might not be known for a runtime-sized array.
3531 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3532 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003533 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003534 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003535#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003536 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003537 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003538 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3539 }
John Kessenichead86222018-03-28 18:01:20 -06003540 spvType = builder.makeRuntimeArray(spvType);
John Kessenichb9197c82019-08-11 07:41:45 -06003541#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06003542 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003543 if (stride > 0)
3544 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003545 }
3546
3547 return spvType;
3548}
3549
John Kessenich0e737842017-03-24 18:38:16 -06003550// TODO: this functionality should exist at a higher level, in creating the AST
3551//
3552// Identify interface members that don't have their required extension turned on.
3553//
3554bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3555{
John Kessenicha28f7a72019-08-06 07:00:58 -06003556#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003557 auto& extensions = glslangIntermediate->getRequestedExtensions();
3558
Rex Xubcf291a2017-03-29 23:01:36 +08003559 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3560 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3561 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003562 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3563 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3564 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003565
3566 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3567 if (member.getFieldName() == "gl_ViewportMask" &&
3568 extensions.find("GL_NV_viewport_array2") == extensions.end())
3569 return true;
3570 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3571 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3572 return true;
3573 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3574 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3575 return true;
3576 }
3577#endif
John Kessenich0e737842017-03-24 18:38:16 -06003578
3579 return false;
3580};
3581
John Kessenich6090df02016-06-30 21:18:02 -06003582// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3583// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3584// Mutually recursive with convertGlslangToSpvType().
3585spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3586 const glslang::TTypeList* glslangMembers,
3587 glslang::TLayoutPacking explicitLayout,
3588 const glslang::TQualifier& qualifier)
3589{
3590 // Create a vector of struct types for SPIR-V to consume
3591 std::vector<spv::Id> spvMembers;
3592 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 -06003593 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003594 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3595 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3596 if (glslangMember.hiddenMember()) {
3597 ++memberDelta;
3598 if (type.getBasicType() == glslang::EbtBlock)
3599 memberRemapper[glslangMembers][i] = -1;
3600 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003601 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003602 if (filterMember(glslangMember)) {
3603 memberDelta++;
3604 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003605 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003606 }
3607 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003608 }
John Kessenich6090df02016-06-30 21:18:02 -06003609 // modify just this child's view of the qualifier
3610 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3611 InheritQualifiers(memberQualifier, qualifier);
3612
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003613 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003614 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003615 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003616
3617 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003618 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3619 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003620
3621 // Make forward pointers for any pointer members, and create a list of members to
3622 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003623 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003624 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3625 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3626 }
3627 spvMembers.push_back(
3628 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3629 } else {
3630 spvMembers.push_back(
3631 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3632 }
John Kessenich6090df02016-06-30 21:18:02 -06003633 }
3634 }
3635
3636 // Make the SPIR-V type
3637 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003638 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003639 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3640
3641 // Decorate it
3642 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3643
John Kessenichd72f4882019-01-16 14:55:37 +07003644 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003645 auto it = deferredForwardPointers[i];
3646 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3647 }
3648
John Kessenich6090df02016-06-30 21:18:02 -06003649 return spvType;
3650}
3651
3652void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3653 const glslang::TTypeList* glslangMembers,
3654 glslang::TLayoutPacking explicitLayout,
3655 const glslang::TQualifier& qualifier,
3656 spv::Id spvType)
3657{
3658 // Name and decorate the non-hidden members
3659 int offset = -1;
3660 int locationOffset = 0; // for use within the members of this struct
3661 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3662 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3663 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003664 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003665 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003666 if (filterMember(glslangMember))
3667 continue;
3668 }
John Kessenich6090df02016-06-30 21:18:02 -06003669
3670 // modify just this child's view of the qualifier
3671 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3672 InheritQualifiers(memberQualifier, qualifier);
3673
3674 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003675 if (member < 0)
3676 continue;
3677
3678 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3679 builder.addMemberDecoration(spvType, member,
3680 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3681 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3682 // Add interpolation and auxiliary storage decorations only to
3683 // top-level members of Input and Output storage classes
3684 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3685 type.getQualifier().storage == glslang::EvqVaryingOut) {
3686 if (type.getBasicType() == glslang::EbtBlock ||
3687 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3688 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3689 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003690#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003691 addMeshNVDecoration(spvType, member, memberQualifier);
3692#endif
John Kessenich6090df02016-06-30 21:18:02 -06003693 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003694 }
3695 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003696
John Kessenichb9197c82019-08-11 07:41:45 -06003697#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003698 if (type.getBasicType() == glslang::EbtBlock &&
3699 qualifier.storage == glslang::EvqBuffer) {
3700 // Add memory decorations only to top-level members of shader storage block
3701 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003702 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003703 for (unsigned int i = 0; i < memory.size(); ++i)
3704 builder.addMemberDecoration(spvType, member, memory[i]);
3705 }
John Kessenichb9197c82019-08-11 07:41:45 -06003706#endif
John Kessenich6090df02016-06-30 21:18:02 -06003707
John Kessenich5d610ee2018-03-07 18:05:55 -07003708 // Location assignment was already completed correctly by the front end,
3709 // just track whether a member needs to be decorated.
3710 // Ignore member locations if the container is an array, as that's
3711 // ill-specified and decisions have been made to not allow this.
3712 if (! type.isArray() && memberQualifier.hasLocation())
3713 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003714
John Kessenich5d610ee2018-03-07 18:05:55 -07003715 if (qualifier.hasLocation()) // track for upcoming inheritance
3716 locationOffset += glslangIntermediate->computeTypeLocationSize(
3717 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003718
John Kessenich5d610ee2018-03-07 18:05:55 -07003719 // component, XFB, others
3720 if (glslangMember.getQualifier().hasComponent())
3721 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3722 glslangMember.getQualifier().layoutComponent);
3723 if (glslangMember.getQualifier().hasXfbOffset())
3724 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3725 glslangMember.getQualifier().layoutXfbOffset);
3726 else if (explicitLayout != glslang::ElpNone) {
3727 // figure out what to do with offset, which is accumulating
3728 int nextOffset;
3729 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3730 if (offset >= 0)
3731 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3732 offset = nextOffset;
3733 }
John Kessenich6090df02016-06-30 21:18:02 -06003734
John Kessenich5d610ee2018-03-07 18:05:55 -07003735 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3736 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3737 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003738
John Kessenich5d610ee2018-03-07 18:05:55 -07003739 // built-in variable decorations
3740 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3741 if (builtIn != spv::BuiltInMax)
3742 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003743
John Kessenichb9197c82019-08-11 07:41:45 -06003744#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003745 // nonuniform
3746 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3747
John Kessenichead86222018-03-28 18:01:20 -06003748 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3749 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3750 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3751 memberQualifier.semanticName);
3752 }
3753
John Kessenich5d610ee2018-03-07 18:05:55 -07003754 if (builtIn == spv::BuiltInLayer) {
3755 // SPV_NV_viewport_array2 extension
3756 if (glslangMember.getQualifier().layoutViewportRelative){
3757 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3758 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3759 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003760 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003761 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3762 builder.addMemberDecoration(spvType, member,
3763 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3764 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3765 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3766 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003767 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003768 }
3769 if (glslangMember.getQualifier().layoutPassthrough) {
3770 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3771 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3772 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3773 }
chaoc771d89f2017-01-13 01:10:53 -08003774#endif
John Kessenich6090df02016-06-30 21:18:02 -06003775 }
3776
3777 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003778 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3779 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003780}
3781
John Kessenich6c292d32016-02-15 20:58:50 -07003782// Turn the expression forming the array size into an id.
3783// This is not quite trivial, because of specialization constants.
3784// Sometimes, a raw constant is turned into an Id, and sometimes
3785// a specialization constant expression is.
3786spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3787{
3788 // First, see if this is sized with a node, meaning a specialization constant:
3789 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3790 if (specNode != nullptr) {
3791 builder.clearAccessChain();
3792 specNode->traverse(this);
3793 return accessChainLoad(specNode->getAsTyped()->getType());
3794 }
qining25262b32016-05-06 17:25:16 -04003795
John Kessenich6c292d32016-02-15 20:58:50 -07003796 // Otherwise, need a compile-time (front end) size, get it:
3797 int size = arraySizes.getDimSize(dim);
3798 assert(size > 0);
3799 return builder.makeUintConstant(size);
3800}
3801
John Kessenich103bef92016-02-08 21:38:15 -07003802// Wrap the builder's accessChainLoad to:
3803// - localize handling of RelaxedPrecision
3804// - use the SPIR-V inferred type instead of another conversion of the glslang type
3805// (avoids unnecessary work and possible type punning for structures)
3806// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003807spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3808{
John Kessenich103bef92016-02-08 21:38:15 -07003809 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003810
3811 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3812 coherentFlags |= TranslateCoherent(type);
3813
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003814 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003815 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003816
John Kessenich5611c6d2018-04-05 11:25:02 -06003817 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003818 TranslateNonUniformDecoration(type.getQualifier()),
3819 nominalTypeId,
3820 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003821 TranslateMemoryScope(coherentFlags),
3822 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003823
3824 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003825 if (type.getBasicType() == glslang::EbtBool) {
3826 if (builder.isScalarType(nominalTypeId)) {
3827 // Conversion for bool
3828 spv::Id boolType = builder.makeBoolType();
3829 if (nominalTypeId != boolType)
3830 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3831 } else if (builder.isVectorType(nominalTypeId)) {
3832 // Conversion for bvec
3833 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3834 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3835 if (nominalTypeId != bvecType)
3836 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3837 }
3838 }
John Kessenich103bef92016-02-08 21:38:15 -07003839
3840 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003841}
3842
Rex Xu27253232016-02-23 17:51:09 +08003843// Wrap the builder's accessChainStore to:
3844// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003845//
3846// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003847void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3848{
3849 // Need to convert to abstract types when necessary
3850 if (type.getBasicType() == glslang::EbtBool) {
3851 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3852
3853 if (builder.isScalarType(nominalTypeId)) {
3854 // Conversion for bool
3855 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003856 if (nominalTypeId != boolType) {
3857 // keep these outside arguments, for determinant order-of-evaluation
3858 spv::Id one = builder.makeUintConstant(1);
3859 spv::Id zero = builder.makeUintConstant(0);
3860 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3861 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003862 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003863 } else if (builder.isVectorType(nominalTypeId)) {
3864 // Conversion for bvec
3865 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3866 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003867 if (nominalTypeId != bvecType) {
3868 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003869 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3870 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3871 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003872 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003873 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3874 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003875 }
3876 }
3877
Jeff Bolz36831c92018-09-05 10:11:41 -05003878 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3879 coherentFlags |= TranslateCoherent(type);
3880
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003881 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003882 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003883
Jeff Bolz36831c92018-09-05 10:11:41 -05003884 builder.accessChainStore(rvalue,
3885 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003886 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003887}
3888
John Kessenich4bf71552016-09-02 11:20:21 -06003889// For storing when types match at the glslang level, but not might match at the
3890// SPIR-V level.
3891//
3892// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003893// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003894// as in a member-decorated way.
3895//
3896// NOTE: This function can handle any store request; if it's not special it
3897// simplifies to a simple OpStore.
3898//
3899// Implicitly uses the existing builder.accessChain as the storage target.
3900void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3901{
John Kessenichb3e24e42016-09-11 12:33:43 -06003902 // we only do the complex path here if it's an aggregate
3903 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003904 accessChainStore(type, rValue);
3905 return;
3906 }
3907
John Kessenichb3e24e42016-09-11 12:33:43 -06003908 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003909 spv::Id rType = builder.getTypeId(rValue);
3910 spv::Id lValue = builder.accessChainGetLValue();
3911 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3912 if (lType == rType) {
3913 accessChainStore(type, rValue);
3914 return;
3915 }
3916
John Kessenichb3e24e42016-09-11 12:33:43 -06003917 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003918 // where the two types were the same type in GLSL. This requires member
3919 // by member copy, recursively.
3920
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003921 // SPIR-V 1.4 added an instruction to do help do this.
3922 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3923 // However, bool in uniform space is changed to int, so
3924 // OpCopyLogical does not work for that.
3925 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3926 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3927 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3928 if (lBool == rBool) {
3929 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3930 accessChainStore(type, logicalCopy);
3931 return;
3932 }
3933 }
3934
John Kessenichb3e24e42016-09-11 12:33:43 -06003935 // If an array, copy element by element.
3936 if (type.isArray()) {
3937 glslang::TType glslangElementType(type, 0);
3938 spv::Id elementRType = builder.getContainedTypeId(rType);
3939 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3940 // get the source member
3941 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003942
John Kessenichb3e24e42016-09-11 12:33:43 -06003943 // set up the target storage
3944 builder.clearAccessChain();
3945 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003946 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003947
John Kessenichb3e24e42016-09-11 12:33:43 -06003948 // store the member
3949 multiTypeStore(glslangElementType, elementRValue);
3950 }
3951 } else {
3952 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003953
John Kessenichb3e24e42016-09-11 12:33:43 -06003954 // loop over structure members
3955 const glslang::TTypeList& members = *type.getStruct();
3956 for (int m = 0; m < (int)members.size(); ++m) {
3957 const glslang::TType& glslangMemberType = *members[m].type;
3958
3959 // get the source member
3960 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3961 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3962
3963 // set up the target storage
3964 builder.clearAccessChain();
3965 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003966 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003967
3968 // store the member
3969 multiTypeStore(glslangMemberType, memberRValue);
3970 }
John Kessenich4bf71552016-09-02 11:20:21 -06003971 }
3972}
3973
John Kessenichf85e8062015-12-19 13:57:10 -07003974// Decide whether or not this type should be
3975// decorated with offsets and strides, and if so
3976// whether std140 or std430 rules should be applied.
3977glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003978{
John Kessenichf85e8062015-12-19 13:57:10 -07003979 // has to be a block
3980 if (type.getBasicType() != glslang::EbtBlock)
3981 return glslang::ElpNone;
3982
Chao Chen3c366992018-09-19 11:41:59 -07003983 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003984 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003985 type.getQualifier().storage != glslang::EvqBuffer &&
3986 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003987 return glslang::ElpNone;
3988
3989 // return the layout to use
3990 switch (type.getQualifier().layoutPacking) {
3991 case glslang::ElpStd140:
3992 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003993 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003994 return type.getQualifier().layoutPacking;
3995 default:
3996 return glslang::ElpNone;
3997 }
John Kessenich31ed4832015-09-09 17:51:38 -06003998}
3999
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004000// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004001int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004002{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004003 int size;
John Kessenich49987892015-12-29 17:11:44 -07004004 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004005 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004006
4007 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004008}
4009
John Kessenich49987892015-12-29 17:11:44 -07004010// 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 -07004011// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004012int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004013{
John Kessenich49987892015-12-29 17:11:44 -07004014 glslang::TType elementType;
4015 elementType.shallowCopy(matrixType);
4016 elementType.clearArraySizes();
4017
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004018 int size;
John Kessenich49987892015-12-29 17:11:44 -07004019 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004020 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004021
4022 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004023}
4024
John Kessenich5e4b1242015-08-06 22:53:06 -06004025// Given a member type of a struct, realign the current offset for it, and compute
4026// the next (not yet aligned) offset for the next member, which will get aligned
4027// on the next call.
4028// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4029// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4030// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004031void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004032 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004033{
4034 // this will get a positive value when deemed necessary
4035 nextOffset = -1;
4036
John Kessenich5e4b1242015-08-06 22:53:06 -06004037 // override anything in currentOffset with user-set offset
4038 if (memberType.getQualifier().hasOffset())
4039 currentOffset = memberType.getQualifier().layoutOffset;
4040
4041 // It could be that current linker usage in glslang updated all the layoutOffset,
4042 // in which case the following code does not matter. But, that's not quite right
4043 // once cross-compilation unit GLSL validation is done, as the original user
4044 // settings are needed in layoutOffset, and then the following will come into play.
4045
John Kessenichf85e8062015-12-19 13:57:10 -07004046 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004047 if (! memberType.getQualifier().hasOffset())
4048 currentOffset = -1;
4049
4050 return;
4051 }
4052
John Kessenichf85e8062015-12-19 13:57:10 -07004053 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004054 if (currentOffset < 0)
4055 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004056
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4058 // but possibly not yet correctly aligned.
4059
4060 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004061 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004062 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004063
4064 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004065 // TODO: make this consistent in early phases of code:
4066 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4067 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4068 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004069 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004070 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004071 int dummySize;
4072 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4073 if (componentAlignment <= 4)
4074 memberAlignment = componentAlignment;
4075 }
4076
4077 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004079
4080 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004081 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004082 glslang::RoundToPow2(currentOffset, 16);
4083
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 nextOffset = currentOffset + memberSize;
4085}
4086
David Netoa901ffe2016-06-08 14:11:40 +01004087void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004088{
David Netoa901ffe2016-06-08 14:11:40 +01004089 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4090 switch (glslangBuiltIn)
4091 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004092 case glslang::EbvPointSize:
4093#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004094 case glslang::EbvClipDistance:
4095 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004096 case glslang::EbvViewportMaskNV:
4097 case glslang::EbvSecondaryPositionNV:
4098 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004099 case glslang::EbvPositionPerViewNV:
4100 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004101 case glslang::EbvTaskCountNV:
4102 case glslang::EbvPrimitiveCountNV:
4103 case glslang::EbvPrimitiveIndicesNV:
4104 case glslang::EbvClipDistancePerViewNV:
4105 case glslang::EbvCullDistancePerViewNV:
4106 case glslang::EbvLayerPerViewNV:
4107 case glslang::EbvMeshViewCountNV:
4108 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004109#endif
David Netoa901ffe2016-06-08 14:11:40 +01004110 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4111 // Alternately, we could just call this for any glslang built-in, since the
4112 // capability already guards against duplicates.
4113 TranslateBuiltInDecoration(glslangBuiltIn, false);
4114 break;
4115 default:
4116 // Capabilities were already generated when the struct was declared.
4117 break;
4118 }
John Kessenichebb50532016-05-16 19:22:05 -06004119}
4120
John Kessenich6fccb3c2016-09-19 16:01:41 -06004121bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004122{
John Kessenicheee9d532016-09-19 18:09:30 -06004123 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004124}
4125
John Kessenichd41993d2017-09-10 15:21:05 -06004126// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004127// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4128// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004129bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004130{
John Kessenich6a14f782017-12-04 02:48:10 -07004131 assert(qualifier == glslang::EvqIn ||
4132 qualifier == glslang::EvqOut ||
4133 qualifier == glslang::EvqInOut ||
4134 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004135 return qualifier != glslang::EvqConstReadOnly;
4136}
4137
4138// Is parameter pass-by-original?
4139bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4140 bool implicitThisParam)
4141{
4142 if (implicitThisParam) // implicit this
4143 return true;
4144 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004145 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004146 return paramType.containsOpaque() || // sampler, etc.
4147 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4148}
4149
John Kessenich140f3df2015-06-26 16:58:36 -06004150// Make all the functions, skeletally, without actually visiting their bodies.
4151void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4152{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004153 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004154 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4155 if (paramPrecision != spv::NoPrecision)
4156 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004157 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004158 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004159 // Original and non-writable params pass the pointer directly and
4160 // use restrict/aliased, others are stored to a pointer in Function
4161 // memory and use RestrictPointer/AliasedPointer.
4162 if (originalParam(type.getQualifier().storage, type, false) ||
4163 !writableParam(type.getQualifier().storage)) {
4164 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4165 } else {
4166 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4167 }
4168 }
John Kessenichfad62972017-07-18 02:35:46 -06004169 };
4170
John Kessenich140f3df2015-06-26 16:58:36 -06004171 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4172 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004173 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004174 continue;
4175
4176 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004177 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004178 //
qining25262b32016-05-06 17:25:16 -04004179 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004180 // function. What it is an address of varies:
4181 //
John Kessenich4bf71552016-09-02 11:20:21 -06004182 // - "in" parameters not marked as "const" can be written to without modifying the calling
4183 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004184 //
4185 // - "const in" parameters can just be the r-value, as no writes need occur.
4186 //
John Kessenich4bf71552016-09-02 11:20:21 -06004187 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4188 // 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 -06004189
4190 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004191 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004192 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4193
John Kessenich155d3512019-08-08 23:29:20 -06004194#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004195 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4196 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004197#else
4198 bool implicitThis = false;
4199#endif
John Kessenich37789792017-03-21 23:56:40 -06004200
John Kessenichfad62972017-07-18 02:35:46 -06004201 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004202 for (int p = 0; p < (int)parameters.size(); ++p) {
4203 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4204 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004205 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004206 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004207 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004208 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4209 else
John Kessenich4bf71552016-09-02 11:20:21 -06004210 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004211 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004212 paramTypes.push_back(typeId);
4213 }
4214
4215 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004216 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4217 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004218 glslFunction->getName().c_str(), paramTypes,
4219 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004220 if (implicitThis)
4221 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004222
4223 // Track function to emit/call later
4224 functionMap[glslFunction->getName().c_str()] = function;
4225
4226 // Set the parameter id's
4227 for (int p = 0; p < (int)parameters.size(); ++p) {
4228 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4229 // give a name too
4230 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004231
4232 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004233 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004234 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004235 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004236 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004237 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004238 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004239 }
4240 }
4241}
4242
4243// Process all the initializers, while skipping the functions and link objects
4244void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4245{
4246 builder.setBuildPoint(shaderEntry->getLastBlock());
4247 for (int i = 0; i < (int)initializers.size(); ++i) {
4248 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4249 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4250
4251 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004252 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004253 initializer->traverse(this);
4254 }
4255 }
4256}
4257
4258// Process all the functions, while skipping initializers.
4259void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4260{
4261 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4262 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004263 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004264 node->traverse(this);
4265 }
4266}
4267
4268void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4269{
qining25262b32016-05-06 17:25:16 -04004270 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004271 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004272 currentFunction = functionMap[node->getName().c_str()];
4273 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004274 builder.setBuildPoint(functionBlock);
4275}
4276
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004277void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004278{
Rex Xufc618912015-09-09 16:42:49 +08004279 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004280
4281 glslang::TSampler sampler = {};
4282 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004283#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004284 bool f16ShadowCompare = false;
4285#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004286 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004287 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4288 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004289#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004290 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4291#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004292 }
4293
John Kessenich140f3df2015-06-26 16:58:36 -06004294 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4295 builder.clearAccessChain();
4296 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004297
John Kessenicha28f7a72019-08-06 07:00:58 -06004298#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004299 // Special case l-value operands
4300 bool lvalue = false;
4301 switch (node.getOp()) {
4302 case glslang::EOpImageAtomicAdd:
4303 case glslang::EOpImageAtomicMin:
4304 case glslang::EOpImageAtomicMax:
4305 case glslang::EOpImageAtomicAnd:
4306 case glslang::EOpImageAtomicOr:
4307 case glslang::EOpImageAtomicXor:
4308 case glslang::EOpImageAtomicExchange:
4309 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004310 case glslang::EOpImageAtomicLoad:
4311 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004312 if (i == 0)
4313 lvalue = true;
4314 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004315 case glslang::EOpSparseImageLoad:
4316 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4317 lvalue = true;
4318 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004319 case glslang::EOpSparseTexture:
4320 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4321 lvalue = true;
4322 break;
4323 case glslang::EOpSparseTextureClamp:
4324 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4325 lvalue = true;
4326 break;
4327 case glslang::EOpSparseTextureLod:
4328 case glslang::EOpSparseTextureOffset:
4329 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4330 lvalue = true;
4331 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004332 case glslang::EOpSparseTextureFetch:
4333 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4334 lvalue = true;
4335 break;
4336 case glslang::EOpSparseTextureFetchOffset:
4337 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4338 lvalue = true;
4339 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004340 case glslang::EOpSparseTextureLodOffset:
4341 case glslang::EOpSparseTextureGrad:
4342 case glslang::EOpSparseTextureOffsetClamp:
4343 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4344 lvalue = true;
4345 break;
4346 case glslang::EOpSparseTextureGradOffset:
4347 case glslang::EOpSparseTextureGradClamp:
4348 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4349 lvalue = true;
4350 break;
4351 case glslang::EOpSparseTextureGradOffsetClamp:
4352 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4353 lvalue = true;
4354 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004355 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004356 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4357 lvalue = true;
4358 break;
4359 case glslang::EOpSparseTextureGatherOffset:
4360 case glslang::EOpSparseTextureGatherOffsets:
4361 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4362 lvalue = true;
4363 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004364 case glslang::EOpSparseTextureGatherLod:
4365 if (i == 3)
4366 lvalue = true;
4367 break;
4368 case glslang::EOpSparseTextureGatherLodOffset:
4369 case glslang::EOpSparseTextureGatherLodOffsets:
4370 if (i == 4)
4371 lvalue = true;
4372 break;
Rex Xu129799a2017-07-05 17:23:28 +08004373 case glslang::EOpSparseImageLoadLod:
4374 if (i == 3)
4375 lvalue = true;
4376 break;
Chao Chen3a137962018-09-19 11:41:27 -07004377 case glslang::EOpImageSampleFootprintNV:
4378 if (i == 4)
4379 lvalue = true;
4380 break;
4381 case glslang::EOpImageSampleFootprintClampNV:
4382 case glslang::EOpImageSampleFootprintLodNV:
4383 if (i == 5)
4384 lvalue = true;
4385 break;
4386 case glslang::EOpImageSampleFootprintGradNV:
4387 if (i == 6)
4388 lvalue = true;
4389 break;
4390 case glslang::EOpImageSampleFootprintGradClampNV:
4391 if (i == 7)
4392 lvalue = true;
4393 break;
Rex Xufc618912015-09-09 16:42:49 +08004394 default:
4395 break;
4396 }
4397
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004398 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004399 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004400 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4401 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4402 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004403#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004404 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004405 }
4406}
4407
John Kessenichfc51d282015-08-19 13:34:18 -06004408void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004409{
John Kessenichfc51d282015-08-19 13:34:18 -06004410 builder.clearAccessChain();
4411 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004412 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004413}
John Kessenich140f3df2015-06-26 16:58:36 -06004414
John Kessenichfc51d282015-08-19 13:34:18 -06004415spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4416{
John Kesseniche485c7a2017-05-31 18:50:53 -06004417 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004418 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004419
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004420 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004421
John Kessenichfc51d282015-08-19 13:34:18 -06004422 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004423
John Kessenichf43c7392019-03-31 10:51:57 -06004424 const glslang::TType &imageType = node->getAsAggregate()
4425 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4426 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004427 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004428#ifdef GLSLANG_WEB
4429 const bool f16ShadowCompare = false;
4430#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004431 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004432 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4433 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004434#endif
4435
John Kessenichf43c7392019-03-31 10:51:57 -06004436 const auto signExtensionMask = [&]() {
4437 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4438 if (sampler.type == glslang::EbtUint)
4439 return spv::ImageOperandsZeroExtendMask;
4440 else if (sampler.type == glslang::EbtInt)
4441 return spv::ImageOperandsSignExtendMask;
4442 }
4443 return spv::ImageOperandsMaskNone;
4444 };
4445
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004446 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4447
John Kessenichfc51d282015-08-19 13:34:18 -06004448 std::vector<spv::Id> arguments;
4449 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004450 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004451 else
4452 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004453 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004454
4455 spv::Builder::TextureParameters params = { };
4456 params.sampler = arguments[0];
4457
Rex Xu04db3f52015-09-16 11:44:02 +08004458 glslang::TCrackedTextureOp cracked;
4459 node->crackTexture(sampler, cracked);
4460
amhagan05506bb2017-06-13 16:53:02 -04004461 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004462
John Kessenichfc51d282015-08-19 13:34:18 -06004463 // Check for queries
4464 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004465 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4466 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004467 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004468
John Kessenichfc51d282015-08-19 13:34:18 -06004469 switch (node->getOp()) {
4470 case glslang::EOpImageQuerySize:
4471 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004472 if (arguments.size() > 1) {
4473 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004474 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004475 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004476 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004477#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004478 case glslang::EOpImageQuerySamples:
4479 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004480 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004481 case glslang::EOpTextureQueryLod:
4482 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004483 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004484 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004485 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004486 case glslang::EOpSparseTexelsResident:
4487 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004488#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004489 default:
4490 assert(0);
4491 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004492 }
John Kessenich140f3df2015-06-26 16:58:36 -06004493 }
4494
LoopDawg4425f242018-02-18 11:40:01 -07004495 int components = node->getType().getVectorSize();
4496
4497 if (node->getOp() == glslang::EOpTextureFetch) {
4498 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4499 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4500 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4501 // here around e.g. which ones return scalars or other types.
4502 components = 4;
4503 }
4504
4505 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4506
4507 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4508
Rex Xufc618912015-09-09 16:42:49 +08004509 // Check for image functions other than queries
4510 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004511 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004512 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004513 spv::IdImmediate image = { true, *(opIt++) };
4514 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004515
4516 // Handle subpass operations
4517 // TODO: GLSL should change to have the "MS" only on the type rather than the
4518 // built-in function.
4519 if (cracked.subpass) {
4520 // add on the (0,0) coordinate
4521 spv::Id zero = builder.makeIntConstant(0);
4522 std::vector<spv::Id> comps;
4523 comps.push_back(zero);
4524 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004525 spv::IdImmediate coord = { true,
4526 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4527 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004528 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4529 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004530 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004531 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4532 }
4533 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004534 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004535 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004536 spv::IdImmediate imageOperand = { true, *(opIt++) };
4537 operands.push_back(imageOperand);
4538 }
John Kessenich6c292d32016-02-15 20:58:50 -07004539 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004540 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4541 builder.setPrecision(result, precision);
4542 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004543 }
4544
John Kessenich149afc32018-08-14 13:31:43 -06004545 spv::IdImmediate coord = { true, *(opIt++) };
4546 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004547 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004548 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004549 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004550 mask = mask | spv::ImageOperandsSampleMask;
4551 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004552 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004553 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4554 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004555 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004556 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004557 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4558 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004559 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004560 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004561 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4562 operands.push_back(imageOperands);
4563 }
4564 if (mask & spv::ImageOperandsSampleMask) {
4565 spv::IdImmediate imageOperand = { true, *opIt++ };
4566 operands.push_back(imageOperand);
4567 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004568 if (mask & spv::ImageOperandsLodMask) {
4569 spv::IdImmediate imageOperand = { true, *opIt++ };
4570 operands.push_back(imageOperand);
4571 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004572 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004573 spv::IdImmediate imageOperand = { true,
4574 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004575 operands.push_back(imageOperand);
4576 }
4577
John Kessenich149afc32018-08-14 13:31:43 -06004578 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004579 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004580
John Kessenich149afc32018-08-14 13:31:43 -06004581 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004582 builder.setPrecision(result[0], precision);
4583
4584 // If needed, add a conversion constructor to the proper size.
4585 if (components != node->getType().getVectorSize())
4586 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4587
4588 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004589 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004590
Jeff Bolz36831c92018-09-05 10:11:41 -05004591 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004592 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004593 spv::IdImmediate texel = { true, *(opIt + 1) };
4594 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004595 } else {
4596 spv::IdImmediate texel = { true, *opIt };
4597 operands.push_back(texel);
4598 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004599
4600 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004601 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004602 mask = mask | spv::ImageOperandsSampleMask;
4603 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004604 if (cracked.lod) {
4605 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4606 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4607 mask = mask | spv::ImageOperandsLodMask;
4608 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4610 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004611 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004612 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004613 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4614 operands.push_back(imageOperands);
4615 }
4616 if (mask & spv::ImageOperandsSampleMask) {
4617 spv::IdImmediate imageOperand = { true, *opIt++ };
4618 operands.push_back(imageOperand);
4619 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004620 if (mask & spv::ImageOperandsLodMask) {
4621 spv::IdImmediate imageOperand = { true, *opIt++ };
4622 operands.push_back(imageOperand);
4623 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004624 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004625 spv::IdImmediate imageOperand = { true,
4626 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004627 operands.push_back(imageOperand);
4628 }
4629
John Kessenich56bab042015-09-16 10:54:31 -06004630 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004631 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004632 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004633 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004634 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4635 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004636 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004637 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004638 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4639
Jeff Bolz36831c92018-09-05 10:11:41 -05004640 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004641 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004642 mask = mask | spv::ImageOperandsSampleMask;
4643 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004644 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004645 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4646 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4647
Jeff Bolz36831c92018-09-05 10:11:41 -05004648 mask = mask | spv::ImageOperandsLodMask;
4649 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004650 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4651 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004652 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004653 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004654 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004655 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004656 }
4657 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004658 spv::IdImmediate imageOperand = { true, *opIt++ };
4659 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004660 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004661 if (mask & spv::ImageOperandsLodMask) {
4662 spv::IdImmediate imageOperand = { true, *opIt++ };
4663 operands.push_back(imageOperand);
4664 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004665 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4666 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4667 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004668 }
4669
4670 // Create the return type that was a special structure
4671 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004672 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004673 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4674 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4675
4676 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4677
4678 // Decode the return type
4679 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4680 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004681 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004682 // Process image atomic operations
4683
4684 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4685 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004686 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004687 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004688 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004689
Jeff Bolz36831c92018-09-05 10:11:41 -05004690 spv::Id resultTypeId;
4691 // imageAtomicStore has a void return type so base the pointer type on
4692 // the type of the value operand.
4693 if (node->getOp() == glslang::EOpImageAtomicStore) {
4694 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4695 } else {
4696 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4697 }
John Kessenich56bab042015-09-16 10:54:31 -06004698 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004699
4700 std::vector<spv::Id> operands;
4701 operands.push_back(pointer);
4702 for (; opIt != arguments.end(); ++opIt)
4703 operands.push_back(*opIt);
4704
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004705 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004706 }
4707 }
4708
John Kessenicha28f7a72019-08-06 07:00:58 -06004709#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004710 // Check for fragment mask functions other than queries
4711 if (cracked.fragMask) {
4712 assert(sampler.ms);
4713
4714 auto opIt = arguments.begin();
4715 std::vector<spv::Id> operands;
4716
4717 // Extract the image if necessary
4718 if (builder.isSampledImage(params.sampler))
4719 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4720
4721 operands.push_back(params.sampler);
4722 ++opIt;
4723
4724 if (sampler.isSubpass()) {
4725 // add on the (0,0) coordinate
4726 spv::Id zero = builder.makeIntConstant(0);
4727 std::vector<spv::Id> comps;
4728 comps.push_back(zero);
4729 comps.push_back(zero);
4730 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4731 }
4732
4733 for (; opIt != arguments.end(); ++opIt)
4734 operands.push_back(*opIt);
4735
4736 spv::Op fragMaskOp = spv::OpNop;
4737 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4738 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4739 else if (node->getOp() == glslang::EOpFragmentFetch)
4740 fragMaskOp = spv::OpFragmentFetchAMD;
4741
4742 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4743 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4744 return builder.createOp(fragMaskOp, resultType(), operands);
4745 }
4746#endif
4747
Rex Xufc618912015-09-09 16:42:49 +08004748 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004749 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004750 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004751 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004752
John Kessenichfc51d282015-08-19 13:34:18 -06004753 // check for bias argument
4754 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004755 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004756 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004757 if (cracked.gather)
4758 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004759
4760 if (f16ShadowCompare)
4761 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004762 if (cracked.offset)
4763 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004764 else if (cracked.offsets)
4765 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004766 if (cracked.grad)
4767 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004768 if (cracked.lodClamp)
4769 ++nonBiasArgCount;
4770 if (sparse)
4771 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004772 if (imageFootprint)
4773 //Following three extra arguments
4774 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4775 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004776 if ((int)arguments.size() > nonBiasArgCount)
4777 bias = true;
4778 }
4779
John Kessenicha5c33d62016-06-02 23:45:21 -06004780 // See if the sampler param should really be just the SPV image part
4781 if (cracked.fetch) {
4782 // a fetch needs to have the image extracted first
4783 if (builder.isSampledImage(params.sampler))
4784 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4785 }
4786
John Kessenicha28f7a72019-08-06 07:00:58 -06004787#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004788 if (cracked.gather) {
4789 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4790 if (bias || cracked.lod ||
4791 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4792 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004793 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004794 }
4795 }
4796#endif
4797
John Kessenichfc51d282015-08-19 13:34:18 -06004798 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004799
John Kessenichfc51d282015-08-19 13:34:18 -06004800 params.coords = arguments[1];
4801 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004802 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004803
4804 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004805 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004806 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004807 ++extraArgs;
4808 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004809 params.Dref = arguments[2];
4810 ++extraArgs;
4811 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004812 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004813 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004814 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004815 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004816 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004817 dRefComp = builder.getNumComponents(params.coords) - 1;
4818 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004819 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4820 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004821
4822 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004823 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004824 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004825 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004826 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4827 !(glslangIntermediate->getStage() == EShLangCompute &&
4828 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004829 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4830 noImplicitLod = true;
4831 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004832
4833 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004834 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004835 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004836 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004837 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004838
4839 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004840 if (cracked.grad) {
4841 params.gradX = arguments[2 + extraArgs];
4842 params.gradY = arguments[3 + extraArgs];
4843 extraArgs += 2;
4844 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004845
4846 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004847 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004848 params.offset = arguments[2 + extraArgs];
4849 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004850 } else if (cracked.offsets) {
4851 params.offsets = arguments[2 + extraArgs];
4852 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004853 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004854
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004855#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004856 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004857 if (cracked.lodClamp) {
4858 params.lodClamp = arguments[2 + extraArgs];
4859 ++extraArgs;
4860 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004861 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004862 if (sparse) {
4863 params.texelOut = arguments[2 + extraArgs];
4864 ++extraArgs;
4865 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004866 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004867 if (cracked.gather && ! sampler.shadow) {
4868 // default component is 0, if missing, otherwise an argument
4869 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004870 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004871 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004872 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004873 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004874 }
Chao Chen3a137962018-09-19 11:41:27 -07004875 spv::Id resultStruct = spv::NoResult;
4876 if (imageFootprint) {
4877 //Following three extra arguments
4878 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4879 params.granularity = arguments[2 + extraArgs];
4880 params.coarse = arguments[3 + extraArgs];
4881 resultStruct = arguments[4 + extraArgs];
4882 extraArgs += 3;
4883 }
4884#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004885 // bias
4886 if (bias) {
4887 params.bias = arguments[2 + extraArgs];
4888 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004889 }
John Kessenichfc51d282015-08-19 13:34:18 -06004890
John Kessenicha28f7a72019-08-06 07:00:58 -06004891#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004892 if (imageFootprint) {
4893 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4894 builder.addCapability(spv::CapabilityImageFootprintNV);
4895
4896
4897 //resultStructType(OpenGL type) contains 5 elements:
4898 //struct gl_TextureFootprint2DNV {
4899 // uvec2 anchor;
4900 // uvec2 offset;
4901 // uvec2 mask;
4902 // uint lod;
4903 // uint granularity;
4904 //};
4905 //or
4906 //struct gl_TextureFootprint3DNV {
4907 // uvec3 anchor;
4908 // uvec3 offset;
4909 // uvec2 mask;
4910 // uint lod;
4911 // uint granularity;
4912 //};
4913 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4914 assert(builder.isStructType(resultStructType));
4915
4916 //resType (SPIR-V type) contains 6 elements:
4917 //Member 0 must be a Boolean type scalar(LOD),
4918 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4919 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4920 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4921 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4922 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4923 std::vector<spv::Id> members;
4924 members.push_back(resultType());
4925 for (int i = 0; i < 5; i++) {
4926 members.push_back(builder.getContainedTypeId(resultStructType, i));
4927 }
4928 spv::Id resType = builder.makeStructType(members, "ResType");
4929
4930 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004931 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4932 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004933
4934 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4935 for (int i = 0; i < 5; i++) {
4936 builder.clearAccessChain();
4937 builder.setAccessChainLValue(resultStruct);
4938
4939 //Accessing to a struct we created, no coherent flag is set
4940 spv::Builder::AccessChain::CoherentFlags flags;
4941 flags.clear();
4942
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004943 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004944 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4945 }
4946 return builder.createCompositeExtract(res, resultType(), 0);
4947 }
4948#endif
4949
John Kessenich65336482016-06-16 14:06:26 -06004950 // projective component (might not to move)
4951 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4952 // are divided by the last component of P."
4953 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4954 // unused components will appear after all used components."
4955 if (cracked.proj) {
4956 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4957 int projTargetComp;
4958 switch (sampler.dim) {
4959 case glslang::Esd1D: projTargetComp = 1; break;
4960 case glslang::Esd2D: projTargetComp = 2; break;
4961 case glslang::EsdRect: projTargetComp = 2; break;
4962 default: projTargetComp = projSourceComp; break;
4963 }
4964 // copy the projective coordinate if we have to
4965 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004966 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004967 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4968 projSourceComp);
4969 params.coords = builder.createCompositeInsert(projComp, params.coords,
4970 builder.getTypeId(params.coords), projTargetComp);
4971 }
4972 }
4973
Jeff Bolz36831c92018-09-05 10:11:41 -05004974 // nonprivate
4975 if (imageType.getQualifier().nonprivate) {
4976 params.nonprivate = true;
4977 }
4978
4979 // volatile
4980 if (imageType.getQualifier().volatil) {
4981 params.volatil = true;
4982 }
4983
St0fFa1184dd2018-04-09 21:08:14 +02004984 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004985 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4986 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004987 );
LoopDawg4425f242018-02-18 11:40:01 -07004988
4989 if (components != node->getType().getVectorSize())
4990 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4991
4992 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004993}
4994
4995spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4996{
4997 // Grab the function's pointer from the previously created function
4998 spv::Function* function = functionMap[node->getName().c_str()];
4999 if (! function)
5000 return 0;
5001
5002 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5003 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5004
5005 // See comments in makeFunctions() for details about the semantics for parameter passing.
5006 //
5007 // These imply we need a four step process:
5008 // 1. Evaluate the arguments
5009 // 2. Allocate and make copies of in, out, and inout arguments
5010 // 3. Make the call
5011 // 4. Copy back the results
5012
John Kessenichd3ed90b2018-05-04 11:43:03 -06005013 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005014 std::vector<spv::Builder::AccessChain> lValues;
5015 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005016 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005017 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005018 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005019 // build l-value
5020 builder.clearAccessChain();
5021 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005022 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005023 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005024 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005025 // save l-value
5026 lValues.push_back(builder.getAccessChain());
5027 } else {
5028 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005029 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005030 }
5031 }
5032
5033 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5034 // copy the original into that space.
5035 //
5036 // Also, build up the list of actual arguments to pass in for the call
5037 int lValueCount = 0;
5038 int rValueCount = 0;
5039 std::vector<spv::Id> spvArgs;
5040 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5041 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005042 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005043 builder.setAccessChain(lValues[lValueCount]);
5044 arg = builder.accessChainGetLValue();
5045 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005046 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005047 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005048 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005049 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5050 // need to copy the input into output space
5051 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005052 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005053 builder.clearAccessChain();
5054 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005055 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005056 }
5057 ++lValueCount;
5058 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005059 // process r-value, which involves a copy for a type mismatch
5060 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5061 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5062 builder.clearAccessChain();
5063 builder.setAccessChainLValue(argCopy);
5064 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5065 arg = builder.createLoad(argCopy);
5066 } else
5067 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005068 ++rValueCount;
5069 }
5070 spvArgs.push_back(arg);
5071 }
5072
5073 // 3. Make the call.
5074 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005075 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005076
5077 // 4. Copy back out an "out" arguments.
5078 lValueCount = 0;
5079 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005080 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005081 ++lValueCount;
5082 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005083 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5084 spv::Id copy = builder.createLoad(spvArgs[a]);
5085 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005086 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005087 }
5088 ++lValueCount;
5089 }
5090 }
5091
5092 return result;
5093}
5094
5095// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005096spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005097 spv::Id typeId, spv::Id left, spv::Id right,
5098 glslang::TBasicType typeProxy, bool reduceComparison)
5099{
John Kessenich66011cb2018-03-06 16:12:04 -07005100 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5101 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005102 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005103
5104 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005105 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005106 bool comparison = false;
5107
5108 switch (op) {
5109 case glslang::EOpAdd:
5110 case glslang::EOpAddAssign:
5111 if (isFloat)
5112 binOp = spv::OpFAdd;
5113 else
5114 binOp = spv::OpIAdd;
5115 break;
5116 case glslang::EOpSub:
5117 case glslang::EOpSubAssign:
5118 if (isFloat)
5119 binOp = spv::OpFSub;
5120 else
5121 binOp = spv::OpISub;
5122 break;
5123 case glslang::EOpMul:
5124 case glslang::EOpMulAssign:
5125 if (isFloat)
5126 binOp = spv::OpFMul;
5127 else
5128 binOp = spv::OpIMul;
5129 break;
5130 case glslang::EOpVectorTimesScalar:
5131 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005132 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005133 if (builder.isVector(right))
5134 std::swap(left, right);
5135 assert(builder.isScalar(right));
5136 needMatchingVectors = false;
5137 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005138 } else if (isFloat)
5139 binOp = spv::OpFMul;
5140 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005141 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005142 break;
5143 case glslang::EOpVectorTimesMatrix:
5144 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005145 binOp = spv::OpVectorTimesMatrix;
5146 break;
5147 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005148 binOp = spv::OpMatrixTimesVector;
5149 break;
5150 case glslang::EOpMatrixTimesScalar:
5151 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005152 binOp = spv::OpMatrixTimesScalar;
5153 break;
5154 case glslang::EOpMatrixTimesMatrix:
5155 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005156 binOp = spv::OpMatrixTimesMatrix;
5157 break;
5158 case glslang::EOpOuterProduct:
5159 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005160 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005161 break;
5162
5163 case glslang::EOpDiv:
5164 case glslang::EOpDivAssign:
5165 if (isFloat)
5166 binOp = spv::OpFDiv;
5167 else if (isUnsigned)
5168 binOp = spv::OpUDiv;
5169 else
5170 binOp = spv::OpSDiv;
5171 break;
5172 case glslang::EOpMod:
5173 case glslang::EOpModAssign:
5174 if (isFloat)
5175 binOp = spv::OpFMod;
5176 else if (isUnsigned)
5177 binOp = spv::OpUMod;
5178 else
5179 binOp = spv::OpSMod;
5180 break;
5181 case glslang::EOpRightShift:
5182 case glslang::EOpRightShiftAssign:
5183 if (isUnsigned)
5184 binOp = spv::OpShiftRightLogical;
5185 else
5186 binOp = spv::OpShiftRightArithmetic;
5187 break;
5188 case glslang::EOpLeftShift:
5189 case glslang::EOpLeftShiftAssign:
5190 binOp = spv::OpShiftLeftLogical;
5191 break;
5192 case glslang::EOpAnd:
5193 case glslang::EOpAndAssign:
5194 binOp = spv::OpBitwiseAnd;
5195 break;
5196 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005197 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005198 binOp = spv::OpLogicalAnd;
5199 break;
5200 case glslang::EOpInclusiveOr:
5201 case glslang::EOpInclusiveOrAssign:
5202 binOp = spv::OpBitwiseOr;
5203 break;
5204 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005205 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005206 binOp = spv::OpLogicalOr;
5207 break;
5208 case glslang::EOpExclusiveOr:
5209 case glslang::EOpExclusiveOrAssign:
5210 binOp = spv::OpBitwiseXor;
5211 break;
5212 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005213 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005214 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005215 break;
5216
5217 case glslang::EOpLessThan:
5218 case glslang::EOpGreaterThan:
5219 case glslang::EOpLessThanEqual:
5220 case glslang::EOpGreaterThanEqual:
5221 case glslang::EOpEqual:
5222 case glslang::EOpNotEqual:
5223 case glslang::EOpVectorEqual:
5224 case glslang::EOpVectorNotEqual:
5225 comparison = true;
5226 break;
5227 default:
5228 break;
5229 }
5230
John Kessenich7c1aa102015-10-15 13:29:11 -06005231 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005232 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005233 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005234 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5235 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005236 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005237
5238 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005239 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005240 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005241
qining25262b32016-05-06 17:25:16 -04005242 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005243 decorations.addNoContraction(builder, result);
5244 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005245 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005246 }
5247
5248 if (! comparison)
5249 return 0;
5250
John Kessenich7c1aa102015-10-15 13:29:11 -06005251 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005252
John Kessenich4583b612016-08-07 19:14:22 -06005253 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005254 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5255 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005256 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005257 return result;
5258 }
John Kessenich140f3df2015-06-26 16:58:36 -06005259
5260 switch (op) {
5261 case glslang::EOpLessThan:
5262 if (isFloat)
5263 binOp = spv::OpFOrdLessThan;
5264 else if (isUnsigned)
5265 binOp = spv::OpULessThan;
5266 else
5267 binOp = spv::OpSLessThan;
5268 break;
5269 case glslang::EOpGreaterThan:
5270 if (isFloat)
5271 binOp = spv::OpFOrdGreaterThan;
5272 else if (isUnsigned)
5273 binOp = spv::OpUGreaterThan;
5274 else
5275 binOp = spv::OpSGreaterThan;
5276 break;
5277 case glslang::EOpLessThanEqual:
5278 if (isFloat)
5279 binOp = spv::OpFOrdLessThanEqual;
5280 else if (isUnsigned)
5281 binOp = spv::OpULessThanEqual;
5282 else
5283 binOp = spv::OpSLessThanEqual;
5284 break;
5285 case glslang::EOpGreaterThanEqual:
5286 if (isFloat)
5287 binOp = spv::OpFOrdGreaterThanEqual;
5288 else if (isUnsigned)
5289 binOp = spv::OpUGreaterThanEqual;
5290 else
5291 binOp = spv::OpSGreaterThanEqual;
5292 break;
5293 case glslang::EOpEqual:
5294 case glslang::EOpVectorEqual:
5295 if (isFloat)
5296 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005297 else if (isBool)
5298 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005299 else
5300 binOp = spv::OpIEqual;
5301 break;
5302 case glslang::EOpNotEqual:
5303 case glslang::EOpVectorNotEqual:
5304 if (isFloat)
5305 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005306 else if (isBool)
5307 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005308 else
5309 binOp = spv::OpINotEqual;
5310 break;
5311 default:
5312 break;
5313 }
5314
qining25262b32016-05-06 17:25:16 -04005315 if (binOp != spv::OpNop) {
5316 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005317 decorations.addNoContraction(builder, result);
5318 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005319 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005320 }
John Kessenich140f3df2015-06-26 16:58:36 -06005321
5322 return 0;
5323}
5324
John Kessenich04bb8a02015-12-12 12:28:14 -07005325//
5326// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5327// These can be any of:
5328//
5329// matrix * scalar
5330// scalar * matrix
5331// matrix * matrix linear algebraic
5332// matrix * vector
5333// vector * matrix
5334// matrix * matrix componentwise
5335// matrix op matrix op in {+, -, /}
5336// matrix op scalar op in {+, -, /}
5337// scalar op matrix op in {+, -, /}
5338//
John Kessenichead86222018-03-28 18:01:20 -06005339spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5340 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005341{
5342 bool firstClass = true;
5343
5344 // First, handle first-class matrix operations (* and matrix/scalar)
5345 switch (op) {
5346 case spv::OpFDiv:
5347 if (builder.isMatrix(left) && builder.isScalar(right)) {
5348 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005349 spv::Id resultType = builder.getTypeId(right);
5350 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005351 op = spv::OpMatrixTimesScalar;
5352 } else
5353 firstClass = false;
5354 break;
5355 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005356 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005357 std::swap(left, right);
5358 assert(builder.isScalar(right));
5359 break;
5360 case spv::OpVectorTimesMatrix:
5361 assert(builder.isVector(left));
5362 assert(builder.isMatrix(right));
5363 break;
5364 case spv::OpMatrixTimesVector:
5365 assert(builder.isMatrix(left));
5366 assert(builder.isVector(right));
5367 break;
5368 case spv::OpMatrixTimesMatrix:
5369 assert(builder.isMatrix(left));
5370 assert(builder.isMatrix(right));
5371 break;
5372 default:
5373 firstClass = false;
5374 break;
5375 }
5376
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005377 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5378 firstClass = true;
5379
qining25262b32016-05-06 17:25:16 -04005380 if (firstClass) {
5381 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005382 decorations.addNoContraction(builder, result);
5383 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005384 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005385 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005386
LoopDawg592860c2016-06-09 08:57:35 -06005387 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005388 // The result type of all of them is the same type as the (a) matrix operand.
5389 // The algorithm is to:
5390 // - break the matrix(es) into vectors
5391 // - smear any scalar to a vector
5392 // - do vector operations
5393 // - make a matrix out the vector results
5394 switch (op) {
5395 case spv::OpFAdd:
5396 case spv::OpFSub:
5397 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005398 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005399 case spv::OpFMul:
5400 {
5401 // one time set up...
5402 bool leftMat = builder.isMatrix(left);
5403 bool rightMat = builder.isMatrix(right);
5404 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5405 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5406 spv::Id scalarType = builder.getScalarTypeId(typeId);
5407 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5408 std::vector<spv::Id> results;
5409 spv::Id smearVec = spv::NoResult;
5410 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005411 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005412 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005413 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005414
5415 // do each vector op
5416 for (unsigned int c = 0; c < numCols; ++c) {
5417 std::vector<unsigned int> indexes;
5418 indexes.push_back(c);
5419 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5420 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005421 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005422 decorations.addNoContraction(builder, result);
5423 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005424 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005425 }
5426
5427 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005428 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005429 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005430 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005431 }
5432 default:
5433 assert(0);
5434 return spv::NoResult;
5435 }
5436}
5437
John Kessenichead86222018-03-28 18:01:20 -06005438spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005439 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005440{
5441 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005442 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005444 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5445 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005446
5447 switch (op) {
5448 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005449 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005450 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005451 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005452 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005453 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005454 unaryOp = spv::OpSNegate;
5455 break;
5456
5457 case glslang::EOpLogicalNot:
5458 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005459 unaryOp = spv::OpLogicalNot;
5460 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005461 case glslang::EOpBitwiseNot:
5462 unaryOp = spv::OpNot;
5463 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005464
John Kessenich140f3df2015-06-26 16:58:36 -06005465 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005466 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005467 break;
5468 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005469 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005470 break;
5471 case glslang::EOpTranspose:
5472 unaryOp = spv::OpTranspose;
5473 break;
5474
5475 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 break;
5478 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005479 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005482 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005483 break;
5484 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005488 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 break;
5490 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005491 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005492 break;
5493 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005494 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 break;
5496 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005497 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005498 break;
5499
5500 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005501 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005502 break;
5503 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
5506 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005507 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005508 break;
5509 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005510 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005511 break;
5512 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005513 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005514 break;
5515 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005516 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005517 break;
5518
5519 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005520 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005521 break;
5522 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005523 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 break;
5525
5526 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005527 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005528 break;
5529 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005530 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005531 break;
5532 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005533 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005534 break;
5535 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005536 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005537 break;
5538 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005539 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005540 break;
5541 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005542 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005543 break;
5544
5545 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005546 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005547 break;
5548 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005549 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005550 break;
5551 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005552 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005553 break;
5554 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005555 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005556 break;
5557 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005558 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005559 break;
5560 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005561 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005562 break;
5563
5564 case glslang::EOpIsNan:
5565 unaryOp = spv::OpIsNan;
5566 break;
5567 case glslang::EOpIsInf:
5568 unaryOp = spv::OpIsInf;
5569 break;
LoopDawg592860c2016-06-09 08:57:35 -06005570 case glslang::EOpIsFinite:
5571 unaryOp = spv::OpIsFinite;
5572 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005573
Rex Xucbc426e2015-12-15 16:03:10 +08005574 case glslang::EOpFloatBitsToInt:
5575 case glslang::EOpFloatBitsToUint:
5576 case glslang::EOpIntBitsToFloat:
5577 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005578 case glslang::EOpDoubleBitsToInt64:
5579 case glslang::EOpDoubleBitsToUint64:
5580 case glslang::EOpInt64BitsToDouble:
5581 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005582 case glslang::EOpFloat16BitsToInt16:
5583 case glslang::EOpFloat16BitsToUint16:
5584 case glslang::EOpInt16BitsToFloat16:
5585 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005586 unaryOp = spv::OpBitcast;
5587 break;
5588
John Kessenich140f3df2015-06-26 16:58:36 -06005589 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005590 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005591 break;
5592 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005593 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005594 break;
5595 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005596 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005597 break;
5598 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005599 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005600 break;
5601 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005602 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005603 break;
5604 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005605 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005606 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005607#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005608 case glslang::EOpPackSnorm4x8:
5609 libCall = spv::GLSLstd450PackSnorm4x8;
5610 break;
5611 case glslang::EOpUnpackSnorm4x8:
5612 libCall = spv::GLSLstd450UnpackSnorm4x8;
5613 break;
5614 case glslang::EOpPackUnorm4x8:
5615 libCall = spv::GLSLstd450PackUnorm4x8;
5616 break;
5617 case glslang::EOpUnpackUnorm4x8:
5618 libCall = spv::GLSLstd450UnpackUnorm4x8;
5619 break;
5620 case glslang::EOpPackDouble2x32:
5621 libCall = spv::GLSLstd450PackDouble2x32;
5622 break;
5623 case glslang::EOpUnpackDouble2x32:
5624 libCall = spv::GLSLstd450UnpackDouble2x32;
5625 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005626#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005627
Rex Xu8ff43de2016-04-22 16:51:45 +08005628 case glslang::EOpPackInt2x32:
5629 case glslang::EOpUnpackInt2x32:
5630 case glslang::EOpPackUint2x32:
5631 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005632 case glslang::EOpPack16:
5633 case glslang::EOpPack32:
5634 case glslang::EOpPack64:
5635 case glslang::EOpUnpack32:
5636 case glslang::EOpUnpack16:
5637 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005638 case glslang::EOpPackInt2x16:
5639 case glslang::EOpUnpackInt2x16:
5640 case glslang::EOpPackUint2x16:
5641 case glslang::EOpUnpackUint2x16:
5642 case glslang::EOpPackInt4x16:
5643 case glslang::EOpUnpackInt4x16:
5644 case glslang::EOpPackUint4x16:
5645 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005646 case glslang::EOpPackFloat2x16:
5647 case glslang::EOpUnpackFloat2x16:
5648 unaryOp = spv::OpBitcast;
5649 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005650
John Kessenich140f3df2015-06-26 16:58:36 -06005651 case glslang::EOpDPdx:
5652 unaryOp = spv::OpDPdx;
5653 break;
5654 case glslang::EOpDPdy:
5655 unaryOp = spv::OpDPdy;
5656 break;
5657 case glslang::EOpFwidth:
5658 unaryOp = spv::OpFwidth;
5659 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005660
John Kessenich140f3df2015-06-26 16:58:36 -06005661 case glslang::EOpAny:
5662 unaryOp = spv::OpAny;
5663 break;
5664 case glslang::EOpAll:
5665 unaryOp = spv::OpAll;
5666 break;
5667
5668 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005669 if (isFloat)
5670 libCall = spv::GLSLstd450FAbs;
5671 else
5672 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005673 break;
5674 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005675 if (isFloat)
5676 libCall = spv::GLSLstd450FSign;
5677 else
5678 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005679 break;
5680
John Kessenicha28f7a72019-08-06 07:00:58 -06005681#ifndef GLSLANG_WEB
5682 case glslang::EOpDPdxFine:
5683 unaryOp = spv::OpDPdxFine;
5684 break;
5685 case glslang::EOpDPdyFine:
5686 unaryOp = spv::OpDPdyFine;
5687 break;
5688 case glslang::EOpFwidthFine:
5689 unaryOp = spv::OpFwidthFine;
5690 break;
5691 case glslang::EOpDPdxCoarse:
5692 unaryOp = spv::OpDPdxCoarse;
5693 break;
5694 case glslang::EOpDPdyCoarse:
5695 unaryOp = spv::OpDPdyCoarse;
5696 break;
5697 case glslang::EOpFwidthCoarse:
5698 unaryOp = spv::OpFwidthCoarse;
5699 break;
5700 case glslang::EOpInterpolateAtCentroid:
5701 if (typeProxy == glslang::EbtFloat16)
5702 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5703 libCall = spv::GLSLstd450InterpolateAtCentroid;
5704 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005705 case glslang::EOpAtomicCounterIncrement:
5706 case glslang::EOpAtomicCounterDecrement:
5707 case glslang::EOpAtomicCounter:
5708 {
5709 // Handle all of the atomics in one place, in createAtomicOperation()
5710 std::vector<spv::Id> operands;
5711 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005712 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005713 }
5714
John Kessenichfc51d282015-08-19 13:34:18 -06005715 case glslang::EOpBitFieldReverse:
5716 unaryOp = spv::OpBitReverse;
5717 break;
5718 case glslang::EOpBitCount:
5719 unaryOp = spv::OpBitCount;
5720 break;
5721 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005722 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005723 break;
5724 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005725 if (isUnsigned)
5726 libCall = spv::GLSLstd450FindUMsb;
5727 else
5728 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005729 break;
5730
Rex Xu574ab042016-04-14 16:53:07 +08005731 case glslang::EOpBallot:
5732 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005733 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005734 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005735 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005736 case glslang::EOpMinInvocations:
5737 case glslang::EOpMaxInvocations:
5738 case glslang::EOpAddInvocations:
5739 case glslang::EOpMinInvocationsNonUniform:
5740 case glslang::EOpMaxInvocationsNonUniform:
5741 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005742 case glslang::EOpMinInvocationsInclusiveScan:
5743 case glslang::EOpMaxInvocationsInclusiveScan:
5744 case glslang::EOpAddInvocationsInclusiveScan:
5745 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5746 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5747 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5748 case glslang::EOpMinInvocationsExclusiveScan:
5749 case glslang::EOpMaxInvocationsExclusiveScan:
5750 case glslang::EOpAddInvocationsExclusiveScan:
5751 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5752 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5753 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005754 {
5755 std::vector<spv::Id> operands;
5756 operands.push_back(operand);
5757 return createInvocationsOperation(op, typeId, operands, typeProxy);
5758 }
John Kessenich66011cb2018-03-06 16:12:04 -07005759 case glslang::EOpSubgroupAll:
5760 case glslang::EOpSubgroupAny:
5761 case glslang::EOpSubgroupAllEqual:
5762 case glslang::EOpSubgroupBroadcastFirst:
5763 case glslang::EOpSubgroupBallot:
5764 case glslang::EOpSubgroupInverseBallot:
5765 case glslang::EOpSubgroupBallotBitCount:
5766 case glslang::EOpSubgroupBallotInclusiveBitCount:
5767 case glslang::EOpSubgroupBallotExclusiveBitCount:
5768 case glslang::EOpSubgroupBallotFindLSB:
5769 case glslang::EOpSubgroupBallotFindMSB:
5770 case glslang::EOpSubgroupAdd:
5771 case glslang::EOpSubgroupMul:
5772 case glslang::EOpSubgroupMin:
5773 case glslang::EOpSubgroupMax:
5774 case glslang::EOpSubgroupAnd:
5775 case glslang::EOpSubgroupOr:
5776 case glslang::EOpSubgroupXor:
5777 case glslang::EOpSubgroupInclusiveAdd:
5778 case glslang::EOpSubgroupInclusiveMul:
5779 case glslang::EOpSubgroupInclusiveMin:
5780 case glslang::EOpSubgroupInclusiveMax:
5781 case glslang::EOpSubgroupInclusiveAnd:
5782 case glslang::EOpSubgroupInclusiveOr:
5783 case glslang::EOpSubgroupInclusiveXor:
5784 case glslang::EOpSubgroupExclusiveAdd:
5785 case glslang::EOpSubgroupExclusiveMul:
5786 case glslang::EOpSubgroupExclusiveMin:
5787 case glslang::EOpSubgroupExclusiveMax:
5788 case glslang::EOpSubgroupExclusiveAnd:
5789 case glslang::EOpSubgroupExclusiveOr:
5790 case glslang::EOpSubgroupExclusiveXor:
5791 case glslang::EOpSubgroupQuadSwapHorizontal:
5792 case glslang::EOpSubgroupQuadSwapVertical:
5793 case glslang::EOpSubgroupQuadSwapDiagonal: {
5794 std::vector<spv::Id> operands;
5795 operands.push_back(operand);
5796 return createSubgroupOperation(op, typeId, operands, typeProxy);
5797 }
Rex Xu9d93a232016-05-05 12:30:44 +08005798 case glslang::EOpMbcnt:
5799 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5800 libCall = spv::MbcntAMD;
5801 break;
5802
5803 case glslang::EOpCubeFaceIndex:
5804 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5805 libCall = spv::CubeFaceIndexAMD;
5806 break;
5807
5808 case glslang::EOpCubeFaceCoord:
5809 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5810 libCall = spv::CubeFaceCoordAMD;
5811 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005812 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005813 unaryOp = spv::OpGroupNonUniformPartitionNV;
5814 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005815 case glslang::EOpConstructReference:
5816 unaryOp = spv::OpBitcast;
5817 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005818#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005819
5820 case glslang::EOpCopyObject:
5821 unaryOp = spv::OpCopyObject;
5822 break;
5823
John Kessenich140f3df2015-06-26 16:58:36 -06005824 default:
5825 return 0;
5826 }
5827
5828 spv::Id id;
5829 if (libCall >= 0) {
5830 std::vector<spv::Id> args;
5831 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005832 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005833 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005834 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005835 }
John Kessenich140f3df2015-06-26 16:58:36 -06005836
John Kessenichb9197c82019-08-11 07:41:45 -06005837 decorations.addNoContraction(builder, id);
5838 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005839 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005840}
5841
John Kessenich7a53f762016-01-20 11:19:27 -07005842// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005843spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5844 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005845{
5846 // Handle unary operations vector by vector.
5847 // The result type is the same type as the original type.
5848 // The algorithm is to:
5849 // - break the matrix into vectors
5850 // - apply the operation to each vector
5851 // - make a matrix out the vector results
5852
5853 // get the types sorted out
5854 int numCols = builder.getNumColumns(operand);
5855 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005856 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5857 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005858 std::vector<spv::Id> results;
5859
5860 // do each vector op
5861 for (int c = 0; c < numCols; ++c) {
5862 std::vector<unsigned int> indexes;
5863 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005864 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5865 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005866 decorations.addNoContraction(builder, destVec);
5867 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005868 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005869 }
5870
5871 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005872 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005873 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005874 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005875}
5876
John Kessenichad7645f2018-06-04 19:11:25 -06005877// For converting integers where both the bitwidth and the signedness could
5878// change, but only do the width change here. The caller is still responsible
5879// for the signedness conversion.
5880spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005881{
John Kessenichad7645f2018-06-04 19:11:25 -06005882 // Get the result type width, based on the type to convert to.
5883 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005884 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005885 case glslang::EOpConvInt16ToUint8:
5886 case glslang::EOpConvIntToUint8:
5887 case glslang::EOpConvInt64ToUint8:
5888 case glslang::EOpConvUint16ToInt8:
5889 case glslang::EOpConvUintToInt8:
5890 case glslang::EOpConvUint64ToInt8:
5891 width = 8;
5892 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005893 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005894 case glslang::EOpConvIntToUint16:
5895 case glslang::EOpConvInt64ToUint16:
5896 case glslang::EOpConvUint8ToInt16:
5897 case glslang::EOpConvUintToInt16:
5898 case glslang::EOpConvUint64ToInt16:
5899 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005900 break;
5901 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005902 case glslang::EOpConvInt16ToUint:
5903 case glslang::EOpConvInt64ToUint:
5904 case glslang::EOpConvUint8ToInt:
5905 case glslang::EOpConvUint16ToInt:
5906 case glslang::EOpConvUint64ToInt:
5907 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005908 break;
5909 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005910 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005911 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005912 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005913 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005914 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005915 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005916 break;
5917
5918 default:
5919 assert(false && "Default missing");
5920 break;
5921 }
5922
John Kessenichad7645f2018-06-04 19:11:25 -06005923 // Get the conversion operation and result type,
5924 // based on the target width, but the source type.
5925 spv::Id type = spv::NoType;
5926 spv::Op convOp = spv::OpNop;
5927 switch(op) {
5928 case glslang::EOpConvInt8ToUint16:
5929 case glslang::EOpConvInt8ToUint:
5930 case glslang::EOpConvInt8ToUint64:
5931 case glslang::EOpConvInt16ToUint8:
5932 case glslang::EOpConvInt16ToUint:
5933 case glslang::EOpConvInt16ToUint64:
5934 case glslang::EOpConvIntToUint8:
5935 case glslang::EOpConvIntToUint16:
5936 case glslang::EOpConvIntToUint64:
5937 case glslang::EOpConvInt64ToUint8:
5938 case glslang::EOpConvInt64ToUint16:
5939 case glslang::EOpConvInt64ToUint:
5940 convOp = spv::OpSConvert;
5941 type = builder.makeIntType(width);
5942 break;
5943 default:
5944 convOp = spv::OpUConvert;
5945 type = builder.makeUintType(width);
5946 break;
5947 }
5948
John Kessenich66011cb2018-03-06 16:12:04 -07005949 if (vectorSize > 0)
5950 type = builder.makeVectorType(type, vectorSize);
5951
John Kessenichad7645f2018-06-04 19:11:25 -06005952 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005953}
5954
John Kessenichead86222018-03-28 18:01:20 -06005955spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5956 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005957{
5958 spv::Op convOp = spv::OpNop;
5959 spv::Id zero = 0;
5960 spv::Id one = 0;
5961
5962 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5963
5964 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005965 case glslang::EOpConvIntToBool:
5966 case glslang::EOpConvUintToBool:
5967 zero = builder.makeUintConstant(0);
5968 zero = makeSmearedConstant(zero, vectorSize);
5969 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005970 case glslang::EOpConvFloatToBool:
5971 zero = builder.makeFloatConstant(0.0F);
5972 zero = makeSmearedConstant(zero, vectorSize);
5973 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005974 case glslang::EOpConvBoolToFloat:
5975 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005976 zero = builder.makeFloatConstant(0.0F);
5977 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005978 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005979
John Kessenich140f3df2015-06-26 16:58:36 -06005980 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005981 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06005982#ifndef GLSLANG_WEB
5983 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08005984 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005985 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005986 } else
5987#endif
5988 {
5989 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005990 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005991 }
Rex Xucabbb782017-03-24 13:41:14 +08005992
John Kessenich140f3df2015-06-26 16:58:36 -06005993 convOp = spv::OpSelect;
5994 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005995
John Kessenich140f3df2015-06-26 16:58:36 -06005996 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005997 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06005998#ifndef GLSLANG_WEB
5999 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006000 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006001 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006002 } else
6003#endif
6004 {
6005 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006006 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006007 }
Rex Xucabbb782017-03-24 13:41:14 +08006008
John Kessenich140f3df2015-06-26 16:58:36 -06006009 convOp = spv::OpSelect;
6010 break;
6011
John Kessenich66011cb2018-03-06 16:12:04 -07006012 case glslang::EOpConvInt8ToFloat16:
6013 case glslang::EOpConvInt8ToFloat:
6014 case glslang::EOpConvInt8ToDouble:
6015 case glslang::EOpConvInt16ToFloat16:
6016 case glslang::EOpConvInt16ToFloat:
6017 case glslang::EOpConvInt16ToDouble:
6018 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006019 case glslang::EOpConvIntToFloat:
6020 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006021 case glslang::EOpConvInt64ToFloat:
6022 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006023 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006024 convOp = spv::OpConvertSToF;
6025 break;
6026
John Kessenich66011cb2018-03-06 16:12:04 -07006027 case glslang::EOpConvUint8ToFloat16:
6028 case glslang::EOpConvUint8ToFloat:
6029 case glslang::EOpConvUint8ToDouble:
6030 case glslang::EOpConvUint16ToFloat16:
6031 case glslang::EOpConvUint16ToFloat:
6032 case glslang::EOpConvUint16ToDouble:
6033 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006034 case glslang::EOpConvUintToFloat:
6035 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006036 case glslang::EOpConvUint64ToFloat:
6037 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006038 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006039 convOp = spv::OpConvertUToF;
6040 break;
6041
John Kessenich66011cb2018-03-06 16:12:04 -07006042 case glslang::EOpConvFloat16ToInt8:
6043 case glslang::EOpConvFloatToInt8:
6044 case glslang::EOpConvDoubleToInt8:
6045 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006046 case glslang::EOpConvFloatToInt16:
6047 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006048 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006049 case glslang::EOpConvFloatToInt:
6050 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006051 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006052 case glslang::EOpConvFloatToInt64:
6053 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006054 convOp = spv::OpConvertFToS;
6055 break;
6056
John Kessenich66011cb2018-03-06 16:12:04 -07006057 case glslang::EOpConvUint8ToInt8:
6058 case glslang::EOpConvInt8ToUint8:
6059 case glslang::EOpConvUint16ToInt16:
6060 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006061 case glslang::EOpConvUintToInt:
6062 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006063 case glslang::EOpConvUint64ToInt64:
6064 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006065 if (builder.isInSpecConstCodeGenMode()) {
6066 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006067#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006068 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6069 zero = builder.makeUint8Constant(0);
6070 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006071 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006072 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6073 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006074 } else
6075#endif
6076 {
Rex Xucabbb782017-03-24 13:41:14 +08006077 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006078 }
qining189b2032016-04-12 23:16:20 -04006079 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006080 // Use OpIAdd, instead of OpBitcast to do the conversion when
6081 // generating for OpSpecConstantOp instruction.
6082 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6083 }
6084 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006085 convOp = spv::OpBitcast;
6086 break;
6087
John Kessenich66011cb2018-03-06 16:12:04 -07006088 case glslang::EOpConvFloat16ToUint8:
6089 case glslang::EOpConvFloatToUint8:
6090 case glslang::EOpConvDoubleToUint8:
6091 case glslang::EOpConvFloat16ToUint16:
6092 case glslang::EOpConvFloatToUint16:
6093 case glslang::EOpConvDoubleToUint16:
6094 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006095 case glslang::EOpConvFloatToUint:
6096 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006097 case glslang::EOpConvFloatToUint64:
6098 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006099 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006100 convOp = spv::OpConvertFToU;
6101 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006102
John Kessenich39697cd2019-08-08 10:35:51 -06006103#ifndef GLSLANG_WEB
6104 case glslang::EOpConvInt8ToBool:
6105 case glslang::EOpConvUint8ToBool:
6106 zero = builder.makeUint8Constant(0);
6107 zero = makeSmearedConstant(zero, vectorSize);
6108 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6109 case glslang::EOpConvInt16ToBool:
6110 case glslang::EOpConvUint16ToBool:
6111 zero = builder.makeUint16Constant(0);
6112 zero = makeSmearedConstant(zero, vectorSize);
6113 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6114 case glslang::EOpConvInt64ToBool:
6115 case glslang::EOpConvUint64ToBool:
6116 zero = builder.makeUint64Constant(0);
6117 zero = makeSmearedConstant(zero, vectorSize);
6118 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6119 case glslang::EOpConvDoubleToBool:
6120 zero = builder.makeDoubleConstant(0.0);
6121 zero = makeSmearedConstant(zero, vectorSize);
6122 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6123 case glslang::EOpConvFloat16ToBool:
6124 zero = builder.makeFloat16Constant(0.0F);
6125 zero = makeSmearedConstant(zero, vectorSize);
6126 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6127 case glslang::EOpConvBoolToDouble:
6128 convOp = spv::OpSelect;
6129 zero = builder.makeDoubleConstant(0.0);
6130 one = builder.makeDoubleConstant(1.0);
6131 break;
6132 case glslang::EOpConvBoolToFloat16:
6133 convOp = spv::OpSelect;
6134 zero = builder.makeFloat16Constant(0.0F);
6135 one = builder.makeFloat16Constant(1.0F);
6136 break;
6137 case glslang::EOpConvBoolToInt8:
6138 zero = builder.makeInt8Constant(0);
6139 one = builder.makeInt8Constant(1);
6140 convOp = spv::OpSelect;
6141 break;
6142 case glslang::EOpConvBoolToUint8:
6143 zero = builder.makeUint8Constant(0);
6144 one = builder.makeUint8Constant(1);
6145 convOp = spv::OpSelect;
6146 break;
6147 case glslang::EOpConvBoolToInt16:
6148 zero = builder.makeInt16Constant(0);
6149 one = builder.makeInt16Constant(1);
6150 convOp = spv::OpSelect;
6151 break;
6152 case glslang::EOpConvBoolToUint16:
6153 zero = builder.makeUint16Constant(0);
6154 one = builder.makeUint16Constant(1);
6155 convOp = spv::OpSelect;
6156 break;
6157 case glslang::EOpConvDoubleToFloat:
6158 case glslang::EOpConvFloatToDouble:
6159 case glslang::EOpConvDoubleToFloat16:
6160 case glslang::EOpConvFloat16ToDouble:
6161 case glslang::EOpConvFloatToFloat16:
6162 case glslang::EOpConvFloat16ToFloat:
6163 convOp = spv::OpFConvert;
6164 if (builder.isMatrixType(destType))
6165 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6166 break;
6167
John Kessenich66011cb2018-03-06 16:12:04 -07006168 case glslang::EOpConvInt8ToInt16:
6169 case glslang::EOpConvInt8ToInt:
6170 case glslang::EOpConvInt8ToInt64:
6171 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006172 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006173 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006174 case glslang::EOpConvIntToInt8:
6175 case glslang::EOpConvIntToInt16:
6176 case glslang::EOpConvIntToInt64:
6177 case glslang::EOpConvInt64ToInt8:
6178 case glslang::EOpConvInt64ToInt16:
6179 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006180 convOp = spv::OpSConvert;
6181 break;
6182
John Kessenich66011cb2018-03-06 16:12:04 -07006183 case glslang::EOpConvUint8ToUint16:
6184 case glslang::EOpConvUint8ToUint:
6185 case glslang::EOpConvUint8ToUint64:
6186 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006187 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006188 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006189 case glslang::EOpConvUintToUint8:
6190 case glslang::EOpConvUintToUint16:
6191 case glslang::EOpConvUintToUint64:
6192 case glslang::EOpConvUint64ToUint8:
6193 case glslang::EOpConvUint64ToUint16:
6194 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006195 convOp = spv::OpUConvert;
6196 break;
6197
John Kessenich66011cb2018-03-06 16:12:04 -07006198 case glslang::EOpConvInt8ToUint16:
6199 case glslang::EOpConvInt8ToUint:
6200 case glslang::EOpConvInt8ToUint64:
6201 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006202 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006203 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006204 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006205 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006206 case glslang::EOpConvIntToUint64:
6207 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006208 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006209 case glslang::EOpConvInt64ToUint:
6210 case glslang::EOpConvUint8ToInt16:
6211 case glslang::EOpConvUint8ToInt:
6212 case glslang::EOpConvUint8ToInt64:
6213 case glslang::EOpConvUint16ToInt8:
6214 case glslang::EOpConvUint16ToInt:
6215 case glslang::EOpConvUint16ToInt64:
6216 case glslang::EOpConvUintToInt8:
6217 case glslang::EOpConvUintToInt16:
6218 case glslang::EOpConvUintToInt64:
6219 case glslang::EOpConvUint64ToInt8:
6220 case glslang::EOpConvUint64ToInt16:
6221 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006222 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006223 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006224
6225 if (builder.isInSpecConstCodeGenMode()) {
6226 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006227 switch(op) {
6228 case glslang::EOpConvInt16ToUint8:
6229 case glslang::EOpConvIntToUint8:
6230 case glslang::EOpConvInt64ToUint8:
6231 case glslang::EOpConvUint16ToInt8:
6232 case glslang::EOpConvUintToInt8:
6233 case glslang::EOpConvUint64ToInt8:
6234 zero = builder.makeUint8Constant(0);
6235 break;
6236 case glslang::EOpConvInt8ToUint16:
6237 case glslang::EOpConvIntToUint16:
6238 case glslang::EOpConvInt64ToUint16:
6239 case glslang::EOpConvUint8ToInt16:
6240 case glslang::EOpConvUintToInt16:
6241 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006242 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006243 break;
6244 case glslang::EOpConvInt8ToUint:
6245 case glslang::EOpConvInt16ToUint:
6246 case glslang::EOpConvInt64ToUint:
6247 case glslang::EOpConvUint8ToInt:
6248 case glslang::EOpConvUint16ToInt:
6249 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006250 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006251 break;
6252 case glslang::EOpConvInt8ToUint64:
6253 case glslang::EOpConvInt16ToUint64:
6254 case glslang::EOpConvIntToUint64:
6255 case glslang::EOpConvUint8ToInt64:
6256 case glslang::EOpConvUint16ToInt64:
6257 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006258 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006259 break;
6260 default:
6261 assert(false && "Default missing");
6262 break;
6263 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006264 zero = makeSmearedConstant(zero, vectorSize);
6265 // Use OpIAdd, instead of OpBitcast to do the conversion when
6266 // generating for OpSpecConstantOp instruction.
6267 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6268 }
6269 // For normal run-time conversion instruction, use OpBitcast.
6270 convOp = spv::OpBitcast;
6271 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006272 case glslang::EOpConvUint64ToPtr:
6273 convOp = spv::OpConvertUToPtr;
6274 break;
6275 case glslang::EOpConvPtrToUint64:
6276 convOp = spv::OpConvertPtrToU;
6277 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006278 case glslang::EOpConvPtrToUvec2:
6279 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006280 if (builder.isVector(operand))
6281 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6282 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006283 convOp = spv::OpBitcast;
6284 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006285#endif
6286
John Kessenich140f3df2015-06-26 16:58:36 -06006287 default:
6288 break;
6289 }
6290
6291 spv::Id result = 0;
6292 if (convOp == spv::OpNop)
6293 return result;
6294
6295 if (convOp == spv::OpSelect) {
6296 zero = makeSmearedConstant(zero, vectorSize);
6297 one = makeSmearedConstant(one, vectorSize);
6298 result = builder.createTriOp(convOp, destType, operand, one, zero);
6299 } else
6300 result = builder.createUnaryOp(convOp, destType, operand);
6301
John Kessenichead86222018-03-28 18:01:20 -06006302 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006303 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006304 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006305}
6306
6307spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6308{
6309 if (vectorSize == 0)
6310 return constant;
6311
6312 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6313 std::vector<spv::Id> components;
6314 for (int c = 0; c < vectorSize; ++c)
6315 components.push_back(constant);
6316 return builder.makeCompositeConstant(vectorTypeId, components);
6317}
6318
John Kessenich426394d2015-07-23 10:22:48 -06006319// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006320spv::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 -06006321{
6322 spv::Op opCode = spv::OpNop;
6323
6324 switch (op) {
6325 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006326 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006327 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006328 opCode = spv::OpAtomicIAdd;
6329 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006330 case glslang::EOpAtomicCounterSubtract:
6331 opCode = spv::OpAtomicISub;
6332 break;
John Kessenich426394d2015-07-23 10:22:48 -06006333 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006334 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006335 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006336 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006337 break;
6338 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006339 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006340 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006341 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006342 break;
6343 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006344 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006345 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006346 opCode = spv::OpAtomicAnd;
6347 break;
6348 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006349 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006350 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006351 opCode = spv::OpAtomicOr;
6352 break;
6353 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006354 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006355 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006356 opCode = spv::OpAtomicXor;
6357 break;
6358 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006359 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006360 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006361 opCode = spv::OpAtomicExchange;
6362 break;
6363 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006364 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006365 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006366 opCode = spv::OpAtomicCompareExchange;
6367 break;
6368 case glslang::EOpAtomicCounterIncrement:
6369 opCode = spv::OpAtomicIIncrement;
6370 break;
6371 case glslang::EOpAtomicCounterDecrement:
6372 opCode = spv::OpAtomicIDecrement;
6373 break;
6374 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006375 case glslang::EOpImageAtomicLoad:
6376 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006377 opCode = spv::OpAtomicLoad;
6378 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006379 case glslang::EOpAtomicStore:
6380 case glslang::EOpImageAtomicStore:
6381 opCode = spv::OpAtomicStore;
6382 break;
John Kessenich426394d2015-07-23 10:22:48 -06006383 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006384 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006385 break;
6386 }
6387
Rex Xue8fe8b02017-09-26 15:42:56 +08006388 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6389 builder.addCapability(spv::CapabilityInt64Atomics);
6390
John Kessenich426394d2015-07-23 10:22:48 -06006391 // Sort out the operands
6392 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006393 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006394 // - compare-exchange swaps the value and comparator
6395 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006396 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006397 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6398 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6399 spv::Id scopeId;
6400 if (glslangIntermediate->usingVulkanMemoryModel()) {
6401 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6402 } else {
6403 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6404 }
6405 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006406 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006407 spv::MemorySemanticsVolatileMask :
6408 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006409 spv::Id semanticsId2 = semanticsId;
6410
6411 pointerId = operands[0];
6412 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6413 // no additional operands
6414 } else if (opCode == spv::OpAtomicCompareExchange) {
6415 compareId = operands[1];
6416 valueId = operands[2];
6417 if (operands.size() > 3) {
6418 scopeId = operands[3];
6419 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6420 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6421 }
6422 } else if (opCode == spv::OpAtomicLoad) {
6423 if (operands.size() > 1) {
6424 scopeId = operands[1];
6425 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6426 }
6427 } else {
6428 // atomic store or RMW
6429 valueId = operands[1];
6430 if (operands.size() > 2) {
6431 scopeId = operands[2];
6432 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6433 }
Rex Xu04db3f52015-09-16 11:44:02 +08006434 }
John Kessenich426394d2015-07-23 10:22:48 -06006435
Jeff Bolz36831c92018-09-05 10:11:41 -05006436 // Check for capabilities
6437 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006438 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6439 spv::MemorySemanticsMakeVisibleKHRMask |
6440 spv::MemorySemanticsOutputMemoryKHRMask |
6441 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006442 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6443 }
John Kessenich426394d2015-07-23 10:22:48 -06006444
Jeff Bolz36831c92018-09-05 10:11:41 -05006445 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6446 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6447 }
John Kessenich48d6e792017-10-06 21:21:48 -06006448
Jeff Bolz36831c92018-09-05 10:11:41 -05006449 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6450 spvAtomicOperands.push_back(pointerId);
6451 spvAtomicOperands.push_back(scopeId);
6452 spvAtomicOperands.push_back(semanticsId);
6453 if (opCode == spv::OpAtomicCompareExchange) {
6454 spvAtomicOperands.push_back(semanticsId2);
6455 spvAtomicOperands.push_back(valueId);
6456 spvAtomicOperands.push_back(compareId);
6457 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6458 spvAtomicOperands.push_back(valueId);
6459 }
John Kessenich48d6e792017-10-06 21:21:48 -06006460
Jeff Bolz36831c92018-09-05 10:11:41 -05006461 if (opCode == spv::OpAtomicStore) {
6462 builder.createNoResultOp(opCode, spvAtomicOperands);
6463 return 0;
6464 } else {
6465 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6466
6467 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6468 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6469 if (op == glslang::EOpAtomicCounterDecrement)
6470 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6471
6472 return resultId;
6473 }
John Kessenich426394d2015-07-23 10:22:48 -06006474}
6475
John Kessenich91cef522016-05-05 16:45:40 -06006476// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006477spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006478{
John Kessenich66011cb2018-03-06 16:12:04 -07006479 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6480 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006481
Rex Xu51596642016-09-21 18:56:12 +08006482 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006483 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006484 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6485
chaocf200da82016-12-20 12:44:35 -08006486 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6487 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006488 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6489 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006490 } else if (op == glslang::EOpAnyInvocation ||
6491 op == glslang::EOpAllInvocations ||
6492 op == glslang::EOpAllInvocationsEqual) {
6493 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6494 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006495 } else {
6496 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006497 if (op == glslang::EOpMinInvocationsNonUniform ||
6498 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006499 op == glslang::EOpAddInvocationsNonUniform ||
6500 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6501 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6502 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6503 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6504 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6505 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006506 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006507
Rex Xu430ef402016-10-14 17:22:23 +08006508 switch (op) {
6509 case glslang::EOpMinInvocations:
6510 case glslang::EOpMaxInvocations:
6511 case glslang::EOpAddInvocations:
6512 case glslang::EOpMinInvocationsNonUniform:
6513 case glslang::EOpMaxInvocationsNonUniform:
6514 case glslang::EOpAddInvocationsNonUniform:
6515 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006516 break;
6517 case glslang::EOpMinInvocationsInclusiveScan:
6518 case glslang::EOpMaxInvocationsInclusiveScan:
6519 case glslang::EOpAddInvocationsInclusiveScan:
6520 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6521 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6522 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6523 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006524 break;
6525 case glslang::EOpMinInvocationsExclusiveScan:
6526 case glslang::EOpMaxInvocationsExclusiveScan:
6527 case glslang::EOpAddInvocationsExclusiveScan:
6528 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6529 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6530 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6531 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006532 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006533 default:
6534 break;
Rex Xu430ef402016-10-14 17:22:23 +08006535 }
John Kessenich149afc32018-08-14 13:31:43 -06006536 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6537 spvGroupOperands.push_back(scope);
6538 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006539 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006540 spvGroupOperands.push_back(groupOp);
6541 }
Rex Xu51596642016-09-21 18:56:12 +08006542 }
6543
John Kessenich149afc32018-08-14 13:31:43 -06006544 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6545 spv::IdImmediate op = { true, *opIt };
6546 spvGroupOperands.push_back(op);
6547 }
John Kessenich91cef522016-05-05 16:45:40 -06006548
6549 switch (op) {
6550 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006551 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006552 break;
John Kessenich91cef522016-05-05 16:45:40 -06006553 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006554 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006555 break;
John Kessenich91cef522016-05-05 16:45:40 -06006556 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006557 opCode = spv::OpSubgroupAllEqualKHR;
6558 break;
Rex Xu51596642016-09-21 18:56:12 +08006559 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006560 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006561 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006562 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006563 break;
6564 case glslang::EOpReadFirstInvocation:
6565 opCode = spv::OpSubgroupFirstInvocationKHR;
6566 break;
6567 case glslang::EOpBallot:
6568 {
6569 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6570 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6571 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6572 //
6573 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6574 //
6575 spv::Id uintType = builder.makeUintType(32);
6576 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6577 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6578
6579 std::vector<spv::Id> components;
6580 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6581 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6582
6583 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6584 return builder.createUnaryOp(spv::OpBitcast, typeId,
6585 builder.createCompositeConstruct(uvec2Type, components));
6586 }
6587
Rex Xu9d93a232016-05-05 12:30:44 +08006588 case glslang::EOpMinInvocations:
6589 case glslang::EOpMaxInvocations:
6590 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006591 case glslang::EOpMinInvocationsInclusiveScan:
6592 case glslang::EOpMaxInvocationsInclusiveScan:
6593 case glslang::EOpAddInvocationsInclusiveScan:
6594 case glslang::EOpMinInvocationsExclusiveScan:
6595 case glslang::EOpMaxInvocationsExclusiveScan:
6596 case glslang::EOpAddInvocationsExclusiveScan:
6597 if (op == glslang::EOpMinInvocations ||
6598 op == glslang::EOpMinInvocationsInclusiveScan ||
6599 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006600 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006601 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006602 else {
6603 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006604 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006605 else
Rex Xu51596642016-09-21 18:56:12 +08006606 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006607 }
Rex Xu430ef402016-10-14 17:22:23 +08006608 } else if (op == glslang::EOpMaxInvocations ||
6609 op == glslang::EOpMaxInvocationsInclusiveScan ||
6610 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006611 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006612 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006613 else {
6614 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006615 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006616 else
Rex Xu51596642016-09-21 18:56:12 +08006617 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006618 }
6619 } else {
6620 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006621 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006622 else
Rex Xu51596642016-09-21 18:56:12 +08006623 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006624 }
6625
Rex Xu2bbbe062016-08-23 15:41:05 +08006626 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006627 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006628
6629 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006630 case glslang::EOpMinInvocationsNonUniform:
6631 case glslang::EOpMaxInvocationsNonUniform:
6632 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006633 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6634 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6635 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6636 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6637 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6638 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6639 if (op == glslang::EOpMinInvocationsNonUniform ||
6640 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6641 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006642 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006643 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006644 else {
6645 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006646 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006647 else
Rex Xu51596642016-09-21 18:56:12 +08006648 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006649 }
6650 }
Rex Xu430ef402016-10-14 17:22:23 +08006651 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6652 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6653 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006654 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006655 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006656 else {
6657 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006658 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006659 else
Rex Xu51596642016-09-21 18:56:12 +08006660 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006661 }
6662 }
6663 else {
6664 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006665 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006666 else
Rex Xu51596642016-09-21 18:56:12 +08006667 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006668 }
6669
Rex Xu2bbbe062016-08-23 15:41:05 +08006670 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006671 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006672
6673 break;
John Kessenich91cef522016-05-05 16:45:40 -06006674 default:
6675 logger->missingFunctionality("invocation operation");
6676 return spv::NoResult;
6677 }
Rex Xu51596642016-09-21 18:56:12 +08006678
6679 assert(opCode != spv::OpNop);
6680 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006681}
6682
Rex Xu2bbbe062016-08-23 15:41:05 +08006683// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006684spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6685 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006686{
6687 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6688 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006689 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006690 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006691 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6692 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6693 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6694
6695 // Handle group invocation operations scalar by scalar.
6696 // The result type is the same type as the original type.
6697 // The algorithm is to:
6698 // - break the vector into scalars
6699 // - apply the operation to each scalar
6700 // - make a vector out the scalar results
6701
6702 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006703 int numComponents = builder.getNumComponents(operands[0]);
6704 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006705 std::vector<spv::Id> results;
6706
6707 // do each scalar op
6708 for (int comp = 0; comp < numComponents; ++comp) {
6709 std::vector<unsigned int> indexes;
6710 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006711 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6712 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006713 if (op == spv::OpSubgroupReadInvocationKHR) {
6714 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006715 spv::IdImmediate operand = { true, operands[1] };
6716 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006717 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006718 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6719 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006720 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006721 spv::IdImmediate operand = { true, operands[1] };
6722 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006723 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006724 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6725 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006726 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006727 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006728 spvGroupOperands.push_back(scalar);
6729 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006730
Rex Xub7072052016-09-26 15:53:40 +08006731 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006732 }
6733
6734 // put the pieces together
6735 return builder.createCompositeConstruct(typeId, results);
6736}
Rex Xu2bbbe062016-08-23 15:41:05 +08006737
John Kessenich66011cb2018-03-06 16:12:04 -07006738// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006739spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6740 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006741{
6742 // Add the required capabilities.
6743 switch (op) {
6744 case glslang::EOpSubgroupElect:
6745 builder.addCapability(spv::CapabilityGroupNonUniform);
6746 break;
6747 case glslang::EOpSubgroupAll:
6748 case glslang::EOpSubgroupAny:
6749 case glslang::EOpSubgroupAllEqual:
6750 builder.addCapability(spv::CapabilityGroupNonUniform);
6751 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6752 break;
6753 case glslang::EOpSubgroupBroadcast:
6754 case glslang::EOpSubgroupBroadcastFirst:
6755 case glslang::EOpSubgroupBallot:
6756 case glslang::EOpSubgroupInverseBallot:
6757 case glslang::EOpSubgroupBallotBitExtract:
6758 case glslang::EOpSubgroupBallotBitCount:
6759 case glslang::EOpSubgroupBallotInclusiveBitCount:
6760 case glslang::EOpSubgroupBallotExclusiveBitCount:
6761 case glslang::EOpSubgroupBallotFindLSB:
6762 case glslang::EOpSubgroupBallotFindMSB:
6763 builder.addCapability(spv::CapabilityGroupNonUniform);
6764 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6765 break;
6766 case glslang::EOpSubgroupShuffle:
6767 case glslang::EOpSubgroupShuffleXor:
6768 builder.addCapability(spv::CapabilityGroupNonUniform);
6769 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6770 break;
6771 case glslang::EOpSubgroupShuffleUp:
6772 case glslang::EOpSubgroupShuffleDown:
6773 builder.addCapability(spv::CapabilityGroupNonUniform);
6774 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6775 break;
6776 case glslang::EOpSubgroupAdd:
6777 case glslang::EOpSubgroupMul:
6778 case glslang::EOpSubgroupMin:
6779 case glslang::EOpSubgroupMax:
6780 case glslang::EOpSubgroupAnd:
6781 case glslang::EOpSubgroupOr:
6782 case glslang::EOpSubgroupXor:
6783 case glslang::EOpSubgroupInclusiveAdd:
6784 case glslang::EOpSubgroupInclusiveMul:
6785 case glslang::EOpSubgroupInclusiveMin:
6786 case glslang::EOpSubgroupInclusiveMax:
6787 case glslang::EOpSubgroupInclusiveAnd:
6788 case glslang::EOpSubgroupInclusiveOr:
6789 case glslang::EOpSubgroupInclusiveXor:
6790 case glslang::EOpSubgroupExclusiveAdd:
6791 case glslang::EOpSubgroupExclusiveMul:
6792 case glslang::EOpSubgroupExclusiveMin:
6793 case glslang::EOpSubgroupExclusiveMax:
6794 case glslang::EOpSubgroupExclusiveAnd:
6795 case glslang::EOpSubgroupExclusiveOr:
6796 case glslang::EOpSubgroupExclusiveXor:
6797 builder.addCapability(spv::CapabilityGroupNonUniform);
6798 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6799 break;
6800 case glslang::EOpSubgroupClusteredAdd:
6801 case glslang::EOpSubgroupClusteredMul:
6802 case glslang::EOpSubgroupClusteredMin:
6803 case glslang::EOpSubgroupClusteredMax:
6804 case glslang::EOpSubgroupClusteredAnd:
6805 case glslang::EOpSubgroupClusteredOr:
6806 case glslang::EOpSubgroupClusteredXor:
6807 builder.addCapability(spv::CapabilityGroupNonUniform);
6808 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6809 break;
6810 case glslang::EOpSubgroupQuadBroadcast:
6811 case glslang::EOpSubgroupQuadSwapHorizontal:
6812 case glslang::EOpSubgroupQuadSwapVertical:
6813 case glslang::EOpSubgroupQuadSwapDiagonal:
6814 builder.addCapability(spv::CapabilityGroupNonUniform);
6815 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6816 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006817 case glslang::EOpSubgroupPartitionedAdd:
6818 case glslang::EOpSubgroupPartitionedMul:
6819 case glslang::EOpSubgroupPartitionedMin:
6820 case glslang::EOpSubgroupPartitionedMax:
6821 case glslang::EOpSubgroupPartitionedAnd:
6822 case glslang::EOpSubgroupPartitionedOr:
6823 case glslang::EOpSubgroupPartitionedXor:
6824 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6825 case glslang::EOpSubgroupPartitionedInclusiveMul:
6826 case glslang::EOpSubgroupPartitionedInclusiveMin:
6827 case glslang::EOpSubgroupPartitionedInclusiveMax:
6828 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6829 case glslang::EOpSubgroupPartitionedInclusiveOr:
6830 case glslang::EOpSubgroupPartitionedInclusiveXor:
6831 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6832 case glslang::EOpSubgroupPartitionedExclusiveMul:
6833 case glslang::EOpSubgroupPartitionedExclusiveMin:
6834 case glslang::EOpSubgroupPartitionedExclusiveMax:
6835 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6836 case glslang::EOpSubgroupPartitionedExclusiveOr:
6837 case glslang::EOpSubgroupPartitionedExclusiveXor:
6838 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6839 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6840 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006841 default: assert(0 && "Unhandled subgroup operation!");
6842 }
6843
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006844
6845 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6846 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006847 const bool isBool = typeProxy == glslang::EbtBool;
6848
6849 spv::Op opCode = spv::OpNop;
6850
6851 // Figure out which opcode to use.
6852 switch (op) {
6853 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6854 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6855 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6856 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6857 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6858 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6859 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6860 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6861 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6862 case glslang::EOpSubgroupBallotBitCount:
6863 case glslang::EOpSubgroupBallotInclusiveBitCount:
6864 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6865 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6866 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6867 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6868 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6869 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6870 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6871 case glslang::EOpSubgroupAdd:
6872 case glslang::EOpSubgroupInclusiveAdd:
6873 case glslang::EOpSubgroupExclusiveAdd:
6874 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006875 case glslang::EOpSubgroupPartitionedAdd:
6876 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6877 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006878 if (isFloat) {
6879 opCode = spv::OpGroupNonUniformFAdd;
6880 } else {
6881 opCode = spv::OpGroupNonUniformIAdd;
6882 }
6883 break;
6884 case glslang::EOpSubgroupMul:
6885 case glslang::EOpSubgroupInclusiveMul:
6886 case glslang::EOpSubgroupExclusiveMul:
6887 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006888 case glslang::EOpSubgroupPartitionedMul:
6889 case glslang::EOpSubgroupPartitionedInclusiveMul:
6890 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006891 if (isFloat) {
6892 opCode = spv::OpGroupNonUniformFMul;
6893 } else {
6894 opCode = spv::OpGroupNonUniformIMul;
6895 }
6896 break;
6897 case glslang::EOpSubgroupMin:
6898 case glslang::EOpSubgroupInclusiveMin:
6899 case glslang::EOpSubgroupExclusiveMin:
6900 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006901 case glslang::EOpSubgroupPartitionedMin:
6902 case glslang::EOpSubgroupPartitionedInclusiveMin:
6903 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006904 if (isFloat) {
6905 opCode = spv::OpGroupNonUniformFMin;
6906 } else if (isUnsigned) {
6907 opCode = spv::OpGroupNonUniformUMin;
6908 } else {
6909 opCode = spv::OpGroupNonUniformSMin;
6910 }
6911 break;
6912 case glslang::EOpSubgroupMax:
6913 case glslang::EOpSubgroupInclusiveMax:
6914 case glslang::EOpSubgroupExclusiveMax:
6915 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006916 case glslang::EOpSubgroupPartitionedMax:
6917 case glslang::EOpSubgroupPartitionedInclusiveMax:
6918 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006919 if (isFloat) {
6920 opCode = spv::OpGroupNonUniformFMax;
6921 } else if (isUnsigned) {
6922 opCode = spv::OpGroupNonUniformUMax;
6923 } else {
6924 opCode = spv::OpGroupNonUniformSMax;
6925 }
6926 break;
6927 case glslang::EOpSubgroupAnd:
6928 case glslang::EOpSubgroupInclusiveAnd:
6929 case glslang::EOpSubgroupExclusiveAnd:
6930 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006931 case glslang::EOpSubgroupPartitionedAnd:
6932 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6933 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006934 if (isBool) {
6935 opCode = spv::OpGroupNonUniformLogicalAnd;
6936 } else {
6937 opCode = spv::OpGroupNonUniformBitwiseAnd;
6938 }
6939 break;
6940 case glslang::EOpSubgroupOr:
6941 case glslang::EOpSubgroupInclusiveOr:
6942 case glslang::EOpSubgroupExclusiveOr:
6943 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006944 case glslang::EOpSubgroupPartitionedOr:
6945 case glslang::EOpSubgroupPartitionedInclusiveOr:
6946 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006947 if (isBool) {
6948 opCode = spv::OpGroupNonUniformLogicalOr;
6949 } else {
6950 opCode = spv::OpGroupNonUniformBitwiseOr;
6951 }
6952 break;
6953 case glslang::EOpSubgroupXor:
6954 case glslang::EOpSubgroupInclusiveXor:
6955 case glslang::EOpSubgroupExclusiveXor:
6956 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006957 case glslang::EOpSubgroupPartitionedXor:
6958 case glslang::EOpSubgroupPartitionedInclusiveXor:
6959 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006960 if (isBool) {
6961 opCode = spv::OpGroupNonUniformLogicalXor;
6962 } else {
6963 opCode = spv::OpGroupNonUniformBitwiseXor;
6964 }
6965 break;
6966 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6967 case glslang::EOpSubgroupQuadSwapHorizontal:
6968 case glslang::EOpSubgroupQuadSwapVertical:
6969 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6970 default: assert(0 && "Unhandled subgroup operation!");
6971 }
6972
John Kessenich149afc32018-08-14 13:31:43 -06006973 // get the right Group Operation
6974 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006975 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006976 default:
6977 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006978 case glslang::EOpSubgroupBallotBitCount:
6979 case glslang::EOpSubgroupAdd:
6980 case glslang::EOpSubgroupMul:
6981 case glslang::EOpSubgroupMin:
6982 case glslang::EOpSubgroupMax:
6983 case glslang::EOpSubgroupAnd:
6984 case glslang::EOpSubgroupOr:
6985 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006986 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006987 break;
6988 case glslang::EOpSubgroupBallotInclusiveBitCount:
6989 case glslang::EOpSubgroupInclusiveAdd:
6990 case glslang::EOpSubgroupInclusiveMul:
6991 case glslang::EOpSubgroupInclusiveMin:
6992 case glslang::EOpSubgroupInclusiveMax:
6993 case glslang::EOpSubgroupInclusiveAnd:
6994 case glslang::EOpSubgroupInclusiveOr:
6995 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006996 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006997 break;
6998 case glslang::EOpSubgroupBallotExclusiveBitCount:
6999 case glslang::EOpSubgroupExclusiveAdd:
7000 case glslang::EOpSubgroupExclusiveMul:
7001 case glslang::EOpSubgroupExclusiveMin:
7002 case glslang::EOpSubgroupExclusiveMax:
7003 case glslang::EOpSubgroupExclusiveAnd:
7004 case glslang::EOpSubgroupExclusiveOr:
7005 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007006 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007007 break;
7008 case glslang::EOpSubgroupClusteredAdd:
7009 case glslang::EOpSubgroupClusteredMul:
7010 case glslang::EOpSubgroupClusteredMin:
7011 case glslang::EOpSubgroupClusteredMax:
7012 case glslang::EOpSubgroupClusteredAnd:
7013 case glslang::EOpSubgroupClusteredOr:
7014 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007015 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007016 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007017 case glslang::EOpSubgroupPartitionedAdd:
7018 case glslang::EOpSubgroupPartitionedMul:
7019 case glslang::EOpSubgroupPartitionedMin:
7020 case glslang::EOpSubgroupPartitionedMax:
7021 case glslang::EOpSubgroupPartitionedAnd:
7022 case glslang::EOpSubgroupPartitionedOr:
7023 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007024 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007025 break;
7026 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7027 case glslang::EOpSubgroupPartitionedInclusiveMul:
7028 case glslang::EOpSubgroupPartitionedInclusiveMin:
7029 case glslang::EOpSubgroupPartitionedInclusiveMax:
7030 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7031 case glslang::EOpSubgroupPartitionedInclusiveOr:
7032 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007033 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007034 break;
7035 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7036 case glslang::EOpSubgroupPartitionedExclusiveMul:
7037 case glslang::EOpSubgroupPartitionedExclusiveMin:
7038 case glslang::EOpSubgroupPartitionedExclusiveMax:
7039 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7040 case glslang::EOpSubgroupPartitionedExclusiveOr:
7041 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007042 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007043 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007044 }
7045
John Kessenich149afc32018-08-14 13:31:43 -06007046 // build the instruction
7047 std::vector<spv::IdImmediate> spvGroupOperands;
7048
7049 // Every operation begins with the Execution Scope operand.
7050 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7051 spvGroupOperands.push_back(executionScope);
7052
7053 // Next, for all operations that use a Group Operation, push that as an operand.
7054 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007055 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007056 spvGroupOperands.push_back(groupOperand);
7057 }
7058
John Kessenich66011cb2018-03-06 16:12:04 -07007059 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007060 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7061 spv::IdImmediate operand = { true, *opIt };
7062 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007063 }
7064
7065 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007066 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007067 switch (op) {
7068 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007069 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7070 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7071 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7072 }
7073 if (directionId != spv::NoResult) {
7074 spv::IdImmediate direction = { true, directionId };
7075 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007076 }
7077
7078 return builder.createOp(opCode, typeId, spvGroupOperands);
7079}
7080
John Kessenich5e4b1242015-08-06 22:53:06 -06007081spv::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 -06007082{
John Kessenich66011cb2018-03-06 16:12:04 -07007083 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7084 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007085
John Kessenich140f3df2015-06-26 16:58:36 -06007086 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007087 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007088 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007089 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007090 spv::Id typeId0 = 0;
7091 if (consumedOperands > 0)
7092 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007093 spv::Id typeId1 = 0;
7094 if (consumedOperands > 1)
7095 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007096 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007097
7098 switch (op) {
7099 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007100 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007101 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007102 else if (isUnsigned)
7103 libCall = spv::GLSLstd450UMin;
7104 else
7105 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007106 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007107 break;
7108 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007109 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007110 break;
7111 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007112 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007113 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007114 else if (isUnsigned)
7115 libCall = spv::GLSLstd450UMax;
7116 else
7117 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007118 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007119 break;
7120 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007121 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007122 break;
7123 case glslang::EOpDot:
7124 opCode = spv::OpDot;
7125 break;
7126 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007127 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007128 break;
7129
7130 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007131 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007132 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007133 else if (isUnsigned)
7134 libCall = spv::GLSLstd450UClamp;
7135 else
7136 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007137 builder.promoteScalar(precision, operands.front(), operands[1]);
7138 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007139 break;
7140 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007141 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7142 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007143 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007144 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007145 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007146 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007147 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007148 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007149 break;
7150 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007151 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007152 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007153 break;
7154 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007155 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007156 builder.promoteScalar(precision, operands[0], operands[2]);
7157 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007158 break;
7159
7160 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007161 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007162 break;
7163 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007164 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007165 break;
7166 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007167 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007168 break;
7169 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007170 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007171 break;
7172 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007173 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007174 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007175#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007176 case glslang::EOpInterpolateAtSample:
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::GLSLstd450InterpolateAtSample;
7180 break;
7181 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007182 if (typeProxy == glslang::EbtFloat16)
7183 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007184 libCall = spv::GLSLstd450InterpolateAtOffset;
7185 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007186 case glslang::EOpAddCarry:
7187 opCode = spv::OpIAddCarry;
7188 typeId = builder.makeStructResultType(typeId0, typeId0);
7189 consumedOperands = 2;
7190 break;
7191 case glslang::EOpSubBorrow:
7192 opCode = spv::OpISubBorrow;
7193 typeId = builder.makeStructResultType(typeId0, typeId0);
7194 consumedOperands = 2;
7195 break;
7196 case glslang::EOpUMulExtended:
7197 opCode = spv::OpUMulExtended;
7198 typeId = builder.makeStructResultType(typeId0, typeId0);
7199 consumedOperands = 2;
7200 break;
7201 case glslang::EOpIMulExtended:
7202 opCode = spv::OpSMulExtended;
7203 typeId = builder.makeStructResultType(typeId0, typeId0);
7204 consumedOperands = 2;
7205 break;
7206 case glslang::EOpBitfieldExtract:
7207 if (isUnsigned)
7208 opCode = spv::OpBitFieldUExtract;
7209 else
7210 opCode = spv::OpBitFieldSExtract;
7211 break;
7212 case glslang::EOpBitfieldInsert:
7213 opCode = spv::OpBitFieldInsert;
7214 break;
7215
7216 case glslang::EOpFma:
7217 libCall = spv::GLSLstd450Fma;
7218 break;
7219 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007220 {
7221 libCall = spv::GLSLstd450FrexpStruct;
7222 assert(builder.isPointerType(typeId1));
7223 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007224 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007225 if (width == 16)
7226 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7227 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007228 if (builder.getNumComponents(operands[0]) == 1)
7229 frexpIntType = builder.makeIntegerType(width, true);
7230 else
7231 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7232 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7233 consumedOperands = 1;
7234 }
John Kessenich55e7d112015-11-15 21:33:39 -07007235 break;
7236 case glslang::EOpLdexp:
7237 libCall = spv::GLSLstd450Ldexp;
7238 break;
7239
Rex Xu574ab042016-04-14 16:53:07 +08007240 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007241 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007242
John Kessenich66011cb2018-03-06 16:12:04 -07007243 case glslang::EOpSubgroupBroadcast:
7244 case glslang::EOpSubgroupBallotBitExtract:
7245 case glslang::EOpSubgroupShuffle:
7246 case glslang::EOpSubgroupShuffleXor:
7247 case glslang::EOpSubgroupShuffleUp:
7248 case glslang::EOpSubgroupShuffleDown:
7249 case glslang::EOpSubgroupClusteredAdd:
7250 case glslang::EOpSubgroupClusteredMul:
7251 case glslang::EOpSubgroupClusteredMin:
7252 case glslang::EOpSubgroupClusteredMax:
7253 case glslang::EOpSubgroupClusteredAnd:
7254 case glslang::EOpSubgroupClusteredOr:
7255 case glslang::EOpSubgroupClusteredXor:
7256 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007257 case glslang::EOpSubgroupPartitionedAdd:
7258 case glslang::EOpSubgroupPartitionedMul:
7259 case glslang::EOpSubgroupPartitionedMin:
7260 case glslang::EOpSubgroupPartitionedMax:
7261 case glslang::EOpSubgroupPartitionedAnd:
7262 case glslang::EOpSubgroupPartitionedOr:
7263 case glslang::EOpSubgroupPartitionedXor:
7264 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7265 case glslang::EOpSubgroupPartitionedInclusiveMul:
7266 case glslang::EOpSubgroupPartitionedInclusiveMin:
7267 case glslang::EOpSubgroupPartitionedInclusiveMax:
7268 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7269 case glslang::EOpSubgroupPartitionedInclusiveOr:
7270 case glslang::EOpSubgroupPartitionedInclusiveXor:
7271 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7272 case glslang::EOpSubgroupPartitionedExclusiveMul:
7273 case glslang::EOpSubgroupPartitionedExclusiveMin:
7274 case glslang::EOpSubgroupPartitionedExclusiveMax:
7275 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7276 case glslang::EOpSubgroupPartitionedExclusiveOr:
7277 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007278 return createSubgroupOperation(op, typeId, operands, typeProxy);
7279
Rex Xu9d93a232016-05-05 12:30:44 +08007280 case glslang::EOpSwizzleInvocations:
7281 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7282 libCall = spv::SwizzleInvocationsAMD;
7283 break;
7284 case glslang::EOpSwizzleInvocationsMasked:
7285 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7286 libCall = spv::SwizzleInvocationsMaskedAMD;
7287 break;
7288 case glslang::EOpWriteInvocation:
7289 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7290 libCall = spv::WriteInvocationAMD;
7291 break;
7292
7293 case glslang::EOpMin3:
7294 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7295 if (isFloat)
7296 libCall = spv::FMin3AMD;
7297 else {
7298 if (isUnsigned)
7299 libCall = spv::UMin3AMD;
7300 else
7301 libCall = spv::SMin3AMD;
7302 }
7303 break;
7304 case glslang::EOpMax3:
7305 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7306 if (isFloat)
7307 libCall = spv::FMax3AMD;
7308 else {
7309 if (isUnsigned)
7310 libCall = spv::UMax3AMD;
7311 else
7312 libCall = spv::SMax3AMD;
7313 }
7314 break;
7315 case glslang::EOpMid3:
7316 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7317 if (isFloat)
7318 libCall = spv::FMid3AMD;
7319 else {
7320 if (isUnsigned)
7321 libCall = spv::UMid3AMD;
7322 else
7323 libCall = spv::SMid3AMD;
7324 }
7325 break;
7326
7327 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007328 if (typeProxy == glslang::EbtFloat16)
7329 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007330 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7331 libCall = spv::InterpolateAtVertexAMD;
7332 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007333 case glslang::EOpBarrier:
7334 {
7335 // This is for the extended controlBarrier function, with four operands.
7336 // The unextended barrier() goes through createNoArgOperation.
7337 assert(operands.size() == 4);
7338 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7339 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7340 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7341 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007342 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7343 spv::MemorySemanticsMakeVisibleKHRMask |
7344 spv::MemorySemanticsOutputMemoryKHRMask |
7345 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007346 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7347 }
7348 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7349 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7350 }
7351 return 0;
7352 }
7353 break;
7354 case glslang::EOpMemoryBarrier:
7355 {
7356 // This is for the extended memoryBarrier function, with three operands.
7357 // The unextended memoryBarrier() goes through createNoArgOperation.
7358 assert(operands.size() == 3);
7359 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7360 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7361 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007362 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7363 spv::MemorySemanticsMakeVisibleKHRMask |
7364 spv::MemorySemanticsOutputMemoryKHRMask |
7365 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007366 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7367 }
7368 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7369 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7370 }
7371 return 0;
7372 }
7373 break;
Chao Chen3c366992018-09-19 11:41:59 -07007374
Chao Chenb50c02e2018-09-19 11:42:24 -07007375 case glslang::EOpReportIntersectionNV:
7376 {
7377 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007378 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007379 }
7380 break;
7381 case glslang::EOpTraceNV:
7382 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007383 builder.createNoResultOp(spv::OpTraceNV, operands);
7384 return 0;
7385 }
7386 break;
7387 case glslang::EOpExecuteCallableNV:
7388 {
7389 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007390 return 0;
7391 }
7392 break;
Chao Chen3c366992018-09-19 11:41:59 -07007393 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7394 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7395 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007396 case glslang::EOpCooperativeMatrixMulAdd:
7397 opCode = spv::OpCooperativeMatrixMulAddNV;
7398 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007399#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007400 default:
7401 return 0;
7402 }
7403
7404 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007405 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007406 // Use an extended instruction from the standard library.
7407 // Construct the call arguments, without modifying the original operands vector.
7408 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7409 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007410 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007411 } else if (opCode == spv::OpDot && !isFloat) {
7412 // int dot(int, int)
7413 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7414 const int componentCount = builder.getNumComponents(operands[0]);
7415 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7416 builder.setPrecision(mulOp, precision);
7417 id = builder.createCompositeExtract(mulOp, typeId, 0);
7418 for (int i = 1; i < componentCount; ++i) {
7419 builder.setPrecision(id, precision);
7420 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7421 }
John Kessenich2359bd02015-12-06 19:29:11 -07007422 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007423 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007424 case 0:
7425 // should all be handled by visitAggregate and createNoArgOperation
7426 assert(0);
7427 return 0;
7428 case 1:
7429 // should all be handled by createUnaryOperation
7430 assert(0);
7431 return 0;
7432 case 2:
7433 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7434 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007435 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007436 // anything 3 or over doesn't have l-value operands, so all should be consumed
7437 assert(consumedOperands == operands.size());
7438 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007439 break;
7440 }
7441 }
7442
John Kessenichb9197c82019-08-11 07:41:45 -06007443#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007444 // Decode the return types that were structures
7445 switch (op) {
7446 case glslang::EOpAddCarry:
7447 case glslang::EOpSubBorrow:
7448 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7449 id = builder.createCompositeExtract(id, typeId0, 0);
7450 break;
7451 case glslang::EOpUMulExtended:
7452 case glslang::EOpIMulExtended:
7453 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7454 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7455 break;
7456 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007457 {
7458 assert(operands.size() == 2);
7459 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7460 // "exp" is floating-point type (from HLSL intrinsic)
7461 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7462 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7463 builder.createStore(member1, operands[1]);
7464 } else
7465 // "exp" is integer type (from GLSL built-in function)
7466 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7467 id = builder.createCompositeExtract(id, typeId0, 0);
7468 }
John Kessenich55e7d112015-11-15 21:33:39 -07007469 break;
7470 default:
7471 break;
7472 }
John Kessenichb9197c82019-08-11 07:41:45 -06007473#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007474
John Kessenich32cfd492016-02-02 12:37:46 -07007475 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007476}
7477
Rex Xu9d93a232016-05-05 12:30:44 +08007478// Intrinsics with no arguments (or no return value, and no precision).
7479spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007480{
John Kessenich155d3512019-08-08 23:29:20 -06007481#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05007482 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7483 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007484
7485 switch (op) {
7486 case glslang::EOpEmitVertex:
7487 builder.createNoResultOp(spv::OpEmitVertex);
7488 return 0;
7489 case glslang::EOpEndPrimitive:
7490 builder.createNoResultOp(spv::OpEndPrimitive);
7491 return 0;
7492 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007493 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007494 if (glslangIntermediate->usingVulkanMemoryModel()) {
7495 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7496 spv::MemorySemanticsOutputMemoryKHRMask |
7497 spv::MemorySemanticsAcquireReleaseMask);
7498 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7499 } else {
7500 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7501 }
John Kessenich82979362017-12-11 04:02:24 -07007502 } else {
7503 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7504 spv::MemorySemanticsWorkgroupMemoryMask |
7505 spv::MemorySemanticsAcquireReleaseMask);
7506 }
John Kessenich140f3df2015-06-26 16:58:36 -06007507 return 0;
7508 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007509 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7510 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007511 return 0;
7512 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007513 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7514 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007515 return 0;
7516 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007517 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7518 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007519 return 0;
7520 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007521 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7522 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007523 return 0;
7524 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007525 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7526 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007527 return 0;
7528 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007529 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7530 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007531 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007532 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007533 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007534 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007535 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007536 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007537 case glslang::EOpDeviceMemoryBarrier:
7538 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7539 spv::MemorySemanticsImageMemoryMask |
7540 spv::MemorySemanticsAcquireReleaseMask);
7541 return 0;
7542 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7543 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7544 spv::MemorySemanticsImageMemoryMask |
7545 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007546 return 0;
7547 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007548 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7549 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007550 return 0;
7551 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007552 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7553 spv::MemorySemanticsWorkgroupMemoryMask |
7554 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007555 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007556 case glslang::EOpSubgroupBarrier:
7557 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7558 spv::MemorySemanticsAcquireReleaseMask);
7559 return spv::NoResult;
7560 case glslang::EOpSubgroupMemoryBarrier:
7561 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7562 spv::MemorySemanticsAcquireReleaseMask);
7563 return spv::NoResult;
7564 case glslang::EOpSubgroupMemoryBarrierBuffer:
7565 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7566 spv::MemorySemanticsAcquireReleaseMask);
7567 return spv::NoResult;
7568 case glslang::EOpSubgroupMemoryBarrierImage:
7569 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7570 spv::MemorySemanticsAcquireReleaseMask);
7571 return spv::NoResult;
7572 case glslang::EOpSubgroupMemoryBarrierShared:
7573 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7574 spv::MemorySemanticsAcquireReleaseMask);
7575 return spv::NoResult;
7576 case glslang::EOpSubgroupElect: {
7577 std::vector<spv::Id> operands;
7578 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7579 }
Rex Xu9d93a232016-05-05 12:30:44 +08007580 case glslang::EOpTime:
7581 {
7582 std::vector<spv::Id> args; // Dummy arguments
7583 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7584 return builder.setPrecision(id, precision);
7585 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007586 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007587 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007588 return 0;
7589 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007590 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007591 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007592
7593 case glslang::EOpBeginInvocationInterlock:
7594 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7595 return 0;
7596 case glslang::EOpEndInvocationInterlock:
7597 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7598 return 0;
7599
Jeff Bolzba6170b2019-07-01 09:23:23 -05007600 case glslang::EOpIsHelperInvocation:
7601 {
7602 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007603 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7604 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7605 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007606 }
7607
amhagan91fb0092019-07-10 21:14:38 -04007608 case glslang::EOpReadClockSubgroupKHR: {
7609 std::vector<spv::Id> args;
7610 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7611 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7612 builder.addCapability(spv::CapabilityShaderClockKHR);
7613 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7614 }
7615
7616 case glslang::EOpReadClockDeviceKHR: {
7617 std::vector<spv::Id> args;
7618 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7619 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7620 builder.addCapability(spv::CapabilityShaderClockKHR);
7621 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7622 }
John Kessenich140f3df2015-06-26 16:58:36 -06007623 default:
John Kessenich155d3512019-08-08 23:29:20 -06007624 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007625 }
John Kessenich155d3512019-08-08 23:29:20 -06007626#endif
7627
7628 logger->missingFunctionality("unknown operation with no arguments");
7629
7630 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007631}
7632
7633spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7634{
John Kessenich2f273362015-07-18 22:34:27 -06007635 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007636 spv::Id id;
7637 if (symbolValues.end() != iter) {
7638 id = iter->second;
7639 return id;
7640 }
7641
7642 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007643 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7644 auto forcedType = getForcedType(builtIn, symbol->getType());
7645 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007646 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007647 if (forcedType.second != spv::NoType)
7648 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007649
Rex Xuc884b4a2016-06-29 15:03:44 +08007650 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007651 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7652 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7653 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007654#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007655 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007656 if (symbol->getQualifier().hasComponent())
7657 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7658 if (symbol->getQualifier().hasIndex())
7659 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007660#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007661 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007662 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007663 // atomic counters use this:
7664 if (symbol->getQualifier().hasOffset())
7665 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007666 }
7667
scygan2c864272016-05-18 18:09:17 +02007668 if (symbol->getQualifier().hasLocation())
7669 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007670 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007671 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007672 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007673 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007674 }
John Kessenich140f3df2015-06-26 16:58:36 -06007675 if (symbol->getQualifier().hasSet())
7676 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007677 else if (IsDescriptorResource(symbol->getType())) {
7678 // default to 0
7679 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7680 }
John Kessenich140f3df2015-06-26 16:58:36 -06007681 if (symbol->getQualifier().hasBinding())
7682 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007683 else if (IsDescriptorResource(symbol->getType())) {
7684 // default to 0
7685 builder.addDecoration(id, spv::DecorationBinding, 0);
7686 }
John Kessenich6c292d32016-02-15 20:58:50 -07007687 if (symbol->getQualifier().hasAttachment())
7688 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007689 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007690 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007691 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007692 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007693 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7694 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7695 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7696 }
7697 if (symbol->getQualifier().hasXfbOffset())
7698 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007699 }
7700
John Kessenichb9197c82019-08-11 07:41:45 -06007701 // add built-in variable decoration
7702 if (builtIn != spv::BuiltInMax) {
7703 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7704 }
7705
7706#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007707 if (symbol->getType().isImage()) {
7708 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007709 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007710 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007711 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007712 }
7713
John Kessenich5611c6d2018-04-05 11:25:02 -06007714 // nonuniform
7715 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7716
chaoc0ad6a4e2016-12-19 16:29:34 -08007717 if (builtIn == spv::BuiltInSampleMask) {
7718 spv::Decoration decoration;
7719 // GL_NV_sample_mask_override_coverage extension
7720 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007721 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007722 else
7723 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007724 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007725 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007726 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007727 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7728 }
7729 }
chaoc771d89f2017-01-13 01:10:53 -08007730 else if (builtIn == spv::BuiltInLayer) {
7731 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007732 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007733 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007734 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7735 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7736 }
John Kessenichb41bff62017-08-11 13:07:17 -06007737 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007738 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7739 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007740 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7741 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7742 }
7743 }
7744
chaoc6e5acae2016-12-20 13:28:52 -08007745 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007746 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007747 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007748 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7749 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007750 if (symbol->getQualifier().pervertexNV) {
7751 builder.addDecoration(id, spv::DecorationPerVertexNV);
7752 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7753 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7754 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007755
John Kessenich5d610ee2018-03-07 18:05:55 -07007756 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7757 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7758 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7759 symbol->getType().getQualifier().semanticName);
7760 }
7761
John Kessenich7015bd62019-08-01 03:28:08 -06007762 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007763 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7764 }
John Kessenichb9197c82019-08-11 07:41:45 -06007765#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007766
John Kessenich140f3df2015-06-26 16:58:36 -06007767 return id;
7768}
7769
John Kessenicha28f7a72019-08-06 07:00:58 -06007770#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007771// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7772void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7773{
7774 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007775 if (qualifier.perPrimitiveNV) {
7776 // Need to add capability/extension for fragment shader.
7777 // Mesh shader already adds this by default.
7778 if (glslangIntermediate->getStage() == EShLangFragment) {
7779 builder.addCapability(spv::CapabilityMeshShadingNV);
7780 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7781 }
Chao Chen3c366992018-09-19 11:41:59 -07007782 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007783 }
Chao Chen3c366992018-09-19 11:41:59 -07007784 if (qualifier.perViewNV)
7785 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7786 if (qualifier.perTaskNV)
7787 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7788 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007789 if (qualifier.perPrimitiveNV) {
7790 // Need to add capability/extension for fragment shader.
7791 // Mesh shader already adds this by default.
7792 if (glslangIntermediate->getStage() == EShLangFragment) {
7793 builder.addCapability(spv::CapabilityMeshShadingNV);
7794 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7795 }
Chao Chen3c366992018-09-19 11:41:59 -07007796 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007797 }
Chao Chen3c366992018-09-19 11:41:59 -07007798 if (qualifier.perViewNV)
7799 builder.addDecoration(id, spv::DecorationPerViewNV);
7800 if (qualifier.perTaskNV)
7801 builder.addDecoration(id, spv::DecorationPerTaskNV);
7802 }
7803}
7804#endif
7805
John Kessenich55e7d112015-11-15 21:33:39 -07007806// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007807// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007808//
7809// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7810//
7811// Recursively walk the nodes. The nodes form a tree whose leaves are
7812// regular constants, which themselves are trees that createSpvConstant()
7813// recursively walks. So, this function walks the "top" of the tree:
7814// - emit specialization constant-building instructions for specConstant
7815// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007816spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007817{
John Kessenich7cc0e282016-03-20 00:46:02 -06007818 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007819
qining4f4bb812016-04-03 23:55:17 -04007820 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007821 if (! node.getQualifier().specConstant) {
7822 // hand off to the non-spec-constant path
7823 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7824 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007825 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007826 nextConst, false);
7827 }
7828
7829 // We now know we have a specialization constant to build
7830
John Kessenichd94c0032016-05-30 19:29:40 -06007831 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007832 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7833 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7834 std::vector<spv::Id> dimConstId;
7835 for (int dim = 0; dim < 3; ++dim) {
7836 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7837 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007838 if (specConst) {
7839 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7840 glslangIntermediate->getLocalSizeSpecId(dim));
7841 }
qining4f4bb812016-04-03 23:55:17 -04007842 }
7843 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7844 }
7845
7846 // An AST node labelled as specialization constant should be a symbol node.
7847 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7848 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007849 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007850 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007851 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7852 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7853 // will set the builder into spec constant op instruction generating mode.
7854 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007855 result = accessChainLoad(sub_tree->getType());
7856 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007857 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007858 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007859 } else {
7860 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007861 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007862 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007863 builder.addName(result, sn->getName().c_str());
7864 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007865 }
qining4f4bb812016-04-03 23:55:17 -04007866
7867 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7868 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007869 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007870 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007871}
7872
John Kessenich140f3df2015-06-26 16:58:36 -06007873// Use 'consts' as the flattened glslang source of scalar constants to recursively
7874// build the aggregate SPIR-V constant.
7875//
7876// If there are not enough elements present in 'consts', 0 will be substituted;
7877// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7878//
qining08408382016-03-21 09:51:37 -04007879spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007880{
7881 // vector of constants for SPIR-V
7882 std::vector<spv::Id> spvConsts;
7883
7884 // Type is used for struct and array constants
7885 spv::Id typeId = convertGlslangToSpvType(glslangType);
7886
7887 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007888 glslang::TType elementType(glslangType, 0);
7889 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007890 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007891 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007892 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007893 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007894 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007895 } else if (glslangType.isCoopMat()) {
7896 glslang::TType componentType(glslangType.getBasicType());
7897 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007898 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007899 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7900 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007901 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007902 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007903 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7904 bool zero = nextConst >= consts.size();
7905 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007906 case glslang::EbtInt:
7907 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7908 break;
7909 case glslang::EbtUint:
7910 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7911 break;
7912 case glslang::EbtFloat:
7913 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7914 break;
7915 case glslang::EbtBool:
7916 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7917 break;
7918#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007919 case glslang::EbtInt8:
7920 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7921 break;
7922 case glslang::EbtUint8:
7923 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7924 break;
7925 case glslang::EbtInt16:
7926 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7927 break;
7928 case glslang::EbtUint16:
7929 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7930 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007931 case glslang::EbtInt64:
7932 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7933 break;
7934 case glslang::EbtUint64:
7935 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7936 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007937 case glslang::EbtDouble:
7938 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7939 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007940 case glslang::EbtFloat16:
7941 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7942 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007943#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007944 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007945 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007946 break;
7947 }
7948 ++nextConst;
7949 }
7950 } else {
7951 // we have a non-aggregate (scalar) constant
7952 bool zero = nextConst >= consts.size();
7953 spv::Id scalar = 0;
7954 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007955 case glslang::EbtInt:
7956 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7957 break;
7958 case glslang::EbtUint:
7959 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7960 break;
7961 case glslang::EbtFloat:
7962 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7963 break;
7964 case glslang::EbtBool:
7965 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7966 break;
7967#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007968 case glslang::EbtInt8:
7969 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7970 break;
7971 case glslang::EbtUint8:
7972 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7973 break;
7974 case glslang::EbtInt16:
7975 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7976 break;
7977 case glslang::EbtUint16:
7978 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7979 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007980 case glslang::EbtInt64:
7981 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7982 break;
7983 case glslang::EbtUint64:
7984 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7985 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007986 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007987 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007988 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007989 case glslang::EbtFloat16:
7990 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7991 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007992 case glslang::EbtReference:
7993 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7994 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7995 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007996#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007997 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007998 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007999 break;
8000 }
8001 ++nextConst;
8002 return scalar;
8003 }
8004
8005 return builder.makeCompositeConstant(typeId, spvConsts);
8006}
8007
John Kessenich7c1aa102015-10-15 13:29:11 -06008008// Return true if the node is a constant or symbol whose reading has no
8009// non-trivial observable cost or effect.
8010bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8011{
8012 // don't know what this is
8013 if (node == nullptr)
8014 return false;
8015
8016 // a constant is safe
8017 if (node->getAsConstantUnion() != nullptr)
8018 return true;
8019
8020 // not a symbol means non-trivial
8021 if (node->getAsSymbolNode() == nullptr)
8022 return false;
8023
8024 // a symbol, depends on what's being read
8025 switch (node->getType().getQualifier().storage) {
8026 case glslang::EvqTemporary:
8027 case glslang::EvqGlobal:
8028 case glslang::EvqIn:
8029 case glslang::EvqInOut:
8030 case glslang::EvqConst:
8031 case glslang::EvqConstReadOnly:
8032 case glslang::EvqUniform:
8033 return true;
8034 default:
8035 return false;
8036 }
qining25262b32016-05-06 17:25:16 -04008037}
John Kessenich7c1aa102015-10-15 13:29:11 -06008038
8039// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008040// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008041// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008042// Return true if trivial.
8043bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8044{
8045 if (node == nullptr)
8046 return false;
8047
John Kessenich84cc15f2017-05-24 16:44:47 -06008048 // count non scalars as trivial, as well as anything coming from HLSL
8049 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008050 return true;
8051
John Kessenich7c1aa102015-10-15 13:29:11 -06008052 // symbols and constants are trivial
8053 if (isTrivialLeaf(node))
8054 return true;
8055
8056 // otherwise, it needs to be a simple operation or one or two leaf nodes
8057
8058 // not a simple operation
8059 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8060 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8061 if (binaryNode == nullptr && unaryNode == nullptr)
8062 return false;
8063
8064 // not on leaf nodes
8065 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8066 return false;
8067
8068 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8069 return false;
8070 }
8071
8072 switch (node->getAsOperator()->getOp()) {
8073 case glslang::EOpLogicalNot:
8074 case glslang::EOpConvIntToBool:
8075 case glslang::EOpConvUintToBool:
8076 case glslang::EOpConvFloatToBool:
8077 case glslang::EOpConvDoubleToBool:
8078 case glslang::EOpEqual:
8079 case glslang::EOpNotEqual:
8080 case glslang::EOpLessThan:
8081 case glslang::EOpGreaterThan:
8082 case glslang::EOpLessThanEqual:
8083 case glslang::EOpGreaterThanEqual:
8084 case glslang::EOpIndexDirect:
8085 case glslang::EOpIndexDirectStruct:
8086 case glslang::EOpLogicalXor:
8087 case glslang::EOpAny:
8088 case glslang::EOpAll:
8089 return true;
8090 default:
8091 return false;
8092 }
8093}
8094
8095// Emit short-circuiting code, where 'right' is never evaluated unless
8096// the left side is true (for &&) or false (for ||).
8097spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8098{
8099 spv::Id boolTypeId = builder.makeBoolType();
8100
8101 // emit left operand
8102 builder.clearAccessChain();
8103 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008104 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008105
8106 // Operands to accumulate OpPhi operands
8107 std::vector<spv::Id> phiOperands;
8108 // accumulate left operand's phi information
8109 phiOperands.push_back(leftId);
8110 phiOperands.push_back(builder.getBuildPoint()->getId());
8111
8112 // Make the two kinds of operation symmetric with a "!"
8113 // || => emit "if (! left) result = right"
8114 // && => emit "if ( left) result = right"
8115 //
8116 // TODO: this runtime "not" for || could be avoided by adding functionality
8117 // to 'builder' to have an "else" without an "then"
8118 if (op == glslang::EOpLogicalOr)
8119 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8120
8121 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008122 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008123
8124 // emit right operand as the "then" part of the "if"
8125 builder.clearAccessChain();
8126 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008127 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008128
8129 // accumulate left operand's phi information
8130 phiOperands.push_back(rightId);
8131 phiOperands.push_back(builder.getBuildPoint()->getId());
8132
8133 // finish the "if"
8134 ifBuilder.makeEndIf();
8135
8136 // phi together the two results
8137 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8138}
8139
John Kessenicha28f7a72019-08-06 07:00:58 -06008140#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008141// Return type Id of the imported set of extended instructions corresponds to the name.
8142// Import this set if it has not been imported yet.
8143spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8144{
8145 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8146 return extBuiltinMap[name];
8147 else {
Rex Xu51596642016-09-21 18:56:12 +08008148 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008149 spv::Id extBuiltins = builder.import(name);
8150 extBuiltinMap[name] = extBuiltins;
8151 return extBuiltins;
8152 }
8153}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008154#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008155
John Kessenich140f3df2015-06-26 16:58:36 -06008156}; // end anonymous namespace
8157
8158namespace glslang {
8159
John Kessenich68d78fd2015-07-12 19:28:10 -06008160void GetSpirvVersion(std::string& version)
8161{
John Kessenich9e55f632015-07-15 10:03:39 -06008162 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008163 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008164 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008165 version = buf;
8166}
8167
John Kessenicha372a3e2017-11-02 22:32:14 -06008168// For low-order part of the generator's magic number. Bump up
8169// when there is a change in the style (e.g., if SSA form changes,
8170// or a different instruction sequence to do something gets used).
8171int GetSpirvGeneratorVersion()
8172{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008173 // return 1; // start
8174 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008175 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008176 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008177 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008178 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8179 // versions 4 and 6 each generate OpArrayLength as it has long been done
8180 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008181}
8182
John Kessenich140f3df2015-06-26 16:58:36 -06008183// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008184void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008185{
8186 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008187 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008188 if (out.fail())
8189 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008190 for (int i = 0; i < (int)spirv.size(); ++i) {
8191 unsigned int word = spirv[i];
8192 out.write((const char*)&word, 4);
8193 }
8194 out.close();
8195}
8196
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008197// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008198void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008199{
John Kessenich155d3512019-08-08 23:29:20 -06008200#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008201 std::ofstream out;
8202 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008203 if (out.fail())
8204 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008205 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008206 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008207 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008208 if (varName != nullptr) {
8209 out << "\t #pragma once" << std::endl;
8210 out << "const uint32_t " << varName << "[] = {" << std::endl;
8211 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008212 const int WORDS_PER_LINE = 8;
8213 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8214 out << "\t";
8215 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8216 const unsigned int word = spirv[i + j];
8217 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8218 if (i + j + 1 < (int)spirv.size()) {
8219 out << ",";
8220 }
8221 }
8222 out << std::endl;
8223 }
Flavio15017db2017-02-15 14:29:33 -08008224 if (varName != nullptr) {
8225 out << "};";
8226 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008227 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008228#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008229}
8230
John Kessenich140f3df2015-06-26 16:58:36 -06008231//
8232// Set up the glslang traversal
8233//
John Kessenich4e11b612018-08-30 16:56:59 -06008234void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008235{
Lei Zhang17535f72016-05-04 15:55:59 -04008236 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008237 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008238}
8239
John Kessenich4e11b612018-08-30 16:56:59 -06008240void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008241 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008242{
John Kessenich140f3df2015-06-26 16:58:36 -06008243 TIntermNode* root = intermediate.getTreeRoot();
8244
8245 if (root == 0)
8246 return;
8247
John Kessenich4e11b612018-08-30 16:56:59 -06008248 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008249 if (options == nullptr)
8250 options = &defaultOptions;
8251
John Kessenich4e11b612018-08-30 16:56:59 -06008252 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008253
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008254 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008255 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008256 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008257 it.dumpSpv(spirv);
8258
GregFfb03a552018-03-29 11:49:14 -06008259#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008260 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8261 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008262 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8263 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008264 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008265 prelegalization = false;
8266 }
John Kessenich717c80a2018-08-23 15:17:10 -06008267
John Kessenich4e11b612018-08-30 16:56:59 -06008268 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008269 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008270
John Kessenich717c80a2018-08-23 15:17:10 -06008271 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008272 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008273
GregFcd1f1692017-09-21 18:40:22 -06008274#endif
8275
John Kessenich4e11b612018-08-30 16:56:59 -06008276 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008277}
8278
8279}; // end namespace glslang