blob: 2dd890811db87434577c380ce66b96ba1060f059 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
SJWf93f5f32020-05-05 07:27:56 -050046// enable spv::HasResultAndType
47#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040048#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040049
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040051#include "clspv/Option.h"
alan-baker86ce19c2020-08-05 13:09:19 -040052#include "clspv/PushConstant.h"
53#include "clspv/SpecConstant.h"
David Neto85082642018-03-24 06:55:20 -070054#include "clspv/spirv_c_strings.hpp"
55#include "clspv/spirv_glsl.hpp"
alan-baker86ce19c2020-08-05 13:09:19 -040056#include "clspv/spirv_reflection.hpp"
David Neto22f144c2017-06-12 14:26:21 -040057
David Neto4feb7a42017-10-06 17:29:42 -040058#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050059#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050060#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070061#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040062#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040063#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040064#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040065#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040066#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040067#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050068#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040069
David Neto22f144c2017-06-12 14:26:21 -040070#if defined(_MSC_VER)
71#pragma warning(pop)
72#endif
73
74using namespace llvm;
75using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050076using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050077using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040078using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040079
80namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040081
David Neto862b7d82018-06-14 18:48:37 -040082cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
83 cl::desc("Show resource variable creation"));
84
alan-baker5ed87542020-03-23 11:05:22 -040085cl::opt<bool>
86 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
87 cl::desc("Dump the IR at the start of SPIRVProducer"));
88
David Neto862b7d82018-06-14 18:48:37 -040089// These hacks exist to help transition code generation algorithms
90// without making huge noise in detailed test output.
91const bool Hack_generate_runtime_array_stride_early = true;
92
David Neto3fbb4072017-10-16 11:28:14 -040093// The value of 1/pi. This value is from MSDN
94// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
95const double kOneOverPi = 0.318309886183790671538;
96const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
97
alan-baker86ce19c2020-08-05 13:09:19 -040098// SPIRV Module Sections (per 2.4 of the SPIR-V spec)
SJW69939d52020-04-16 07:29:07 -050099// These are used to collect SPIRVInstructions by type on-the-fly.
100enum SPIRVSection {
101 kCapabilities,
102 kExtensions,
103 kImports,
104 kMemoryModel,
105 kEntryPoints,
106 kExecutionModes,
107
108 kDebug,
109 kAnnotations,
110
111 kTypes,
112 kConstants = kTypes,
113 kGlobalVariables,
114
115 kFunctions,
116
alan-baker86ce19c2020-08-05 13:09:19 -0400117 // This is not a section of the SPIR-V spec and should always immediately
118 // precede kSectionCount. It is a convenient place for the embedded
119 // reflection data.
120 kReflection,
SJW69939d52020-04-16 07:29:07 -0500121 kSectionCount
122};
123
SJW01901d92020-05-21 08:58:31 -0500124class SPIRVID {
125 uint32_t id;
126
127public:
128 SPIRVID(uint32_t _id = 0) : id(_id) {}
129 uint32_t get() const { return id; }
130 bool isValid() const { return id != 0; }
131 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500132 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500133};
SJWf93f5f32020-05-05 07:27:56 -0500134
SJW88ed5fe2020-05-11 12:40:57 -0500135enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400136
137struct SPIRVOperand {
SJW88ed5fe2020-05-11 12:40:57 -0500138 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
139 LiteralNum[0] = Num;
140 }
David Neto22f144c2017-06-12 14:26:21 -0400141 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
142 : Type(Ty), LiteralStr(Str) {}
143 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
144 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500145 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
146 auto sz = NumVec.size();
147 assert(sz >= 1 && sz <= 2);
148 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
149 LiteralNum[0] = NumVec[0];
150 if (sz == 2) {
151 LiteralNum[1] = NumVec[1];
152 }
153 }
David Neto22f144c2017-06-12 14:26:21 -0400154
James Price11010dc2019-12-19 13:53:09 -0500155 SPIRVOperandType getType() const { return Type; };
156 uint32_t getNumID() const { return LiteralNum[0]; };
157 std::string getLiteralStr() const { return LiteralStr; };
SJW88ed5fe2020-05-11 12:40:57 -0500158 const uint32_t *getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400159
David Neto87846742018-04-11 17:36:22 -0400160 uint32_t GetNumWords() const {
161 switch (Type) {
162 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500163 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400164 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500165 case LITERAL_DWORD:
166 return 2;
David Neto87846742018-04-11 17:36:22 -0400167 case LITERAL_STRING:
168 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400169 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400170 }
171 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
172 }
173
David Neto22f144c2017-06-12 14:26:21 -0400174private:
175 SPIRVOperandType Type;
176 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500177 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400178};
179
SJW88ed5fe2020-05-11 12:40:57 -0500180typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400181
David Neto22f144c2017-06-12 14:26:21 -0400182struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500183 // Primary constructor must have Opcode, initializes WordCount based on ResID.
184 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
185 : Opcode(static_cast<uint16_t>(Opc)) {
186 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400187 }
David Neto22f144c2017-06-12 14:26:21 -0400188
SJWf93f5f32020-05-05 07:27:56 -0500189 // Creates an instruction with an opcode and no result ID, and with the given
190 // operands. This calls primary constructor to initialize Opcode, WordCount.
191 // Takes ownership of the operands and clears |Ops|.
192 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
193 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500194 }
SJWf93f5f32020-05-05 07:27:56 -0500195 // Creates an instruction with an opcode and no result ID, and with the given
196 // operands. This calls primary constructor to initialize Opcode, WordCount.
197 // Takes ownership of the operands and clears |Ops|.
198 SPIRVInstruction(spv::Op Opc, SPIRVID ResID, SPIRVOperandVec &Ops)
199 : SPIRVInstruction(Opc, ResID) {
200 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500201 }
David Netoef5ba2b2019-12-20 08:35:54 -0500202
David Netoee2660d2018-06-28 16:31:29 -0400203 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400204 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500205 SPIRVID getResultID() const { return ResultID; }
206 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400207
208private:
SJW01901d92020-05-21 08:58:31 -0500209 void setResult(SPIRVID ResID = 0) {
210 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500211 ResultID = ResID;
212 }
213
214 void setOperands(SPIRVOperandVec &Ops) {
215 assert(Operands.empty());
216 Operands = std::move(Ops);
217 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500218 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500219 }
220 }
221
222private:
David Netoee2660d2018-06-28 16:31:29 -0400223 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400224 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500225 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500226 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400227};
228
229struct SPIRVProducerPass final : public ModulePass {
SJW01901d92020-05-21 08:58:31 -0500230 typedef DenseMap<Type *, SPIRVID> TypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400231 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500232 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500233 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500234 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
235 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500236 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500237 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500238 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400239 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500240 // - the SPIR-V instruction placeholder that will be replaced
241 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400242 DeferredInstVecType;
243 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
244 GlobalConstFuncMapType;
245
David Neto44795152017-07-13 15:45:28 -0400246 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500247 raw_pwrite_stream &out,
alan-baker00e7a582019-06-07 12:54:21 -0400248 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400249 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500250 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400251 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Neto0676e6f2017-07-11 18:47:44 -0400252 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500253 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
254 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
SJW01901d92020-05-21 08:58:31 -0500255 WorkgroupSizeVarID(0) {
256 addCapability(spv::CapabilityShader);
257 Ptr = this;
258 }
David Neto22f144c2017-06-12 14:26:21 -0400259
James Price11010dc2019-12-19 13:53:09 -0500260 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500261 }
262
David Neto22f144c2017-06-12 14:26:21 -0400263 void getAnalysisUsage(AnalysisUsage &AU) const override {
264 AU.addRequired<DominatorTreeWrapperPass>();
265 AU.addRequired<LoopInfoWrapperPass>();
266 }
267
268 virtual bool runOnModule(Module &module) override;
269
270 // output the SPIR-V header block
271 void outputHeader();
272
273 // patch the SPIR-V header block
274 void patchHeader();
275
SJW01901d92020-05-21 08:58:31 -0500276 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400277 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
278 TypeList &getTypeList() { return Types; };
David Neto22f144c2017-06-12 14:26:21 -0400279 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500280 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
281 return SPIRVSections[Section];
282 };
David Neto22f144c2017-06-12 14:26:21 -0400283 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
284 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
SJW806a5d82020-07-15 12:51:38 -0500285 SPIRVIDListType &getEntryPointInterfacesList() {
286 return EntryPointInterfacesList;
287 };
SJW01901d92020-05-21 08:58:31 -0500288 SPIRVID getOpExtInstImportID();
289 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500290
alan-baker5b86ed72019-02-15 08:26:50 -0500291 bool hasVariablePointersStorageBuffer() {
292 return HasVariablePointersStorageBuffer;
293 }
SJW01901d92020-05-21 08:58:31 -0500294 void setVariablePointersStorageBuffer() {
295 if (!HasVariablePointersStorageBuffer) {
296 addCapability(spv::CapabilityVariablePointersStorageBuffer);
297 HasVariablePointersStorageBuffer = true;
298 }
alan-baker5b86ed72019-02-15 08:26:50 -0500299 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400300 bool hasVariablePointers() { return HasVariablePointers; };
SJW01901d92020-05-21 08:58:31 -0500301 void setVariablePointers() {
302 if (!HasVariablePointers) {
303 addCapability(spv::CapabilityVariablePointers);
304 HasVariablePointers = true;
305 }
306 };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500307 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
308 return samplerMap;
309 }
David Neto22f144c2017-06-12 14:26:21 -0400310 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
311 return GlobalConstFuncTypeMap;
312 }
313 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
314 return GlobalConstArgumentSet;
315 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500316 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400317
SJW77b87ad2020-04-21 14:37:52 -0500318 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500319 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
320 // *not* be converted to a storage buffer, replace each such global variable
321 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500322 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400323 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
324 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500325 void FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400326 void FindTypePerGlobalVar(GlobalVariable &GV);
327 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500328 void FindTypesForSamplerMap();
329 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500330 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
331 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400332 void FindType(Type *Ty);
SJWf93f5f32020-05-05 07:27:56 -0500333
334 // Lookup or create Types, Constants.
335 // Returns SPIRVID once it has been created.
336 SPIRVID getSPIRVType(Type *Ty);
337 SPIRVID getSPIRVConstant(Constant *Cst);
SJW806a5d82020-07-15 12:51:38 -0500338 SPIRVID getSPIRVInt32Constant(uint32_t CstVal);
SJWf93f5f32020-05-05 07:27:56 -0500339 // Lookup SPIRVID of llvm::Value, may create Constant.
340 SPIRVID getSPIRVValue(Value *V);
341
SJW806a5d82020-07-15 12:51:38 -0500342 SPIRVID getSPIRVBuiltin(spv::BuiltIn BID, spv::Capability Cap);
343
David Neto19a1bad2017-08-25 15:01:41 -0400344 // Generates instructions for SPIR-V types corresponding to the LLVM types
345 // saved in the |Types| member. A type follows its subtypes. IDs are
346 // allocated sequentially starting with the current value of nextID, and
347 // with a type following its subtypes. Also updates nextID to just beyond
348 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500349 void GenerateSPIRVTypes();
SJW77b87ad2020-04-21 14:37:52 -0500350 void GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400351 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500352 void GenerateWorkgroupVars();
alan-baker86ce19c2020-08-05 13:09:19 -0400353 // Generate reflection instructions for resource variables associated with
David Neto862b7d82018-06-14 18:48:37 -0400354 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500355 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400356 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500357 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400358 void GenerateFuncPrologue(Function &F);
359 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400360 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400361 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
362 spv::Op GetSPIRVCastOpcode(Instruction &I);
363 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
SJW806a5d82020-07-15 12:51:38 -0500364 SPIRVID GenerateClspvInstruction(CallInst *Call,
365 const FunctionInfo &FuncInfo);
366 SPIRVID GenerateImageInstruction(CallInst *Call,
367 const FunctionInfo &FuncInfo);
368 SPIRVID GenerateSubgroupInstruction(CallInst *Call,
369 const FunctionInfo &FuncInfo);
370 SPIRVID GenerateInstructionFromCall(CallInst *Call);
David Neto22f144c2017-06-12 14:26:21 -0400371 void GenerateInstruction(Instruction &I);
372 void GenerateFuncEpilogue();
373 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500374 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400375 bool is4xi8vec(Type *Ty) const;
376 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400377 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400378 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400379 // Returns the GLSL extended instruction enum that the given function
380 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500381 glsl::ExtInst getExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400382 // Returns the GLSL extended instruction enum indirectly used by the given
383 // function. That is, to implement the given function, we use an extended
384 // instruction plus one more instruction. If none, then returns the 0 value,
385 // i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500386 glsl::ExtInst getIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400387 // Returns the single GLSL extended instruction used directly or
388 // indirectly by the given function call.
SJW61531372020-06-09 07:31:08 -0500389 glsl::ExtInst
390 getDirectOrIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto22f144c2017-06-12 14:26:21 -0400391 void WriteOneWord(uint32_t Word);
SJW88ed5fe2020-05-11 12:40:57 -0500392 void WriteResultID(const SPIRVInstruction &Inst);
393 void WriteWordCountAndOpcode(const SPIRVInstruction &Inst);
394 void WriteOperand(const SPIRVOperand &Op);
David Neto22f144c2017-06-12 14:26:21 -0400395 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500396 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400397
Alan Baker9bf93fb2018-08-28 16:59:26 -0400398 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500399 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400400
Alan Bakerfcda9482018-10-02 17:09:59 -0400401 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500402 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400403
alan-baker06cad652019-12-03 17:56:47 -0500404 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500405 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500406
Alan Bakerfcda9482018-10-02 17:09:59 -0400407 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
408 // uses the internal map, otherwise it falls back on the data layout.
409 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
410 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
411 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000412 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
413 unsigned member,
414 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400415
alan-baker5b86ed72019-02-15 08:26:50 -0500416 // Returns the base pointer of |v|.
417 Value *GetBasePointer(Value *v);
418
SJW01901d92020-05-21 08:58:31 -0500419 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
420 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
421
alan-baker5b86ed72019-02-15 08:26:50 -0500422 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
423 // |address_space|.
424 void setVariablePointersCapabilities(unsigned address_space);
425
426 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
427 // variable.
428 bool sameResource(Value *lhs, Value *rhs) const;
429
430 // Returns true if |inst| is phi or select that selects from the same
431 // structure (or null).
432 bool selectFromSameObject(Instruction *inst);
433
alan-bakere9308012019-03-15 10:25:13 -0400434 // Returns true if |Arg| is called with a coherent resource.
435 bool CalledWithCoherentResource(Argument &Arg);
436
SJWf93f5f32020-05-05 07:27:56 -0500437 //
438 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
439 template <enum SPIRVSection TSection = kFunctions>
440 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
441 bool has_result, has_result_type;
442 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
443 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500444 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500445 return RID;
446 }
447 template <enum SPIRVSection TSection = kFunctions>
448 SPIRVID addSPIRVInst(spv::Op Op) {
449 SPIRVOperandVec Ops;
450 return addSPIRVInst<TSection>(Op, Ops);
451 }
452 template <enum SPIRVSection TSection = kFunctions>
453 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
454 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500455 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500456 return addSPIRVInst<TSection>(Op, Ops);
457 }
458 template <enum SPIRVSection TSection = kFunctions>
459 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
460 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500461 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500462 return addSPIRVInst<TSection>(Op, Ops);
463 }
464
SJW88ed5fe2020-05-11 12:40:57 -0500465 //
466 // Add placeholder for llvm::Value that references future values.
467 // Must have result ID just in case final SPIRVInstruction requires.
468 SPIRVID addSPIRVPlaceholder(Value *I) {
469 SPIRVID RID = incrNextID();
470 SPIRVOperandVec Ops;
471 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
472 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
473 return RID;
474 }
475 // Replace placeholder with actual SPIRVInstruction on the final pass
476 // (HandleDeferredInstruction).
477 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
478 SPIRVOperandVec &Operands) {
479 bool has_result, has_result_type;
480 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
481 SPIRVID RID = has_result ? I->getResultID() : 0;
482 *I = SPIRVInstruction(Opcode, RID, Operands);
483 return RID;
484 }
485
SJW806a5d82020-07-15 12:51:38 -0500486 //
487 // Add global variable and capture entry point interface
488 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
489 const SPIRVID &InitID = SPIRVID());
490
alan-baker86ce19c2020-08-05 13:09:19 -0400491 SPIRVID getReflectionImport();
492 void GenerateReflection();
493 void GenerateKernelReflection();
494 void GeneratePushConstantReflection();
495 void GenerateSpecConstantReflection();
496 void AddArgumentReflection(SPIRVID kernel_decl, const std::string &name,
497 clspv::ArgKind arg_kind, uint32_t ordinal,
498 uint32_t descriptor_set, uint32_t binding,
499 uint32_t offset, uint32_t size, uint32_t spec_id,
500 uint32_t elem_size);
501
David Neto22f144c2017-06-12 14:26:21 -0400502private:
503 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500504
505 Module *module;
506
SJW01901d92020-05-21 08:58:31 -0500507 // Set of Capabilities required
508 CapabilitySetType CapabilitySet;
509
SJW806a5d82020-07-15 12:51:38 -0500510 // Map from clspv::BuiltinType to SPIRV Global Variable
511 BuiltinConstantMapType BuiltinConstantMap;
512
David Neto44795152017-07-13 15:45:28 -0400513 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400514 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400515
516 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
517 // convert to other formats on demand?
518
519 // When emitting a C initialization list, the WriteSPIRVBinary method
520 // will actually write its words to this vector via binaryTempOut.
521 SmallVector<char, 100> binaryTempUnderlyingVector;
522 raw_svector_ostream binaryTempOut;
523
524 // Binary output writes to this stream, which might be |out| or
525 // |binaryTempOut|. It's the latter when we really want to write a C
526 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400527 raw_pwrite_stream *binaryOut;
David Neto0676e6f2017-07-11 18:47:44 -0400528 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400529 uint64_t patchBoundOffset;
530 uint32_t nextID;
531
SJWf93f5f32020-05-05 07:27:56 -0500532 SPIRVID incrNextID() { return nextID++; }
533
alan-bakerf67468c2019-11-25 15:51:49 -0500534 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500535 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500536 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500537 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500538
David Neto19a1bad2017-08-25 15:01:41 -0400539 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400540 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400541 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400542 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400543 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400544 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400545 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400546 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500547 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400548
David Neto22f144c2017-06-12 14:26:21 -0400549 EntryPointVecType EntryPointVec;
550 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500551 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500552 SPIRVID OpExtInstImportID;
553 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500554 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400555 bool HasVariablePointers;
556 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500557 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700558
559 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700560 // will map F's type to (G, index of the parameter), where in a first phase
561 // G is F's type. During FindTypePerFunc, G will be changed to F's type
562 // but replacing the pointer-to-constant parameter with
563 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700564 // TODO(dneto): This doesn't seem general enough? A function might have
565 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400566 GlobalConstFuncMapType GlobalConstFuncTypeMap;
567 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400568 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700569 // or array types, and which point into transparent memory (StorageBuffer
570 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400571 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700572 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400573
574 // This is truly ugly, but works around what look like driver bugs.
575 // For get_local_size, an earlier part of the flow has created a module-scope
576 // variable in Private address space to hold the value for the workgroup
577 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
578 // When this is present, save the IDs of the initializer value and variable
579 // in these two variables. We only ever do a vector load from it, and
580 // when we see one of those, substitute just the value of the intializer.
581 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700582 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500583 SPIRVID WorkgroupSizeValueID;
584 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400585
David Neto862b7d82018-06-14 18:48:37 -0400586 // Bookkeeping for mapping kernel arguments to resource variables.
587 struct ResourceVarInfo {
588 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400589 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400590 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400591 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400592 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
593 const int index; // Index into ResourceVarInfoList
594 const unsigned descriptor_set;
595 const unsigned binding;
596 Function *const var_fn; // The @clspv.resource.var.* function.
597 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400598 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400599 const unsigned addr_space; // The LLVM address space
600 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500601 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400602 };
603 // A list of resource var info. Each one correponds to a module-scope
604 // resource variable we will have to create. Resource var indices are
605 // indices into this vector.
606 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
607 // This is a vector of pointers of all the resource vars, but ordered by
608 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500609 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400610 // Map a function to the ordered list of resource variables it uses, one for
611 // each argument. If an argument does not use a resource variable, it
612 // will have a null pointer entry.
613 using FunctionToResourceVarsMapType =
614 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
615 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
616
617 // What LLVM types map to SPIR-V types needing layout? These are the
618 // arrays and structures supporting storage buffers and uniform buffers.
619 TypeList TypesNeedingLayout;
620 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
621 UniqueVector<StructType *> StructTypesNeedingBlock;
622 // For a call that represents a load from an opaque type (samplers, images),
623 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500624 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700625
David Netoc6f3ab22018-04-06 18:02:31 -0400626 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500627 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400628 LocalArgList LocalArgs;
629 // Information about a pointer-to-local argument.
630 struct LocalArgInfo {
631 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500632 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400633 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500634 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400635 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500636 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400637 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500638 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400639 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500640 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400641 // The specialization constant ID of the array size.
642 int spec_id;
643 };
Alan Baker202c8c72018-08-13 13:47:44 -0400644 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500645 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400646 // A mapping from SpecId to its LocalArgInfo.
647 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400648 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500649 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400650 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500651 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
652 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500653
654 // Maps basic block to its merge block.
655 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
656 // Maps basic block to its continue block.
657 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500658
alan-baker86ce19c2020-08-05 13:09:19 -0400659 SPIRVID ReflectionID;
660 DenseMap<Function *, SPIRVID> KernelDeclarations;
661
SJW01901d92020-05-21 08:58:31 -0500662public:
663 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400664};
665
666char SPIRVProducerPass::ID;
SJW01901d92020-05-21 08:58:31 -0500667SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
David Netoc6f3ab22018-04-06 18:02:31 -0400668
alan-bakerb6b09dc2018-11-08 16:59:28 -0500669} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400670
671namespace clspv {
alan-baker86ce19c2020-08-05 13:09:19 -0400672ModulePass *
673createSPIRVProducerPass(raw_pwrite_stream &out,
674 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
675 bool outputCInitList) {
676 return new SPIRVProducerPass(out, samplerMap, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400677}
David Netoc2c368d2017-06-30 16:50:17 -0400678} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400679
SJW01901d92020-05-21 08:58:31 -0500680namespace {
681SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
682 list.emplace_back(LITERAL_WORD, num);
683 return list;
684}
685
686SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
687 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
688 return list;
689}
690
691SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
692 list.emplace_back(num_vec);
693 return list;
694}
695
696SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
697 list.emplace_back(LITERAL_STRING, str);
698 return list;
699}
700
701SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
702 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
703 return list;
704}
705
706SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
707 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
708 return list;
709}
710
SJW806a5d82020-07-15 12:51:38 -0500711SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500712 list.emplace_back(NUMBERID, v.get());
713 return list;
714}
715} // namespace
716
SJW77b87ad2020-04-21 14:37:52 -0500717bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500718 // TODO(sjw): Need to reset all data members for each Module, or better
719 // yet create a new SPIRVProducer for every module.. For now only
720 // allow 1 call.
721 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500722 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400723 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500724 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400725 }
David Neto0676e6f2017-07-11 18:47:44 -0400726 binaryOut = outputCInitList ? &binaryTempOut : &out;
727
SJW77b87ad2020-04-21 14:37:52 -0500728 PopulateUBOTypeMaps();
729 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400730
David Neto22f144c2017-06-12 14:26:21 -0400731 // SPIR-V always begins with its header information
732 outputHeader();
733
734 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500735 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400736
David Neto22f144c2017-06-12 14:26:21 -0400737 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500738 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400739 // If the GV is one of our special __spirv_* variables, remove the
740 // initializer as it was only placed there to force LLVM to not throw the
741 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000742 if (GV.getName().startswith("__spirv_") ||
743 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400744 GV.setInitializer(nullptr);
745 }
746
747 // Collect types' information from global variable.
748 FindTypePerGlobalVar(GV);
David Neto22f144c2017-06-12 14:26:21 -0400749 }
750
David Neto22f144c2017-06-12 14:26:21 -0400751 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500752 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400753
alan-baker09cb9802019-12-10 13:16:27 -0500754 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500755 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400756
757 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500758 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400759 GenerateGlobalVar(GV);
760 }
SJW77b87ad2020-04-21 14:37:52 -0500761 GenerateResourceVars();
762 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400763
764 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500765 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400766 if (F.isDeclaration()) {
767 continue;
768 }
769
770 // Generate Function Prologue.
771 GenerateFuncPrologue(F);
772
773 // Generate SPIRV instructions for function body.
774 GenerateFuncBody(F);
775
776 // Generate Function Epilogue.
777 GenerateFuncEpilogue();
778 }
779
780 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500781 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400782
David Neto22f144c2017-06-12 14:26:21 -0400783 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500784 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400785
alan-baker86ce19c2020-08-05 13:09:19 -0400786 // Generate embedded reflection information.
787 GenerateReflection();
788
alan-baker00e7a582019-06-07 12:54:21 -0400789 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400790
791 // We need to patch the SPIR-V header to set bound correctly.
792 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400793
794 if (outputCInitList) {
795 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400796 std::ostringstream os;
797
David Neto57fb0b92017-08-04 15:35:09 -0400798 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400799 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400800 os << ",\n";
801 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400802 first = false;
803 };
804
805 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400806 const std::string str(binaryTempOut.str());
807 for (unsigned i = 0; i < str.size(); i += 4) {
808 const uint32_t a = static_cast<unsigned char>(str[i]);
809 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
810 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
811 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
812 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400813 }
814 os << "}\n";
815 out << os.str();
816 }
817
David Neto22f144c2017-06-12 14:26:21 -0400818 return false;
819}
820
821void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400822 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
823 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500824 uint32_t minor = 0;
825 if (SpvVersion() == SPIRVVersion::SPIRV_1_3) {
826 minor = 3;
827 }
828 uint32_t version = (1 << 16) | (minor << 8);
829 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400830
alan-baker0c18ab02019-06-12 10:23:21 -0400831 // use Google's vendor ID
832 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400833 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400834
alan-baker00e7a582019-06-07 12:54:21 -0400835 // we record where we need to come back to and patch in the bound value
836 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400837
alan-baker00e7a582019-06-07 12:54:21 -0400838 // output a bad bound for now
839 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400840
alan-baker00e7a582019-06-07 12:54:21 -0400841 // output the schema (reserved for use and must be 0)
842 const uint32_t schema = 0;
843 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400844}
845
846void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400847 // for a binary we just write the value of nextID over bound
848 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
849 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400850}
851
SJW77b87ad2020-04-21 14:37:52 -0500852void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400853 // This function generates LLVM IR for function such as global variable for
854 // argument, constant and pointer type for argument access. These information
855 // is artificial one because we need Vulkan SPIR-V output. This function is
856 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400857
SJW77b87ad2020-04-21 14:37:52 -0500858 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400859
SJW77b87ad2020-04-21 14:37:52 -0500860 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400861
862 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500863 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400864 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
865 if (spv::BuiltInWorkgroupSize == BuiltinType) {
866 HasWorkGroupBuiltin = true;
867 }
868 }
869
SJW77b87ad2020-04-21 14:37:52 -0500870 FindTypesForSamplerMap();
871 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400872}
873
SJW77b87ad2020-04-21 14:37:52 -0500874void SPIRVProducerPass::FindGlobalConstVars() {
875 clspv::NormalizeGlobalVariables(*module);
876 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400877
David Neto862b7d82018-06-14 18:48:37 -0400878 SmallVector<GlobalVariable *, 8> GVList;
879 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500880 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400881 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
882 if (GV.use_empty()) {
883 DeadGVList.push_back(&GV);
884 } else {
885 GVList.push_back(&GV);
886 }
887 }
888 }
889
890 // Remove dead global __constant variables.
891 for (auto GV : DeadGVList) {
892 GV->eraseFromParent();
893 }
894 DeadGVList.clear();
895
896 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
897 // For now, we only support a single storage buffer.
898 if (GVList.size() > 0) {
899 assert(GVList.size() == 1);
900 const auto *GV = GVList[0];
901 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400902 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400903 const size_t kConstantMaxSize = 65536;
904 if (constants_byte_size > kConstantMaxSize) {
905 outs() << "Max __constant capacity of " << kConstantMaxSize
906 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
907 llvm_unreachable("Max __constant capacity exceeded");
908 }
909 }
910 } else {
911 // Change global constant variable's address space to ModuleScopePrivate.
912 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
913 for (auto GV : GVList) {
914 // Create new gv with ModuleScopePrivate address space.
915 Type *NewGVTy = GV->getType()->getPointerElementType();
916 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500917 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400918 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
919 NewGV->takeName(GV);
920
921 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
922 SmallVector<User *, 8> CandidateUsers;
923
924 auto record_called_function_type_as_user =
925 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
926 // Find argument index.
927 unsigned index = 0;
928 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
929 if (gv == call->getOperand(i)) {
930 // TODO(dneto): Should we break here?
931 index = i;
932 }
933 }
934
935 // Record function type with global constant.
936 GlobalConstFuncTyMap[call->getFunctionType()] =
937 std::make_pair(call->getFunctionType(), index);
938 };
939
940 for (User *GVU : GVUsers) {
941 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
942 record_called_function_type_as_user(GV, Call);
943 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
944 // Check GEP users.
945 for (User *GEPU : GEP->users()) {
946 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
947 record_called_function_type_as_user(GEP, GEPCall);
948 }
949 }
950 }
951
952 CandidateUsers.push_back(GVU);
953 }
954
955 for (User *U : CandidateUsers) {
956 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500957 if (!isa<Constant>(U)) {
958 // #254: Can't change operands of a constant, but this shouldn't be
959 // something that sticks around in the module.
960 U->replaceUsesOfWith(GV, NewGV);
961 }
David Neto862b7d82018-06-14 18:48:37 -0400962 }
963
964 // Delete original gv.
965 GV->eraseFromParent();
966 }
967 }
968}
969
SJW77b87ad2020-04-21 14:37:52 -0500970void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -0400971 ResourceVarInfoList.clear();
972 FunctionToResourceVarsMap.clear();
973 ModuleOrderedResourceVars.reset();
974 // Normally, there is one resource variable per clspv.resource.var.*
975 // function, since that is unique'd by arg type and index. By design,
976 // we can share these resource variables across kernels because all
977 // kernels use the same descriptor set.
978 //
979 // But if the user requested distinct descriptor sets per kernel, then
980 // the descriptor allocator has made different (set,binding) pairs for
981 // the same (type,arg_index) pair. Since we can decorate a resource
982 // variable with only exactly one DescriptorSet and Binding, we are
983 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +0000984 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -0400985 // (set,binding) values.
986 const bool always_distinct_sets =
987 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -0500988 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -0400989 // Rely on the fact the resource var functions have a stable ordering
990 // in the module.
SJW61531372020-06-09 07:31:08 -0500991 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -0400992 // Find all calls to this function with distinct set and binding pairs.
993 // Save them in ResourceVarInfoList.
994
995 // Determine uniqueness of the (set,binding) pairs only withing this
996 // one resource-var builtin function.
997 using SetAndBinding = std::pair<unsigned, unsigned>;
998 // Maps set and binding to the resource var info.
999 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1000 bool first_use = true;
1001 for (auto &U : F.uses()) {
1002 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1003 const auto set = unsigned(
1004 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1005 const auto binding = unsigned(
1006 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1007 const auto arg_kind = clspv::ArgKind(
1008 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1009 const auto arg_index = unsigned(
1010 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001011 const auto coherent = unsigned(
1012 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001013
1014 // Find or make the resource var info for this combination.
1015 ResourceVarInfo *rv = nullptr;
1016 if (always_distinct_sets) {
1017 // Make a new resource var any time we see a different
1018 // (set,binding) pair.
1019 SetAndBinding key{set, binding};
1020 auto where = set_and_binding_map.find(key);
1021 if (where == set_and_binding_map.end()) {
1022 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001023 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001024 ResourceVarInfoList.emplace_back(rv);
1025 set_and_binding_map[key] = rv;
1026 } else {
1027 rv = where->second;
1028 }
1029 } else {
1030 // The default is to make exactly one resource for each
1031 // clspv.resource.var.* function.
1032 if (first_use) {
1033 first_use = false;
1034 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001035 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001036 ResourceVarInfoList.emplace_back(rv);
1037 } else {
1038 rv = ResourceVarInfoList.back().get();
1039 }
1040 }
1041
1042 // Now populate FunctionToResourceVarsMap.
1043 auto &mapping =
1044 FunctionToResourceVarsMap[call->getParent()->getParent()];
1045 while (mapping.size() <= arg_index) {
1046 mapping.push_back(nullptr);
1047 }
1048 mapping[arg_index] = rv;
1049 }
1050 }
1051 }
1052 }
1053
1054 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001055 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001056 auto where = FunctionToResourceVarsMap.find(&F);
1057 if (where != FunctionToResourceVarsMap.end()) {
1058 for (auto &rv : where->second) {
1059 if (rv != nullptr) {
1060 ModuleOrderedResourceVars.insert(rv);
1061 }
1062 }
1063 }
1064 }
1065 if (ShowResourceVars) {
1066 for (auto *info : ModuleOrderedResourceVars) {
1067 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1068 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1069 << "\n";
1070 }
1071 }
1072}
1073
David Neto22f144c2017-06-12 14:26:21 -04001074void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1075 // Investigate global variable's type.
1076 FindType(GV.getType());
1077}
1078
1079void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1080 // Investigate function's type.
1081 FunctionType *FTy = F.getFunctionType();
1082
1083 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1084 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001085 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001086 if (GlobalConstFuncTyMap.count(FTy)) {
1087 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1088 SmallVector<Type *, 4> NewFuncParamTys;
1089 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1090 Type *ParamTy = FTy->getParamType(i);
1091 if (i == GVCstArgIdx) {
1092 Type *EleTy = ParamTy->getPointerElementType();
1093 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1094 }
1095
1096 NewFuncParamTys.push_back(ParamTy);
1097 }
1098
1099 FunctionType *NewFTy =
1100 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1101 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1102 FTy = NewFTy;
1103 }
1104
1105 FindType(FTy);
1106 } else {
1107 // As kernel functions do not have parameters, create new function type and
1108 // add it to type map.
1109 SmallVector<Type *, 4> NewFuncParamTys;
1110 FunctionType *NewFTy =
1111 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1112 FindType(NewFTy);
1113 }
1114
1115 // Investigate instructions' type in function body.
1116 for (BasicBlock &BB : F) {
1117 for (Instruction &I : BB) {
1118 if (isa<ShuffleVectorInst>(I)) {
1119 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1120 // Ignore type for mask of shuffle vector instruction.
1121 if (i == 2) {
1122 continue;
1123 }
1124
1125 Value *Op = I.getOperand(i);
1126 if (!isa<MetadataAsValue>(Op)) {
1127 FindType(Op->getType());
1128 }
1129 }
1130
1131 FindType(I.getType());
1132 continue;
1133 }
1134
David Neto862b7d82018-06-14 18:48:37 -04001135 CallInst *Call = dyn_cast<CallInst>(&I);
1136
SJW61531372020-06-09 07:31:08 -05001137 if (Call) {
1138 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
1139 if (func_info.getType() == Builtins::kClspvResource ||
1140 func_info.getType() == Builtins::kClspvLocal) {
1141 // This is a fake call representing access to a resource/workgroup
1142 // variable. We handle that elsewhere.
1143 continue;
1144 }
Alan Baker202c8c72018-08-13 13:47:44 -04001145 }
1146
alan-bakerf083bed2020-01-29 08:15:42 -05001147 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1148 // OpCompositeExtract which takes literal values for indices. As a result
1149 // don't map the type of indices.
1150 if (I.getOpcode() == Instruction::ExtractValue) {
1151 FindType(I.getOperand(0)->getType());
1152 continue;
1153 }
1154 if (I.getOpcode() == Instruction::InsertValue) {
1155 FindType(I.getOperand(0)->getType());
1156 FindType(I.getOperand(1)->getType());
1157 continue;
1158 }
1159
1160 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1161 // the index is a constant. In such a case don't map the index type.
1162 if (I.getOpcode() == Instruction::ExtractElement) {
1163 FindType(I.getOperand(0)->getType());
1164 Value *op1 = I.getOperand(1);
1165 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1166 FindType(op1->getType());
1167 }
1168 continue;
1169 }
1170 if (I.getOpcode() == Instruction::InsertElement) {
1171 FindType(I.getOperand(0)->getType());
1172 FindType(I.getOperand(1)->getType());
1173 Value *op2 = I.getOperand(2);
1174 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1175 FindType(op2->getType());
1176 }
1177 continue;
1178 }
1179
David Neto22f144c2017-06-12 14:26:21 -04001180 // Work through the operands of the instruction.
1181 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1182 Value *const Op = I.getOperand(i);
1183 // If any of the operands is a constant, find the type!
1184 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1185 FindType(Op->getType());
1186 }
1187 }
1188
1189 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001190 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001191 // Avoid to check call instruction's type.
1192 break;
1193 }
Alan Baker202c8c72018-08-13 13:47:44 -04001194 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
SJW61531372020-06-09 07:31:08 -05001195 if (Builtins::Lookup(OpCall->getCalledFunction()) ==
1196 Builtins::kClspvLocal) {
Alan Baker202c8c72018-08-13 13:47:44 -04001197 // This is a fake call representing access to a workgroup variable.
1198 // We handle that elsewhere.
1199 continue;
1200 }
1201 }
David Neto22f144c2017-06-12 14:26:21 -04001202 if (!isa<MetadataAsValue>(&Op)) {
1203 FindType(Op->getType());
1204 continue;
1205 }
1206 }
1207
David Neto22f144c2017-06-12 14:26:21 -04001208 // We don't want to track the type of this call as we are going to replace
1209 // it.
SJW61531372020-06-09 07:31:08 -05001210 if (Call && Builtins::Lookup(Call->getCalledFunction()) ==
1211 Builtins::kClspvSamplerVarLiteral) {
David Neto22f144c2017-06-12 14:26:21 -04001212 continue;
1213 }
1214
1215 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1216 // If gep's base operand has ModuleScopePrivate address space, make gep
1217 // return ModuleScopePrivate address space.
1218 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1219 // Add pointer type with private address space for global constant to
1220 // type list.
1221 Type *EleTy = I.getType()->getPointerElementType();
1222 Type *NewPTy =
1223 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1224
1225 FindType(NewPTy);
1226 continue;
1227 }
1228 }
1229
1230 FindType(I.getType());
1231 }
1232 }
1233}
1234
SJW77b87ad2020-04-21 14:37:52 -05001235void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001236 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001237 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001238 0 < getSamplerMap().size()) {
SJW77b87ad2020-04-21 14:37:52 -05001239 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001240 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001241 SamplerStructTy =
1242 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001243 }
1244
1245 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1246
1247 FindType(SamplerTy);
1248 }
1249}
1250
SJW77b87ad2020-04-21 14:37:52 -05001251void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001252 // Record types so they are generated.
1253 TypesNeedingLayout.reset();
1254 StructTypesNeedingBlock.reset();
1255
1256 // To match older clspv codegen, generate the float type first if required
1257 // for images.
1258 for (const auto *info : ModuleOrderedResourceVars) {
1259 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1260 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001261 if (IsIntImageType(info->var_fn->getReturnType())) {
1262 // Nothing for now...
1263 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001264 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001265 }
1266
1267 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001268 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001269 }
1270 }
1271
1272 for (const auto *info : ModuleOrderedResourceVars) {
1273 Type *type = info->var_fn->getReturnType();
1274
1275 switch (info->arg_kind) {
1276 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001277 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001278 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1279 StructTypesNeedingBlock.insert(sty);
1280 } else {
1281 errs() << *type << "\n";
1282 llvm_unreachable("Buffer arguments must map to structures!");
1283 }
1284 break;
1285 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001286 case clspv::ArgKind::PodUBO:
1287 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001288 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1289 StructTypesNeedingBlock.insert(sty);
1290 } else {
1291 errs() << *type << "\n";
1292 llvm_unreachable("POD arguments must map to structures!");
1293 }
1294 break;
1295 case clspv::ArgKind::ReadOnlyImage:
1296 case clspv::ArgKind::WriteOnlyImage:
1297 case clspv::ArgKind::Sampler:
1298 // Sampler and image types map to the pointee type but
1299 // in the uniform constant address space.
1300 type = PointerType::get(type->getPointerElementType(),
1301 clspv::AddressSpace::UniformConstant);
1302 break;
1303 default:
1304 break;
1305 }
1306
1307 // The converted type is the type of the OpVariable we will generate.
1308 // If the pointee type is an array of size zero, FindType will convert it
1309 // to a runtime array.
1310 FindType(type);
1311 }
1312
alan-bakerdcd97412019-09-16 15:32:30 -04001313 // If module constants are clustered in a storage buffer then that struct
1314 // needs layout decorations.
1315 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001316 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001317 PointerType *PTy = cast<PointerType>(GV.getType());
1318 const auto AS = PTy->getAddressSpace();
1319 const bool module_scope_constant_external_init =
1320 (AS == AddressSpace::Constant) && GV.hasInitializer();
1321 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1322 if (module_scope_constant_external_init &&
1323 spv::BuiltInMax == BuiltinType) {
1324 StructTypesNeedingBlock.insert(
1325 cast<StructType>(PTy->getPointerElementType()));
1326 }
1327 }
1328 }
1329
SJW77b87ad2020-04-21 14:37:52 -05001330 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001331 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1332 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1333 assert(Ty->isStructTy() && "Push constants have to be structures.");
1334 auto STy = cast<StructType>(Ty);
1335 StructTypesNeedingBlock.insert(STy);
1336 }
1337 }
1338
David Neto862b7d82018-06-14 18:48:37 -04001339 // Traverse the arrays and structures underneath each Block, and
1340 // mark them as needing layout.
1341 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1342 StructTypesNeedingBlock.end());
1343 while (!work_list.empty()) {
1344 Type *type = work_list.back();
1345 work_list.pop_back();
1346 TypesNeedingLayout.insert(type);
1347 switch (type->getTypeID()) {
1348 case Type::ArrayTyID:
1349 work_list.push_back(type->getArrayElementType());
1350 if (!Hack_generate_runtime_array_stride_early) {
1351 // Remember this array type for deferred decoration.
1352 TypesNeedingArrayStride.insert(type);
1353 }
1354 break;
1355 case Type::StructTyID:
1356 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1357 work_list.push_back(elem_ty);
1358 }
1359 default:
1360 // This type and its contained types don't get layout.
1361 break;
1362 }
1363 }
1364}
1365
SJWf93f5f32020-05-05 07:27:56 -05001366void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001367 // The SpecId assignment for pointer-to-local arguments is recorded in
1368 // module-level metadata. Translate that information into local argument
1369 // information.
SJWf93f5f32020-05-05 07:27:56 -05001370 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001371 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001372 if (!nmd)
1373 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001374 for (auto operand : nmd->operands()) {
1375 MDTuple *tuple = cast<MDTuple>(operand);
1376 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1377 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001378 ConstantAsMetadata *arg_index_md =
1379 cast<ConstantAsMetadata>(tuple->getOperand(1));
1380 int arg_index = static_cast<int>(
1381 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1382 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001383
1384 ConstantAsMetadata *spec_id_md =
1385 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001386 int spec_id = static_cast<int>(
1387 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001388
Alan Baker202c8c72018-08-13 13:47:44 -04001389 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001390 if (LocalSpecIdInfoMap.count(spec_id))
1391 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001392
SJWf93f5f32020-05-05 07:27:56 -05001393 // Generate the spec constant.
1394 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001395 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001396 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001397
SJWf93f5f32020-05-05 07:27:56 -05001398 // Generate the array type.
1399 Type *ElemTy = arg->getType()->getPointerElementType();
1400 Ops.clear();
1401 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001402 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001403
1404 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1405
1406 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001407 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001408 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1409
1410 // Generate OpVariable.
1411 //
1412 // Ops[0] : Result Type ID
1413 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001414 SPIRVID VariableID =
1415 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001416
1417 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001418 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001419 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1420
1421 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1422 ArrayTypeID, PtrArrayTypeID, spec_id};
1423 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001424 }
1425}
1426
David Neto22f144c2017-06-12 14:26:21 -04001427void SPIRVProducerPass::FindType(Type *Ty) {
1428 TypeList &TyList = getTypeList();
1429
1430 if (0 != TyList.idFor(Ty)) {
1431 return;
1432 }
1433
1434 if (Ty->isPointerTy()) {
1435 auto AddrSpace = Ty->getPointerAddressSpace();
1436 if ((AddressSpace::Constant == AddrSpace) ||
1437 (AddressSpace::Global == AddrSpace)) {
1438 auto PointeeTy = Ty->getPointerElementType();
1439
1440 if (PointeeTy->isStructTy() &&
1441 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1442 FindType(PointeeTy);
1443 auto ActualPointerTy =
1444 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1445 FindType(ActualPointerTy);
1446 return;
1447 }
1448 }
1449 }
1450
David Neto862b7d82018-06-14 18:48:37 -04001451 // By convention, LLVM array type with 0 elements will map to
1452 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1453 // has a constant number of elements. We need to support type of the
1454 // constant.
1455 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1456 if (arrayTy->getNumElements() > 0) {
1457 LLVMContext &Context = Ty->getContext();
1458 FindType(Type::getInt32Ty(Context));
1459 }
David Neto22f144c2017-06-12 14:26:21 -04001460 }
1461
1462 for (Type *SubTy : Ty->subtypes()) {
1463 FindType(SubTy);
1464 }
1465
1466 TyList.insert(Ty);
1467}
1468
David Neto22f144c2017-06-12 14:26:21 -04001469spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1470 switch (AddrSpace) {
1471 default:
1472 llvm_unreachable("Unsupported OpenCL address space");
1473 case AddressSpace::Private:
1474 return spv::StorageClassFunction;
1475 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001476 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001477 case AddressSpace::Constant:
1478 return clspv::Option::ConstantArgsInUniformBuffer()
1479 ? spv::StorageClassUniform
1480 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001481 case AddressSpace::Input:
1482 return spv::StorageClassInput;
1483 case AddressSpace::Local:
1484 return spv::StorageClassWorkgroup;
1485 case AddressSpace::UniformConstant:
1486 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001487 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001488 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001489 case AddressSpace::ModuleScopePrivate:
1490 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001491 case AddressSpace::PushConstant:
1492 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001493 }
1494}
1495
David Neto862b7d82018-06-14 18:48:37 -04001496spv::StorageClass
1497SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1498 switch (arg_kind) {
1499 case clspv::ArgKind::Buffer:
1500 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001501 case clspv::ArgKind::BufferUBO:
1502 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001503 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001504 return spv::StorageClassStorageBuffer;
1505 case clspv::ArgKind::PodUBO:
1506 return spv::StorageClassUniform;
1507 case clspv::ArgKind::PodPushConstant:
1508 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001509 case clspv::ArgKind::Local:
1510 return spv::StorageClassWorkgroup;
1511 case clspv::ArgKind::ReadOnlyImage:
1512 case clspv::ArgKind::WriteOnlyImage:
1513 case clspv::ArgKind::Sampler:
1514 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001515 default:
1516 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001517 }
1518}
1519
David Neto22f144c2017-06-12 14:26:21 -04001520spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1521 return StringSwitch<spv::BuiltIn>(Name)
1522 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1523 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1524 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1525 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1526 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001527 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001528 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001529 .Default(spv::BuiltInMax);
1530}
1531
SJW01901d92020-05-21 08:58:31 -05001532SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1533 if (OpExtInstImportID == 0) {
1534 //
1535 // Generate OpExtInstImport.
1536 //
1537 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001538
SJW01901d92020-05-21 08:58:31 -05001539 OpExtInstImportID =
1540 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1541 }
1542 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001543}
1544
SJW806a5d82020-07-15 12:51:38 -05001545SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1546 spv::StorageClass SC,
1547 const SPIRVID &InitID) {
1548 // Generate OpVariable.
1549 //
1550 // Ops[0] : Result Type ID
1551 // Ops[1] : Storage Class
1552 // Ops[2] : Initialization Value ID (optional)
1553
1554 SPIRVOperandVec Ops;
1555 Ops << TypeID << SC;
1556 if (InitID.isValid()) {
1557 Ops << InitID;
1558 }
1559
1560 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1561
1562 if (SC == spv::StorageClassInput) {
1563 getEntryPointInterfacesList().push_back(VID);
1564 }
1565
1566 return VID;
1567}
1568
SJW01901d92020-05-21 08:58:31 -05001569SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001570 auto TI = TypeMap.find(Ty);
1571 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001572 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001573 return TI->second;
1574 }
1575
1576 const auto &DL = module->getDataLayout();
1577
SJW01901d92020-05-21 08:58:31 -05001578 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001579
1580 switch (Ty->getTypeID()) {
1581 default: {
1582 Ty->print(errs());
1583 llvm_unreachable("Unsupported type???");
1584 break;
1585 }
1586 case Type::MetadataTyID:
1587 case Type::LabelTyID: {
1588 // Ignore these types.
1589 break;
1590 }
1591 case Type::PointerTyID: {
1592 PointerType *PTy = cast<PointerType>(Ty);
1593 unsigned AddrSpace = PTy->getAddressSpace();
1594
1595 if (AddrSpace != AddressSpace::UniformConstant) {
1596 auto PointeeTy = PTy->getElementType();
1597 if (PointeeTy->isStructTy() &&
1598 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1599 // TODO(sjw): assert always an image?
1600 RID = getSPIRVType(PointeeTy);
1601 break;
1602 }
1603 }
1604
1605 // For the purposes of our Vulkan SPIR-V type system, constant and global
1606 // are conflated.
1607 if (AddressSpace::Constant == AddrSpace) {
1608 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1609 AddrSpace = AddressSpace::Global;
1610 // Check to see if we already created this type (for instance, if we
1611 // had a constant <type>* and a global <type>*, the type would be
1612 // created by one of these types, and shared by both).
1613 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1614 if (0 < TypeMap.count(GlobalTy)) {
1615 RID = TypeMap[GlobalTy];
1616 break;
1617 }
1618 }
1619 } else if (AddressSpace::Global == AddrSpace) {
1620 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1621 AddrSpace = AddressSpace::Constant;
1622
1623 // Check to see if we already created this type (for instance, if we
1624 // had a constant <type>* and a global <type>*, the type would be
1625 // created by one of these types, and shared by both).
1626 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1627 if (0 < TypeMap.count(ConstantTy)) {
1628 RID = TypeMap[ConstantTy];
1629 break;
1630 }
1631 }
1632 }
1633
1634 //
1635 // Generate OpTypePointer.
1636 //
1637
1638 // OpTypePointer
1639 // Ops[0] = Storage Class
1640 // Ops[1] = Element Type ID
1641 SPIRVOperandVec Ops;
1642
SJW01901d92020-05-21 08:58:31 -05001643 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001644
1645 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1646 break;
1647 }
1648 case Type::StructTyID: {
1649 StructType *STy = cast<StructType>(Ty);
1650
1651 // Handle sampler type.
1652 if (STy->isOpaque()) {
1653 if (STy->getName().equals("opencl.sampler_t")) {
1654 //
1655 // Generate OpTypeSampler
1656 //
1657 // Empty Ops.
1658
1659 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1660 break;
1661 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
1662 STy->getName().startswith("opencl.image1d_wo_t") ||
1663 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1664 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1665 STy->getName().startswith("opencl.image2d_ro_t") ||
1666 STy->getName().startswith("opencl.image2d_wo_t") ||
1667 STy->getName().startswith("opencl.image2d_array_ro_t") ||
1668 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1669 STy->getName().startswith("opencl.image3d_ro_t") ||
1670 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001671
1672 if (STy->getName().contains("_wo_t")) {
1673 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
1674 }
1675 if (STy->getName().startswith("opencl.image1d_")) {
1676 if (STy->getName().contains(".sampled"))
1677 addCapability(spv::CapabilitySampled1D);
1678 else
1679 addCapability(spv::CapabilityImage1D);
1680 }
1681
SJWf93f5f32020-05-05 07:27:56 -05001682 //
1683 // Generate OpTypeImage
1684 //
1685 // Ops[0] = Sampled Type ID
1686 // Ops[1] = Dim ID
1687 // Ops[2] = Depth (Literal Number)
1688 // Ops[3] = Arrayed (Literal Number)
1689 // Ops[4] = MS (Literal Number)
1690 // Ops[5] = Sampled (Literal Number)
1691 // Ops[6] = Image Format ID
1692 //
1693 SPIRVOperandVec Ops;
1694
SJW01901d92020-05-21 08:58:31 -05001695 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001696 if (STy->getName().contains(".float")) {
1697 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1698 } else if (STy->getName().contains(".uint")) {
1699 SampledTyID = getSPIRVType(Type::getInt32Ty(Ty->getContext()));
1700 } else if (STy->getName().contains(".int")) {
1701 // Generate a signed 32-bit integer if necessary.
1702 if (int32ID == 0) {
1703 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001704 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001705 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1706 }
1707 SampledTyID = int32ID;
1708
1709 // Generate a vec4 of the signed int if necessary.
1710 if (v4int32ID == 0) {
1711 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001712 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001713 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1714 }
1715 } else {
1716 // This was likely an UndefValue.
1717 SampledTyID = getSPIRVType(Type::getFloatTy(Ty->getContext()));
1718 }
SJW01901d92020-05-21 08:58:31 -05001719 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001720
1721 spv::Dim DimID = spv::Dim2D;
1722 if (STy->getName().startswith("opencl.image1d_ro_t") ||
1723 STy->getName().startswith("opencl.image1d_wo_t") ||
1724 STy->getName().startswith("opencl.image1d_array_ro_t") ||
1725 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1726 DimID = spv::Dim1D;
1727 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
1728 STy->getName().startswith("opencl.image3d_wo_t")) {
1729 DimID = spv::Dim3D;
1730 }
SJW01901d92020-05-21 08:58:31 -05001731 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001732
1733 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001734 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001735
1736 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001737 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001738
1739 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001740 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001741
1742 // Set up Sampled.
1743 //
1744 // From Spec
1745 //
1746 // 0 indicates this is only known at run time, not at compile time
1747 // 1 indicates will be used with sampler
1748 // 2 indicates will be used without a sampler (a storage image)
1749 uint32_t Sampled = 1;
1750 if (!STy->getName().contains(".sampled")) {
1751 Sampled = 2;
1752 }
SJW01901d92020-05-21 08:58:31 -05001753 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001754
1755 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001756 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001757
1758 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1759
1760 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001761 Ops << RID;
SJWf93f5f32020-05-05 07:27:56 -05001762
1763 getImageTypeMap()[Ty] =
1764 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1765 break;
1766 }
1767 }
1768
1769 //
1770 // Generate OpTypeStruct
1771 //
1772 // Ops[0] ... Ops[n] = Member IDs
1773 SPIRVOperandVec Ops;
1774
1775 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001776 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001777 }
1778
1779 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1780
1781 // Generate OpMemberDecorate.
1782 if (TypesNeedingLayout.idFor(STy)) {
1783 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1784 MemberIdx++) {
1785 // Ops[0] = Structure Type ID
1786 // Ops[1] = Member Index(Literal Number)
1787 // Ops[2] = Decoration (Offset)
1788 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001789 const auto ByteOffset =
1790 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1791
SJW01901d92020-05-21 08:58:31 -05001792 Ops.clear();
1793 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001794
1795 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1796 }
1797 }
1798
1799 // Generate OpDecorate.
1800 if (StructTypesNeedingBlock.idFor(STy)) {
1801 Ops.clear();
1802 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001803 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001804
1805 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1806 }
1807 break;
1808 }
1809 case Type::IntegerTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001810 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001811
alan-bakere2a62752020-07-09 22:53:23 -04001812 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001813 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001814 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001815 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001816 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001817 addCapability(spv::CapabilityInt64);
1818 }
1819
alan-bakere2a62752020-07-09 22:53:23 -04001820 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001821 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1822 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001823 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001824 // i8 is added to TypeMap as i32.
1825 RID = getSPIRVType(Type::getIntNTy(Ty->getContext(), 32));
1826 } else {
1827 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001828 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001829 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1830 }
1831 }
1832 break;
1833 }
1834 case Type::HalfTyID:
1835 case Type::FloatTyID:
1836 case Type::DoubleTyID: {
alan-bakere2a62752020-07-09 22:53:23 -04001837 uint32_t bit_width = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
1838 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001839 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001840 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001841 addCapability(spv::CapabilityFloat64);
1842 }
1843
SJWf93f5f32020-05-05 07:27:56 -05001844 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001845 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001846
1847 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1848 break;
1849 }
1850 case Type::ArrayTyID: {
1851 ArrayType *ArrTy = cast<ArrayType>(Ty);
1852 const uint64_t Length = ArrTy->getArrayNumElements();
1853 if (Length == 0) {
1854 // By convention, map it to a RuntimeArray.
1855
1856 Type *EleTy = ArrTy->getArrayElementType();
1857
1858 //
1859 // Generate OpTypeRuntimeArray.
1860 //
1861 // OpTypeRuntimeArray
1862 // Ops[0] = Element Type ID
1863 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001864 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001865
1866 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1867
1868 if (Hack_generate_runtime_array_stride_early) {
1869 // Generate OpDecorate.
1870
1871 // Ops[0] = Target ID
1872 // Ops[1] = Decoration (ArrayStride)
1873 // Ops[2] = Stride Number(Literal Number)
1874 Ops.clear();
1875
SJW01901d92020-05-21 08:58:31 -05001876 Ops << RID << spv::DecorationArrayStride
1877 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001878
1879 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1880 }
1881
1882 } else {
1883
1884 //
1885 // Generate OpConstant and OpTypeArray.
1886 //
1887
1888 //
1889 // Generate OpConstant for array length.
1890 //
1891 // Add constant for length to constant list.
1892 Constant *CstLength =
1893 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001894
1895 // Remember to generate ArrayStride later
1896 getTypesNeedingArrayStride().insert(Ty);
1897
1898 //
1899 // Generate OpTypeArray.
1900 //
1901 // Ops[0] = Element Type ID
1902 // Ops[1] = Array Length Constant ID
1903 SPIRVOperandVec Ops;
1904
SJW01901d92020-05-21 08:58:31 -05001905 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001906
1907 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1908 }
1909 break;
1910 }
1911 case Type::FixedVectorTyID: {
1912 auto VecTy = cast<VectorType>(Ty);
1913 // <4 x i8> is changed to i32 if i8 is not generally supported.
1914 if (!clspv::Option::Int8Support() &&
1915 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
1916 if (VecTy->getNumElements() == 4) {
1917 RID = getSPIRVType(VecTy->getElementType());
1918 break;
1919 } else {
1920 Ty->print(errs());
1921 llvm_unreachable("Support above i8 vector type");
1922 }
1923 }
1924
1925 // Ops[0] = Component Type ID
1926 // Ops[1] = Component Count (Literal Number)
1927 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001928 Ops << VecTy->getElementType() << VecTy->getNumElements();
SJWf93f5f32020-05-05 07:27:56 -05001929
1930 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1931 break;
1932 }
1933 case Type::VoidTyID: {
1934 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
1935 break;
1936 }
1937 case Type::FunctionTyID: {
1938 // Generate SPIRV instruction for function type.
1939 FunctionType *FTy = cast<FunctionType>(Ty);
1940
1941 // Ops[0] = Return Type ID
1942 // Ops[1] ... Ops[n] = Parameter Type IDs
1943 SPIRVOperandVec Ops;
1944
1945 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05001946 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05001947
1948 // Find SPIRV instructions for parameter types
1949 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1950 // Find SPIRV instruction for parameter type.
1951 auto ParamTy = FTy->getParamType(k);
1952 if (ParamTy->isPointerTy()) {
1953 auto PointeeTy = ParamTy->getPointerElementType();
1954 if (PointeeTy->isStructTy() &&
1955 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1956 ParamTy = PointeeTy;
1957 }
1958 }
1959
SJW01901d92020-05-21 08:58:31 -05001960 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05001961 }
1962
1963 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
1964 break;
1965 }
1966 }
1967
SJW01901d92020-05-21 08:58:31 -05001968 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05001969 TypeMap[Ty] = RID;
1970 }
1971 return RID;
David Neto22f144c2017-06-12 14:26:21 -04001972}
1973
SJW77b87ad2020-04-21 14:37:52 -05001974void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04001975 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05001976 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04001977 }
David Neto22f144c2017-06-12 14:26:21 -04001978}
1979
SJW806a5d82020-07-15 12:51:38 -05001980SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
1981 Type *i32 = Type::getInt32Ty(module->getContext());
1982 Constant *Cst = ConstantInt::get(i32, CstVal);
1983 return getSPIRVValue(Cst);
1984}
1985
SJWf93f5f32020-05-05 07:27:56 -05001986SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04001987 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07001988 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04001989
SJW01901d92020-05-21 08:58:31 -05001990 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04001991
SJWf93f5f32020-05-05 07:27:56 -05001992 //
1993 // Generate OpConstant.
1994 //
1995 // Ops[0] = Result Type ID
1996 // Ops[1] .. Ops[n] = Values LiteralNumber
1997 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04001998
SJW01901d92020-05-21 08:58:31 -05001999 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04002000
SJWf93f5f32020-05-05 07:27:56 -05002001 std::vector<uint32_t> LiteralNum;
2002 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04002003
SJWf93f5f32020-05-05 07:27:56 -05002004 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04002005 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05002006 Opcode = spv::OpUndef;
2007 if (hack_undef && IsTypeNullable(Cst->getType())) {
2008 Opcode = spv::OpConstantNull;
2009 }
2010 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04002011 unsigned bit_width = CI->getBitWidth();
2012 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05002013 // If the bitwidth of constant is 1, generate OpConstantTrue or
2014 // OpConstantFalse.
2015 if (CI->getZExtValue()) {
2016 // Ops[0] = Result Type ID
2017 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04002018 } else {
SJWf93f5f32020-05-05 07:27:56 -05002019 // Ops[0] = Result Type ID
2020 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04002021 }
SJWf93f5f32020-05-05 07:27:56 -05002022 } else {
2023 auto V = CI->getZExtValue();
2024 LiteralNum.push_back(V & 0xFFFFFFFF);
2025
alan-bakere2a62752020-07-09 22:53:23 -04002026 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05002027 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002028 }
2029
2030 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002031
SJW01901d92020-05-21 08:58:31 -05002032 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002033 }
2034 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2035 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2036 Type *CFPTy = CFP->getType();
2037 if (CFPTy->isFloatTy()) {
2038 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2039 } else if (CFPTy->isDoubleTy()) {
2040 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2041 LiteralNum.push_back(FPVal >> 32);
2042 } else if (CFPTy->isHalfTy()) {
2043 LiteralNum.push_back(FPVal & 0xFFFF);
2044 } else {
2045 CFPTy->print(errs());
2046 llvm_unreachable("Implement this ConstantFP Type");
2047 }
David Neto22f144c2017-06-12 14:26:21 -04002048
SJWf93f5f32020-05-05 07:27:56 -05002049 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04002050
SJW01901d92020-05-21 08:58:31 -05002051 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002052 } else if (isa<ConstantDataSequential>(Cst) &&
2053 cast<ConstantDataSequential>(Cst)->isString()) {
2054 Cst->print(errs());
2055 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002056
SJWf93f5f32020-05-05 07:27:56 -05002057 } else if (const ConstantDataSequential *CDS =
2058 dyn_cast<ConstantDataSequential>(Cst)) {
2059 // Let's convert <4 x i8> constant to int constant specially.
2060 // This case occurs when all the values are specified as constant
2061 // ints.
2062 Type *CstTy = Cst->getType();
2063 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002064 //
2065 // Generate OpConstant with OpTypeInt 32 0.
2066 //
2067 uint32_t IntValue = 0;
2068 for (unsigned k = 0; k < 4; k++) {
2069 const uint64_t Val = CDS->getElementAsInteger(k);
2070 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002071 }
2072
SJW806a5d82020-07-15 12:51:38 -05002073 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002074 } else {
2075
David Neto49351ac2017-08-26 17:32:20 -04002076 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002077 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002078 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002079 }
2080
2081 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002082 }
2083 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2084 // Let's convert <4 x i8> constant to int constant specially.
2085 // This case occurs when at least one of the values is an undef.
2086 Type *CstTy = Cst->getType();
2087 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002088 //
2089 // Generate OpConstant with OpTypeInt 32 0.
2090 //
2091 uint32_t IntValue = 0;
2092 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2093 I != E; ++I) {
2094 uint64_t Val = 0;
2095 const Value *CV = *I;
2096 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2097 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002098 }
SJWf93f5f32020-05-05 07:27:56 -05002099 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002100 }
2101
SJW806a5d82020-07-15 12:51:38 -05002102 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002103 } else {
2104
David Neto22f144c2017-06-12 14:26:21 -04002105 // We use a constant composite in SPIR-V for our constant aggregate in
2106 // LLVM.
2107 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002108
2109 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002110 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002111 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002112 }
David Neto22f144c2017-06-12 14:26:21 -04002113 }
SJWf93f5f32020-05-05 07:27:56 -05002114 } else if (Cst->isNullValue()) {
2115 Opcode = spv::OpConstantNull;
2116 } else {
2117 Cst->print(errs());
2118 llvm_unreachable("Unsupported Constant???");
2119 }
David Neto22f144c2017-06-12 14:26:21 -04002120
SJWf93f5f32020-05-05 07:27:56 -05002121 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2122 // Null pointer requires variable pointers.
2123 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2124 }
alan-baker5b86ed72019-02-15 08:26:50 -05002125
SJWf93f5f32020-05-05 07:27:56 -05002126 if (RID == 0) {
2127 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2128 }
2129
2130 VMap[Cst] = RID;
2131
2132 return RID;
2133}
2134
2135SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2136 auto II = ValueMap.find(V);
2137 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002138 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002139 return II->second;
2140 }
2141 if (Constant *Cst = dyn_cast<Constant>(V)) {
2142 return getSPIRVConstant(Cst);
2143 } else {
2144 llvm_unreachable("Variable not found");
2145 }
2146}
2147
SJW77b87ad2020-04-21 14:37:52 -05002148void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002149 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002150 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002151 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2152 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002153
David Neto862b7d82018-06-14 18:48:37 -04002154 // We might have samplers in the sampler map that are not used
2155 // in the translation unit. We need to allocate variables
2156 // for them and bindings too.
2157 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002158
SJW77b87ad2020-04-21 14:37:52 -05002159 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002160 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002161 if (!var_fn)
2162 return;
alan-baker09cb9802019-12-10 13:16:27 -05002163
David Neto862b7d82018-06-14 18:48:37 -04002164 for (auto user : var_fn->users()) {
2165 // Populate SamplerLiteralToDescriptorSetMap and
2166 // SamplerLiteralToBindingMap.
2167 //
2168 // Look for calls like
2169 // call %opencl.sampler_t addrspace(2)*
2170 // @clspv.sampler.var.literal(
2171 // i32 descriptor,
2172 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002173 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002174 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002175 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002176 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002177 auto sampler_value = third_param;
2178 if (clspv::Option::UseSamplerMap()) {
2179 if (third_param >= sampler_map.size()) {
2180 errs() << "Out of bounds index to sampler map: " << third_param;
2181 llvm_unreachable("bad sampler init: out of bounds");
2182 }
2183 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002184 }
2185
David Neto862b7d82018-06-14 18:48:37 -04002186 const auto descriptor_set = static_cast<unsigned>(
2187 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2188 const auto binding = static_cast<unsigned>(
2189 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2190
2191 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2192 SamplerLiteralToBindingMap[sampler_value] = binding;
2193 used_bindings.insert(binding);
2194 }
2195 }
2196
alan-baker09cb9802019-12-10 13:16:27 -05002197 DenseSet<size_t> seen;
2198 for (auto user : var_fn->users()) {
2199 if (!isa<CallInst>(user))
2200 continue;
2201
2202 auto call = cast<CallInst>(user);
2203 const unsigned third_param = static_cast<unsigned>(
2204 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2205
2206 // Already allocated a variable for this value.
2207 if (!seen.insert(third_param).second)
2208 continue;
2209
2210 auto sampler_value = third_param;
2211 if (clspv::Option::UseSamplerMap()) {
2212 sampler_value = sampler_map[third_param].first;
2213 }
2214
SJW806a5d82020-07-15 12:51:38 -05002215 auto sampler_var_id = addSPIRVGlobalVariable(
2216 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002217
alan-baker09cb9802019-12-10 13:16:27 -05002218 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002219
David Neto862b7d82018-06-14 18:48:37 -04002220 unsigned descriptor_set;
2221 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002222 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002223 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002224 // This sampler is not actually used. Find the next one.
2225 for (binding = 0; used_bindings.count(binding); binding++)
2226 ;
2227 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2228 used_bindings.insert(binding);
2229 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002230 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2231 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002232
alan-baker86ce19c2020-08-05 13:09:19 -04002233 auto import_id = getReflectionImport();
2234 SPIRVOperandVec Ops;
2235 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2236 << reflection::ExtInstLiteralSampler
2237 << getSPIRVInt32Constant(descriptor_set)
2238 << getSPIRVInt32Constant(binding)
2239 << getSPIRVInt32Constant(sampler_value);
2240 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002241 }
2242
SJW69939d52020-04-16 07:29:07 -05002243 // Ops[0] = Target ID
2244 // Ops[1] = Decoration (DescriptorSet)
2245 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002246 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002247 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002248
SJWf93f5f32020-05-05 07:27:56 -05002249 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002250
2251 // Ops[0] = Target ID
2252 // Ops[1] = Decoration (Binding)
2253 // Ops[2] = LiteralNumber according to Decoration
2254 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002255 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002256
SJWf93f5f32020-05-05 07:27:56 -05002257 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002258 }
David Neto862b7d82018-06-14 18:48:37 -04002259}
David Neto22f144c2017-06-12 14:26:21 -04002260
SJW77b87ad2020-04-21 14:37:52 -05002261void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002262 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002263
David Neto862b7d82018-06-14 18:48:37 -04002264 // Generate variables. Make one for each of resource var info object.
2265 for (auto *info : ModuleOrderedResourceVars) {
2266 Type *type = info->var_fn->getReturnType();
2267 // Remap the address space for opaque types.
2268 switch (info->arg_kind) {
2269 case clspv::ArgKind::Sampler:
2270 case clspv::ArgKind::ReadOnlyImage:
2271 case clspv::ArgKind::WriteOnlyImage:
2272 type = PointerType::get(type->getPointerElementType(),
2273 clspv::AddressSpace::UniformConstant);
2274 break;
2275 default:
2276 break;
2277 }
David Neto22f144c2017-06-12 14:26:21 -04002278
David Neto862b7d82018-06-14 18:48:37 -04002279 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002280
SJW806a5d82020-07-15 12:51:38 -05002281 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002282
2283 // Map calls to the variable-builtin-function.
2284 for (auto &U : info->var_fn->uses()) {
2285 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2286 const auto set = unsigned(
2287 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2288 const auto binding = unsigned(
2289 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2290 if (set == info->descriptor_set && binding == info->binding) {
2291 switch (info->arg_kind) {
2292 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002293 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002294 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002295 case clspv::ArgKind::PodUBO:
2296 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002297 // The call maps to the variable directly.
2298 VMap[call] = info->var_id;
2299 break;
2300 case clspv::ArgKind::Sampler:
2301 case clspv::ArgKind::ReadOnlyImage:
2302 case clspv::ArgKind::WriteOnlyImage:
2303 // The call maps to a load we generate later.
2304 ResourceVarDeferredLoadCalls[call] = info->var_id;
2305 break;
2306 default:
2307 llvm_unreachable("Unhandled arg kind");
2308 }
2309 }
David Neto22f144c2017-06-12 14:26:21 -04002310 }
David Neto862b7d82018-06-14 18:48:37 -04002311 }
2312 }
David Neto22f144c2017-06-12 14:26:21 -04002313
David Neto862b7d82018-06-14 18:48:37 -04002314 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002315 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002316 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002317 // Push constants don't need descriptor set or binding decorations.
2318 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2319 continue;
2320
David Neto862b7d82018-06-14 18:48:37 -04002321 // Decorate with DescriptorSet and Binding.
2322 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002323 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002324 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002325
2326 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002327 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002328 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002329
alan-bakere9308012019-03-15 10:25:13 -04002330 if (info->coherent) {
2331 // Decorate with Coherent if required for the variable.
2332 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002333 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002334 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002335 }
2336
David Neto862b7d82018-06-14 18:48:37 -04002337 // Generate NonWritable and NonReadable
2338 switch (info->arg_kind) {
2339 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002340 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002341 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2342 clspv::AddressSpace::Constant) {
2343 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002344 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002345 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002346 }
David Neto862b7d82018-06-14 18:48:37 -04002347 break;
David Neto862b7d82018-06-14 18:48:37 -04002348 case clspv::ArgKind::WriteOnlyImage:
2349 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002350 Ops << info->var_id << spv::DecorationNonReadable;
SJWf93f5f32020-05-05 07:27:56 -05002351 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002352 break;
2353 default:
2354 break;
David Neto22f144c2017-06-12 14:26:21 -04002355 }
2356 }
2357}
2358
2359void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002360 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002361 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002362 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002363
2364 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2365 Type *Ty = GV.getType();
2366 PointerType *PTy = cast<PointerType>(Ty);
2367
SJW01901d92020-05-21 08:58:31 -05002368 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002369
2370 // Workgroup size is handled differently (it goes into a constant)
2371 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002372 uint32_t PrevXDimCst = 0xFFFFFFFF;
2373 uint32_t PrevYDimCst = 0xFFFFFFFF;
2374 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002375 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002376 for (Function &Func : *GV.getParent()) {
2377 if (Func.isDeclaration()) {
2378 continue;
2379 }
2380
2381 // We only need to check kernels.
2382 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2383 continue;
2384 }
2385
2386 if (const MDNode *MD =
2387 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2388 uint32_t CurXDimCst = static_cast<uint32_t>(
2389 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2390 uint32_t CurYDimCst = static_cast<uint32_t>(
2391 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2392 uint32_t CurZDimCst = static_cast<uint32_t>(
2393 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2394
2395 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2396 PrevZDimCst == 0xFFFFFFFF) {
2397 PrevXDimCst = CurXDimCst;
2398 PrevYDimCst = CurYDimCst;
2399 PrevZDimCst = CurZDimCst;
2400 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2401 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002402 HasMD = false;
2403 continue;
David Neto22f144c2017-06-12 14:26:21 -04002404 } else {
2405 continue;
2406 }
2407
2408 //
2409 // Generate OpConstantComposite.
2410 //
2411 // Ops[0] : Result Type ID
2412 // Ops[1] : Constant size for x dimension.
2413 // Ops[2] : Constant size for y dimension.
2414 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002415 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002416
SJW01901d92020-05-21 08:58:31 -05002417 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002418 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002419 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002420 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002421 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002422 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002423
SJW01901d92020-05-21 08:58:31 -05002424 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2425 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002426
SJWf93f5f32020-05-05 07:27:56 -05002427 InitializerID =
2428 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002429 } else {
alan-baker3b609772020-09-03 19:10:17 -04002430 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002431 }
2432 }
2433
2434 // If all kernels do not have metadata for reqd_work_group_size, generate
2435 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002436 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002437 //
2438 // Generate OpSpecConstants for x/y/z dimension.
2439 //
2440 // Ops[0] : Result Type ID
2441 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002442
alan-bakera1be3322020-04-20 12:48:18 -04002443 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002444 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002445
SJWf93f5f32020-05-05 07:27:56 -05002446 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002447 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002448 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002449
David Neto257c3892018-04-11 13:19:45 -04002450 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002451 Ops << result_type_id << 1;
2452 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002453
2454 // Y Dimension
2455 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002456 Ops << result_type_id << 1;
2457 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002458
2459 // Z Dimension
2460 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002461 Ops << result_type_id << 1;
2462 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002463
David Neto257c3892018-04-11 13:19:45 -04002464 BuiltinDimVec.push_back(XDimCstID);
2465 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002466 BuiltinDimVec.push_back(ZDimCstID);
2467
David Neto22f144c2017-06-12 14:26:21 -04002468 //
2469 // Generate OpSpecConstantComposite.
2470 //
2471 // Ops[0] : Result Type ID
2472 // Ops[1] : Constant size for x dimension.
2473 // Ops[2] : Constant size for y dimension.
2474 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002475 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002476 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002477
SJWf93f5f32020-05-05 07:27:56 -05002478 InitializerID =
2479 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002480 }
alan-bakerbed3a882020-04-21 14:42:41 -04002481 } else if (BuiltinType == spv::BuiltInWorkDim) {
2482 // 1. Generate a specialization constant with a default of 3.
2483 // 2. Allocate and annotate a SpecId for the constant.
2484 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002485 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002486
2487 //
2488 // Generate OpSpecConstant.
2489 //
2490 // Ops[0] : Result Type ID
2491 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002492
SJW01901d92020-05-21 08:58:31 -05002493 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002494
SJWf93f5f32020-05-05 07:27:56 -05002495 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002496
2497 //
2498 // Generate SpecId decoration.
2499 //
2500 // Ops[0] : target
2501 // Ops[1] : decoration
2502 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002503 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002504 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002505 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002506
SJWf93f5f32020-05-05 07:27:56 -05002507 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002508 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2509 // 1. Generate a spec constant with a default of {0, 0, 0}.
2510 // 2. Allocate and annotate SpecIds for the constants.
2511 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002512 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002513
2514 //
2515 // Generate OpSpecConstant for each dimension.
2516 //
2517 // Ops[0] : Result Type ID
2518 // Ops[1] : Default literal value
2519 //
SJW01901d92020-05-21 08:58:31 -05002520 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2521 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002522
alan-bakere1996972020-05-04 08:38:12 -04002523 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002524 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2525 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002526
alan-bakere1996972020-05-04 08:38:12 -04002527 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002528 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2529 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002530
2531 //
2532 // Generate SpecId decoration for each dimension.
2533 //
2534 // Ops[0] : target
2535 // Ops[1] : decoration
2536 // Ops[2] : SpecId
2537 //
2538 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2539 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002540 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002541 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002542
2543 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2544 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002545 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002546 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002547
2548 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2549 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002550 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002551 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002552
2553 //
2554 // Generate OpSpecConstantComposite.
2555 //
2556 // Ops[0] : type id
2557 // Ops[1..n-1] : elements
2558 //
alan-bakere1996972020-05-04 08:38:12 -04002559 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002560 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002561 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002562 }
2563
David Neto85082642018-03-24 06:55:20 -07002564 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002565 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002566
David Neto85082642018-03-24 06:55:20 -07002567 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002568 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002569 clspv::Option::ModuleConstantsInStorageBuffer();
2570
Kévin Petit23d5f182019-08-13 16:21:29 +01002571 if (GV.hasInitializer()) {
2572 auto GVInit = GV.getInitializer();
2573 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002574 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002575 }
2576 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002577
SJW806a5d82020-07-15 12:51:38 -05002578 SPIRVID var_id =
2579 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002580
SJWf93f5f32020-05-05 07:27:56 -05002581 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002582
alan-bakere1996972020-05-04 08:38:12 -04002583 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2584 return builtin == spv::BuiltInWorkDim ||
2585 builtin == spv::BuiltInGlobalOffset;
2586 };
2587
alan-bakere1996972020-05-04 08:38:12 -04002588 // If we have a builtin (not an OpenCL builtin).
2589 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002590 //
2591 // Generate OpDecorate.
2592 //
2593 // DOps[0] = Target ID
2594 // DOps[1] = Decoration (Builtin)
2595 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002596 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002597
2598 // WorkgroupSize is different, we decorate the constant composite that has
2599 // its value, rather than the variable that we use to access the value.
2600 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2601 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002602 // Save both the value and variable IDs for later.
2603 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002604 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002605 } else {
SJWf93f5f32020-05-05 07:27:56 -05002606 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002607 }
2608
SJW806a5d82020-07-15 12:51:38 -05002609 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002610 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002611
SJW01901d92020-05-21 08:58:31 -05002612 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002613 } else if (module_scope_constant_external_init) {
2614 // This module scope constant is initialized from a storage buffer with data
2615 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002616 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002617
alan-baker86ce19c2020-08-05 13:09:19 -04002618 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002619 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2620 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002621 std::string hexbytes;
2622 llvm::raw_string_ostream str(hexbytes);
2623 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002624
2625 // Reflection instruction for constant data.
2626 SPIRVOperandVec Ops;
2627 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2628 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2629 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2630 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2631 << data_id;
2632 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002633
David Neto85082642018-03-24 06:55:20 -07002634 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002635 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002636 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2637 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002638
2639 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002640 Ops.clear();
2641 Ops << var_id << spv::DecorationBinding << 0;
2642 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002643 }
2644}
2645
David Neto22f144c2017-06-12 14:26:21 -04002646void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002647 ValueMapType &VMap = getValueMap();
2648 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002649 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2650 auto &GlobalConstArgSet = getGlobalConstArgSet();
2651
2652 FunctionType *FTy = F.getFunctionType();
2653
2654 //
David Neto22f144c2017-06-12 14:26:21 -04002655 // Generate OPFunction.
2656 //
2657
2658 // FOps[0] : Result Type ID
2659 // FOps[1] : Function Control
2660 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002661 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002662
2663 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002664 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002665
2666 // Check function attributes for SPIRV Function Control.
2667 uint32_t FuncControl = spv::FunctionControlMaskNone;
2668 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2669 FuncControl |= spv::FunctionControlInlineMask;
2670 }
2671 if (F.hasFnAttribute(Attribute::NoInline)) {
2672 FuncControl |= spv::FunctionControlDontInlineMask;
2673 }
2674 // TODO: Check llvm attribute for Function Control Pure.
2675 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2676 FuncControl |= spv::FunctionControlPureMask;
2677 }
2678 // TODO: Check llvm attribute for Function Control Const.
2679 if (F.hasFnAttribute(Attribute::ReadNone)) {
2680 FuncControl |= spv::FunctionControlConstMask;
2681 }
2682
SJW01901d92020-05-21 08:58:31 -05002683 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002684
SJW01901d92020-05-21 08:58:31 -05002685 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002686 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2687 SmallVector<Type *, 4> NewFuncParamTys;
2688 FunctionType *NewFTy =
2689 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002690 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002691 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002692 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002693 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002694 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002695 } else {
SJWf93f5f32020-05-05 07:27:56 -05002696 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002697 }
2698 }
2699
SJW01901d92020-05-21 08:58:31 -05002700 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002701
SJWf93f5f32020-05-05 07:27:56 -05002702 // Generate SPIRV instruction for function.
2703 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2704 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002705
SJWf93f5f32020-05-05 07:27:56 -05002706 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2707 EntryPoints.push_back(std::make_pair(&F, FID));
2708 }
David Neto22f144c2017-06-12 14:26:21 -04002709
David Neto482550a2018-03-24 05:21:07 -07002710 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002711 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002712 }
David Neto22f144c2017-06-12 14:26:21 -04002713
2714 //
2715 // Generate OpFunctionParameter for Normal function.
2716 //
2717
2718 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002719
David Neto22f144c2017-06-12 14:26:21 -04002720 // Iterate Argument for name instead of param type from function type.
2721 unsigned ArgIdx = 0;
2722 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002723 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002724 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002725
2726 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002727 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002728 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2729 if (GlobalConstFuncTyMap.count(FTy)) {
2730 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2731 Type *EleTy = PTy->getPointerElementType();
2732 Type *ArgTy =
2733 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002734 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002735 GlobalConstArgSet.insert(&Arg);
2736 }
2737 }
2738 }
SJW01901d92020-05-21 08:58:31 -05002739 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002740
2741 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002742 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002743 VMap[&Arg] = param_id;
2744
2745 if (CalledWithCoherentResource(Arg)) {
2746 // If the arg is passed a coherent resource ever, then decorate this
2747 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002748 Ops.clear();
2749 Ops << param_id << spv::DecorationCoherent;
2750 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002751 }
David Neto22f144c2017-06-12 14:26:21 -04002752
2753 ArgIdx++;
2754 }
2755 }
2756}
2757
SJW77b87ad2020-04-21 14:37:52 -05002758void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002759 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002760 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002761 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002762
SJWf93f5f32020-05-05 07:27:56 -05002763 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002764
SJW01901d92020-05-21 08:58:31 -05002765 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002766 //
SJW01901d92020-05-21 08:58:31 -05002767 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002768 //
2769 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002770 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002771 }
2772
2773 // Always add the storage buffer extension
2774 {
David Neto22f144c2017-06-12 14:26:21 -04002775 //
2776 // Generate OpExtension.
2777 //
2778 // Ops[0] = Name (Literal String)
2779 //
SJWf93f5f32020-05-05 07:27:56 -05002780 addSPIRVInst<kExtensions>(spv::OpExtension,
2781 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002782 }
David Neto22f144c2017-06-12 14:26:21 -04002783
alan-baker5b86ed72019-02-15 08:26:50 -05002784 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2785 //
2786 // Generate OpExtension.
2787 //
2788 // Ops[0] = Name (Literal String)
2789 //
SJWf93f5f32020-05-05 07:27:56 -05002790 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002791 }
2792
2793 //
2794 // Generate OpMemoryModel
2795 //
2796 // Memory model for Vulkan will always be GLSL450.
2797
2798 // Ops[0] = Addressing Model
2799 // Ops[1] = Memory Model
2800 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002801 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002802
SJWf93f5f32020-05-05 07:27:56 -05002803 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002804
2805 //
2806 // Generate OpEntryPoint
2807 //
2808 for (auto EntryPoint : EntryPoints) {
2809 // Ops[0] = Execution Model
2810 // Ops[1] = EntryPoint ID
2811 // Ops[2] = Name (Literal String)
2812 // ...
2813 //
2814 // TODO: Do we need to consider Interface ID for forward references???
2815 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002816 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002817 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002818
SJW806a5d82020-07-15 12:51:38 -05002819 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002820 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002821 }
2822
SJWf93f5f32020-05-05 07:27:56 -05002823 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002824 }
2825
alan-baker3b609772020-09-03 19:10:17 -04002826 if (BuiltinDimVec.empty()) {
2827 for (auto EntryPoint : EntryPoints) {
2828 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2829 ->getMetadata("reqd_work_group_size");
2830 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2831 //
2832 // Generate OpExecutionMode
2833 //
David Neto22f144c2017-06-12 14:26:21 -04002834
alan-baker3b609772020-09-03 19:10:17 -04002835 // Ops[0] = Entry Point ID
2836 // Ops[1] = Execution Mode
2837 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2838 Ops.clear();
2839 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2840
2841 uint32_t XDim = static_cast<uint32_t>(
2842 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2843 uint32_t YDim = static_cast<uint32_t>(
2844 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2845 uint32_t ZDim = static_cast<uint32_t>(
2846 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2847
2848 Ops << XDim << YDim << ZDim;
2849
2850 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002851 }
David Neto22f144c2017-06-12 14:26:21 -04002852 }
2853 }
2854
2855 //
2856 // Generate OpSource.
2857 //
2858 // Ops[0] = SourceLanguage ID
2859 // Ops[1] = Version (LiteralNum)
2860 //
SJW01901d92020-05-21 08:58:31 -05002861 uint32_t LangID = spv::SourceLanguageUnknown;
2862 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002863 switch (clspv::Option::Language()) {
2864 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002865 LangID = spv::SourceLanguageOpenCL_C;
2866 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002867 break;
2868 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002869 LangID = spv::SourceLanguageOpenCL_C;
2870 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002871 break;
2872 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002873 LangID = spv::SourceLanguageOpenCL_C;
2874 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002875 break;
2876 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002877 LangID = spv::SourceLanguageOpenCL_C;
2878 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002879 break;
2880 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002881 LangID = spv::SourceLanguageOpenCL_CPP;
2882 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002883 break;
2884 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002885 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002886 }
David Neto22f144c2017-06-12 14:26:21 -04002887
SJW01901d92020-05-21 08:58:31 -05002888 Ops.clear();
2889 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002890 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002891
2892 if (!BuiltinDimVec.empty()) {
2893 //
2894 // Generate OpDecorates for x/y/z dimension.
2895 //
2896 // Ops[0] = Target ID
2897 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002898 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002899
2900 // X Dimension
2901 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002902 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002903 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002904
2905 // Y Dimension
2906 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002907 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002908 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002909
2910 // Z Dimension
2911 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002912 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002913 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002914 }
2915}
2916
David Netob6e2e062018-04-25 10:32:06 -04002917void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2918 // Work around a driver bug. Initializers on Private variables might not
2919 // work. So the start of the kernel should store the initializer value to the
2920 // variables. Yes, *every* entry point pays this cost if *any* entry point
2921 // uses this builtin. At this point I judge this to be an acceptable tradeoff
2922 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002923 // TODO(dneto): Remove this at some point once fixed drivers are widely
2924 // available.
SJW01901d92020-05-21 08:58:31 -05002925 if (WorkgroupSizeVarID.isValid()) {
2926 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04002927
SJWf93f5f32020-05-05 07:27:56 -05002928 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002929 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04002930
SJWf93f5f32020-05-05 07:27:56 -05002931 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04002932 }
2933}
2934
David Neto22f144c2017-06-12 14:26:21 -04002935void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002936 ValueMapType &VMap = getValueMap();
2937
David Netob6e2e062018-04-25 10:32:06 -04002938 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04002939
2940 for (BasicBlock &BB : F) {
2941 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04002942
2943 //
2944 // Generate OpLabel for Basic Block.
2945 //
SJWf93f5f32020-05-05 07:27:56 -05002946 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04002947
David Neto6dcd4712017-06-23 11:06:47 -04002948 // OpVariable instructions must come first.
2949 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05002950 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
2951 // Allocating a pointer requires variable pointers.
2952 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002953 setVariablePointersCapabilities(
2954 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05002955 }
David Neto6dcd4712017-06-23 11:06:47 -04002956 GenerateInstruction(I);
2957 }
2958 }
2959
David Neto22f144c2017-06-12 14:26:21 -04002960 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04002961 if (clspv::Option::HackInitializers()) {
2962 GenerateEntryPointInitialStores();
2963 }
David Neto22f144c2017-06-12 14:26:21 -04002964 }
2965
2966 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04002967 if (!isa<AllocaInst>(I)) {
2968 GenerateInstruction(I);
2969 }
David Neto22f144c2017-06-12 14:26:21 -04002970 }
2971 }
2972}
2973
2974spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
2975 const std::map<CmpInst::Predicate, spv::Op> Map = {
2976 {CmpInst::ICMP_EQ, spv::OpIEqual},
2977 {CmpInst::ICMP_NE, spv::OpINotEqual},
2978 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
2979 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
2980 {CmpInst::ICMP_ULT, spv::OpULessThan},
2981 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
2982 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
2983 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
2984 {CmpInst::ICMP_SLT, spv::OpSLessThan},
2985 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
2986 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
2987 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
2988 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
2989 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
2990 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
2991 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
2992 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
2993 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
2994 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
2995 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
2996 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
2997 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
2998
2999 assert(0 != Map.count(I->getPredicate()));
3000
3001 return Map.at(I->getPredicate());
3002}
3003
3004spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3005 const std::map<unsigned, spv::Op> Map{
3006 {Instruction::Trunc, spv::OpUConvert},
3007 {Instruction::ZExt, spv::OpUConvert},
3008 {Instruction::SExt, spv::OpSConvert},
3009 {Instruction::FPToUI, spv::OpConvertFToU},
3010 {Instruction::FPToSI, spv::OpConvertFToS},
3011 {Instruction::UIToFP, spv::OpConvertUToF},
3012 {Instruction::SIToFP, spv::OpConvertSToF},
3013 {Instruction::FPTrunc, spv::OpFConvert},
3014 {Instruction::FPExt, spv::OpFConvert},
3015 {Instruction::BitCast, spv::OpBitcast}};
3016
3017 assert(0 != Map.count(I.getOpcode()));
3018
3019 return Map.at(I.getOpcode());
3020}
3021
3022spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003023 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003024 switch (I.getOpcode()) {
3025 default:
3026 break;
3027 case Instruction::Or:
3028 return spv::OpLogicalOr;
3029 case Instruction::And:
3030 return spv::OpLogicalAnd;
3031 case Instruction::Xor:
3032 return spv::OpLogicalNotEqual;
3033 }
3034 }
3035
alan-bakerb6b09dc2018-11-08 16:59:28 -05003036 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003037 {Instruction::Add, spv::OpIAdd},
3038 {Instruction::FAdd, spv::OpFAdd},
3039 {Instruction::Sub, spv::OpISub},
3040 {Instruction::FSub, spv::OpFSub},
3041 {Instruction::Mul, spv::OpIMul},
3042 {Instruction::FMul, spv::OpFMul},
3043 {Instruction::UDiv, spv::OpUDiv},
3044 {Instruction::SDiv, spv::OpSDiv},
3045 {Instruction::FDiv, spv::OpFDiv},
3046 {Instruction::URem, spv::OpUMod},
3047 {Instruction::SRem, spv::OpSRem},
3048 {Instruction::FRem, spv::OpFRem},
3049 {Instruction::Or, spv::OpBitwiseOr},
3050 {Instruction::Xor, spv::OpBitwiseXor},
3051 {Instruction::And, spv::OpBitwiseAnd},
3052 {Instruction::Shl, spv::OpShiftLeftLogical},
3053 {Instruction::LShr, spv::OpShiftRightLogical},
3054 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3055
3056 assert(0 != Map.count(I.getOpcode()));
3057
3058 return Map.at(I.getOpcode());
3059}
3060
SJW806a5d82020-07-15 12:51:38 -05003061SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3062 spv::Capability Cap) {
3063 SPIRVID RID;
3064
3065 auto ii = BuiltinConstantMap.find(BID);
3066
3067 if (ii != BuiltinConstantMap.end()) {
3068 return ii->second;
3069 } else {
3070
3071 addCapability(Cap);
3072
3073 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
3074 AddressSpace::Input);
3075
3076 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
3077
3078 BuiltinConstantMap[BID] = RID;
3079
3080 //
3081 // Generate OpDecorate.
3082 //
3083 // Ops[0] : target
3084 // Ops[1] : decoration
3085 // Ops[2] : SpecId
3086 SPIRVOperandVec Ops;
3087 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3088
3089 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3090 }
3091
3092 return RID;
3093}
3094
3095SPIRVID
3096SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3097 const FunctionInfo &FuncInfo) {
3098 SPIRVID RID;
3099
3100 switch (FuncInfo.getType()) {
3101 case Builtins::kClspvCompositeConstruct:
3102 RID = addSPIRVPlaceholder(Call);
3103 break;
3104 case Builtins::kClspvResource: {
3105 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3106 // Generate an OpLoad
3107 SPIRVOperandVec Ops;
3108
3109 Ops << Call->getType()->getPointerElementType()
3110 << ResourceVarDeferredLoadCalls[Call];
3111
3112 RID = addSPIRVInst(spv::OpLoad, Ops);
3113
3114 } else {
3115 // This maps to an OpVariable we've already generated.
3116 // No code is generated for the call.
3117 }
3118 break;
3119 }
3120 case Builtins::kClspvLocal: {
3121 // Don't codegen an instruction here, but instead map this call directly
3122 // to the workgroup variable id.
3123 int spec_id = static_cast<int>(
3124 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3125 const auto &info = LocalSpecIdInfoMap[spec_id];
3126 RID = info.variable_id;
3127 break;
3128 }
3129 case Builtins::kClspvSamplerVarLiteral: {
3130 // Sampler initializers become a load of the corresponding sampler.
3131 // Map this to a load from the variable.
3132 const auto third_param = static_cast<unsigned>(
3133 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3134 auto sampler_value = third_param;
3135 if (clspv::Option::UseSamplerMap()) {
3136 sampler_value = getSamplerMap()[third_param].first;
3137 }
3138
3139 // Generate an OpLoad
3140 SPIRVOperandVec Ops;
3141
3142 Ops << SamplerTy->getPointerElementType()
3143 << SamplerLiteralToIDMap[sampler_value];
3144
3145 RID = addSPIRVInst(spv::OpLoad, Ops);
3146 break;
3147 }
3148 case Builtins::kSpirvAtomicXor: {
3149 // Handle SPIR-V intrinsics
3150 SPIRVOperandVec Ops;
3151
3152 if (!Call->getType()->isVoidTy()) {
3153 Ops << Call->getType();
3154 }
3155
3156 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3157 Ops << Call->getArgOperand(i);
3158 }
3159
3160 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3161 break;
3162 }
3163 case Builtins::kSpirvOp: {
3164 // Handle SPIR-V intrinsics
3165 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3166 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3167 if (opcode != spv::OpNop) {
3168 SPIRVOperandVec Ops;
3169
3170 if (!Call->getType()->isVoidTy()) {
3171 Ops << Call->getType();
3172 }
3173
3174 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3175 Ops << Call->getArgOperand(i);
3176 }
3177
3178 RID = addSPIRVInst(opcode, Ops);
3179 }
3180 break;
3181 }
3182 case Builtins::kSpirvCopyMemory: {
3183 //
3184 // Generate OpCopyMemory.
3185 //
3186
3187 // Ops[0] = Dst ID
3188 // Ops[1] = Src ID
3189 // Ops[2] = Memory Access
3190 // Ops[3] = Alignment
3191
3192 auto IsVolatile =
3193 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
3194
3195 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3196 : spv::MemoryAccessMaskNone;
3197
3198 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3199
3200 auto Alignment =
3201 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
3202
3203 SPIRVOperandVec Ops;
3204 Ops << Call->getArgOperand(0) << Call->getArgOperand(1) << MemoryAccess
3205 << static_cast<uint32_t>(Alignment);
3206
3207 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3208 break;
3209 }
3210 default:
3211 llvm_unreachable("Unknown CLSPV Instruction");
3212 break;
3213 }
3214 return RID;
3215}
3216
3217SPIRVID
3218SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3219 const FunctionInfo &FuncInfo) {
3220 SPIRVID RID;
3221
3222 LLVMContext &Context = module->getContext();
3223 switch (FuncInfo.getType()) {
3224 case Builtins::kReadImagef:
3225 case Builtins::kReadImageh:
3226 case Builtins::kReadImagei:
3227 case Builtins::kReadImageui: {
3228 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3229 // Additionally, OpTypeSampledImage is generated.
3230 const auto &pi = FuncInfo.getParameter(1);
3231 if (pi.isSampler()) {
3232 //
3233 // Generate OpSampledImage.
3234 //
3235 // Ops[0] = Result Type ID
3236 // Ops[1] = Image ID
3237 // Ops[2] = Sampler ID
3238 //
3239 SPIRVOperandVec Ops;
3240
3241 Value *Image = Call->getArgOperand(0);
3242 Value *Sampler = Call->getArgOperand(1);
3243 Value *Coordinate = Call->getArgOperand(2);
3244
3245 TypeMapType &OpImageTypeMap = getImageTypeMap();
3246 Type *ImageTy = Image->getType()->getPointerElementType();
3247 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3248
3249 Ops << ImageTyID << Image << Sampler;
3250
3251 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3252
3253 //
3254 // Generate OpImageSampleExplicitLod.
3255 //
3256 // Ops[0] = Result Type ID
3257 // Ops[1] = Sampled Image ID
3258 // Ops[2] = Coordinate ID
3259 // Ops[3] = Image Operands Type ID
3260 // Ops[4] ... Ops[n] = Operands ID
3261 //
3262 Ops.clear();
3263
3264 const bool is_int_image = IsIntImageType(Image->getType());
3265 SPIRVID result_type;
3266 if (is_int_image) {
3267 result_type = v4int32ID;
3268 } else {
3269 result_type = getSPIRVType(Call->getType());
3270 }
3271
3272 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
3273 Ops << result_type << SampledImageID << Coordinate
3274 << spv::ImageOperandsLodMask << CstFP0;
3275
3276 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3277
3278 if (is_int_image) {
3279 // Generate the bitcast.
3280 Ops.clear();
3281 Ops << Call->getType() << RID;
3282 RID = addSPIRVInst(spv::OpBitcast, Ops);
3283 }
3284 } else {
3285
3286 // read_image (without a sampler) is mapped to OpImageFetch.
3287 Value *Image = Call->getArgOperand(0);
3288 Value *Coordinate = Call->getArgOperand(1);
3289
3290 //
3291 // Generate OpImageFetch
3292 //
3293 // Ops[0] = Result Type ID
3294 // Ops[1] = Image ID
3295 // Ops[2] = Coordinate ID
3296 // Ops[3] = Lod
3297 // Ops[4] = 0
3298 //
3299 SPIRVOperandVec Ops;
3300
3301 const bool is_int_image = IsIntImageType(Image->getType());
3302 SPIRVID result_type;
3303 if (is_int_image) {
3304 result_type = v4int32ID;
3305 } else {
3306 result_type = getSPIRVType(Call->getType());
3307 }
3308
3309 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3310 << getSPIRVInt32Constant(0);
3311
3312 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3313
3314 if (is_int_image) {
3315 // Generate the bitcast.
3316 Ops.clear();
3317 Ops << Call->getType() << RID;
3318 RID = addSPIRVInst(spv::OpBitcast, Ops);
3319 }
3320 }
3321 break;
3322 }
3323
3324 case Builtins::kWriteImagef:
3325 case Builtins::kWriteImageh:
3326 case Builtins::kWriteImagei:
3327 case Builtins::kWriteImageui: {
3328 // write_image is mapped to OpImageWrite.
3329 //
3330 // Generate OpImageWrite.
3331 //
3332 // Ops[0] = Image ID
3333 // Ops[1] = Coordinate ID
3334 // Ops[2] = Texel ID
3335 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3336 // Ops[4] ... Ops[n] = (Optional) Operands ID
3337 //
3338 SPIRVOperandVec Ops;
3339
3340 Value *Image = Call->getArgOperand(0);
3341 Value *Coordinate = Call->getArgOperand(1);
3342 Value *Texel = Call->getArgOperand(2);
3343
3344 SPIRVID TexelID = getSPIRVValue(Texel);
3345
3346 const bool is_int_image = IsIntImageType(Image->getType());
3347 if (is_int_image) {
3348 // Generate a bitcast to v4int and use it as the texel value.
3349 Ops << v4int32ID << TexelID;
3350 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3351 Ops.clear();
3352 }
3353 Ops << Image << Coordinate << TexelID;
3354
3355 RID = addSPIRVInst(spv::OpImageWrite, Ops);
3356 break;
3357 }
3358
3359 case Builtins::kGetImageHeight:
3360 case Builtins::kGetImageWidth:
3361 case Builtins::kGetImageDepth:
3362 case Builtins::kGetImageDim: {
3363 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3364 addCapability(spv::CapabilityImageQuery);
3365
3366 //
3367 // Generate OpImageQuerySize[Lod]
3368 //
3369 // Ops[0] = Image ID
3370 //
3371 // Result type has components equal to the dimensionality of the image,
3372 // plus 1 if the image is arrayed.
3373 //
3374 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3375 SPIRVOperandVec Ops;
3376
3377 // Implement:
3378 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3379 SPIRVID SizesTypeID;
3380
3381 Value *Image = Call->getArgOperand(0);
3382 const uint32_t dim = ImageDimensionality(Image->getType());
3383 const uint32_t components =
3384 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3385 if (components == 1) {
3386 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3387 } else {
3388 SizesTypeID = getSPIRVType(
3389 FixedVectorType::get(Type::getInt32Ty(Context), components));
3390 }
3391 Ops << SizesTypeID << Image;
3392 spv::Op query_opcode = spv::OpImageQuerySize;
3393 if (IsSampledImageType(Image->getType())) {
3394 query_opcode = spv::OpImageQuerySizeLod;
3395 // Need explicit 0 for Lod operand.
3396 Ops << getSPIRVInt32Constant(0);
3397 }
3398
3399 RID = addSPIRVInst(query_opcode, Ops);
3400
3401 // May require an extra instruction to create the appropriate result of
3402 // the builtin function.
3403 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3404 if (dim == 3) {
3405 // get_image_dim returns an int4 for 3D images.
3406 //
3407
3408 // Implement:
3409 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3410 Ops.clear();
3411 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3412 << getSPIRVInt32Constant(0);
3413
3414 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3415 } else if (dim != components) {
3416 // get_image_dim return an int2 regardless of the arrayedness of the
3417 // image. If the image is arrayed an element must be dropped from the
3418 // query result.
3419 //
3420
3421 // Implement:
3422 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3423 Ops.clear();
3424 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3425 << 0 << 1;
3426
3427 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3428 }
3429 } else if (components > 1) {
3430 // Implement:
3431 // %result = OpCompositeExtract %uint %sizes <component number>
3432 Ops.clear();
3433 Ops << Call->getType() << RID;
3434
3435 uint32_t component = 0;
3436 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3437 component = 1;
3438 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3439 component = 2;
3440 Ops << component;
3441
3442 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3443 }
3444 break;
3445 }
3446 default:
3447 llvm_unreachable("Unsupported Image builtin");
3448 }
3449
3450 return RID;
3451}
3452
3453SPIRVID
3454SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3455 const FunctionInfo &FuncInfo) {
3456 SPIRVID RID;
3457
3458 // requires SPIRV version 1.3 or greater
3459 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3460 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3461 // TODO(sjw): error out gracefully
3462 }
3463
3464 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3465 spv::Capability spvCap =
3466 spv::CapabilityGroupNonUniform) {
3467 SPIRVOperandVec Ops;
3468 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3469
3470 return addSPIRVInst(spv::OpLoad, Ops);
3471 };
3472
3473 spv::Op op = spv::OpNop;
3474 switch (FuncInfo.getType()) {
3475 case Builtins::kGetSubGroupSize:
3476 return loadBuiltin(spv::BuiltInSubgroupSize);
3477 case Builtins::kGetNumSubGroups:
3478 return loadBuiltin(spv::BuiltInNumSubgroups);
3479 case Builtins::kGetSubGroupId:
3480 return loadBuiltin(spv::BuiltInSubgroupId);
3481 case Builtins::kGetSubGroupLocalId:
3482 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3483
3484 case Builtins::kSubGroupBroadcast:
3485 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3486 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3487 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3488 "SPIRV version < 1.5");
3489 }
3490 addCapability(spv::CapabilityGroupNonUniformBallot);
3491 op = spv::OpGroupNonUniformBroadcast;
3492 break;
3493
3494 case Builtins::kSubGroupAll:
3495 addCapability(spv::CapabilityGroupNonUniformVote);
3496 op = spv::OpGroupNonUniformAll;
3497 break;
3498 case Builtins::kSubGroupAny:
3499 addCapability(spv::CapabilityGroupNonUniformVote);
3500 op = spv::OpGroupNonUniformAny;
3501 break;
3502 case Builtins::kSubGroupReduceAdd:
3503 case Builtins::kSubGroupScanExclusiveAdd:
3504 case Builtins::kSubGroupScanInclusiveAdd: {
3505 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3506 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3507 op = spv::OpGroupNonUniformIAdd;
3508 } else {
3509 op = spv::OpGroupNonUniformFAdd;
3510 }
3511 break;
3512 }
3513 case Builtins::kSubGroupReduceMin:
3514 case Builtins::kSubGroupScanExclusiveMin:
3515 case Builtins::kSubGroupScanInclusiveMin: {
3516 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3517 auto &param = FuncInfo.getParameter(0);
3518 if (param.type_id == Type::IntegerTyID) {
3519 op = param.is_signed ? spv::OpGroupNonUniformSMin
3520 : spv::OpGroupNonUniformUMin;
3521 } else {
3522 op = spv::OpGroupNonUniformFMin;
3523 }
3524 break;
3525 }
3526 case Builtins::kSubGroupReduceMax:
3527 case Builtins::kSubGroupScanExclusiveMax:
3528 case Builtins::kSubGroupScanInclusiveMax: {
3529 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3530 auto &param = FuncInfo.getParameter(0);
3531 if (param.type_id == Type::IntegerTyID) {
3532 op = param.is_signed ? spv::OpGroupNonUniformSMax
3533 : spv::OpGroupNonUniformUMax;
3534 } else {
3535 op = spv::OpGroupNonUniformFMax;
3536 }
3537 break;
3538 }
3539
3540 case Builtins::kGetEnqueuedNumSubGroups:
3541 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3542 case Builtins::kGetMaxSubGroupSize:
3543 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3544 case Builtins::kSubGroupBarrier:
3545 case Builtins::kSubGroupReserveReadPipe:
3546 case Builtins::kSubGroupReserveWritePipe:
3547 case Builtins::kSubGroupCommitReadPipe:
3548 case Builtins::kSubGroupCommitWritePipe:
3549 case Builtins::kGetKernelSubGroupCountForNdrange:
3550 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3551 default:
3552 Call->print(errs());
3553 llvm_unreachable("Unsupported sub_group operation");
3554 break;
3555 }
3556
3557 assert(op != spv::OpNop);
3558
3559 SPIRVOperandVec Operands;
3560
3561 //
3562 // Generate OpGroupNonUniform*
3563 //
3564 // Ops[0] = Result Type ID
3565 // Ops[1] = ScopeSubgroup
3566 // Ops[2] = Value ID
3567 // Ops[3] = Local ID
3568
3569 // The result type.
3570 Operands << Call->getType();
3571
3572 // Subgroup Scope
3573 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3574
3575 switch (FuncInfo.getType()) {
3576 case Builtins::kSubGroupReduceAdd:
3577 case Builtins::kSubGroupReduceMin:
3578 case Builtins::kSubGroupReduceMax:
3579 Operands << spv::GroupOperationReduce;
3580 break;
3581 case Builtins::kSubGroupScanExclusiveAdd:
3582 case Builtins::kSubGroupScanExclusiveMin:
3583 case Builtins::kSubGroupScanExclusiveMax:
3584 Operands << spv::GroupOperationExclusiveScan;
3585 break;
3586 case Builtins::kSubGroupScanInclusiveAdd:
3587 case Builtins::kSubGroupScanInclusiveMin:
3588 case Builtins::kSubGroupScanInclusiveMax:
3589 Operands << spv::GroupOperationInclusiveScan;
3590 break;
3591 default:
3592 break;
3593 }
3594
3595 for (Use &use : Call->arg_operands()) {
3596 Operands << use.get();
3597 }
3598
3599 return addSPIRVInst(op, Operands);
3600}
3601
3602SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3603 LLVMContext &Context = module->getContext();
3604
3605 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3606 auto func_type = func_info.getType();
3607
3608 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3609 return GenerateClspvInstruction(Call, func_info);
3610 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3611 return GenerateImageInstruction(Call, func_info);
3612 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3613 return GenerateSubgroupInstruction(Call, func_info);
3614 }
3615
3616 SPIRVID RID;
3617
3618 switch (func_type) {
3619 case Builtins::kPopcount: {
3620 //
3621 // Generate OpBitCount
3622 //
3623 // Ops[0] = Result Type ID
3624 // Ops[1] = Base ID
3625 SPIRVOperandVec Ops;
3626 Ops << Call->getType() << Call->getOperand(0);
3627
3628 RID = addSPIRVInst(spv::OpBitCount, Ops);
3629 break;
3630 }
3631 default: {
3632 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3633
3634 if (EInst) {
3635 SPIRVID ExtInstImportID = getOpExtInstImportID();
3636
3637 //
3638 // Generate OpExtInst.
3639 //
3640
3641 // Ops[0] = Result Type ID
3642 // Ops[1] = Set ID (OpExtInstImport ID)
3643 // Ops[2] = Instruction Number (Literal Number)
3644 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3645 SPIRVOperandVec Ops;
3646
3647 Ops << Call->getType() << ExtInstImportID << EInst;
3648
3649 for (auto &use : Call->arg_operands()) {
3650 Ops << use.get();
3651 }
3652
3653 RID = addSPIRVInst(spv::OpExtInst, Ops);
3654
3655 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3656 if (IndirectExtInst != kGlslExtInstBad) {
3657
3658 // Generate one more instruction that uses the result of the extended
3659 // instruction. Its result id is one more than the id of the
3660 // extended instruction.
3661 auto generate_extra_inst = [this, &Context, &Call,
3662 &RID](spv::Op opcode, Constant *constant) {
3663 //
3664 // Generate instruction like:
3665 // result = opcode constant <extinst-result>
3666 //
3667 // Ops[0] = Result Type ID
3668 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3669 // Ops[2] = Operand 1 ;; the result of the extended instruction
3670 SPIRVOperandVec Ops;
3671
3672 Type *resultTy = Call->getType();
3673
3674 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003675 constant =
3676 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003677 }
3678 Ops << resultTy << constant << RID;
3679
3680 RID = addSPIRVInst(opcode, Ops);
3681 };
3682
3683 auto IntTy = Type::getInt32Ty(Context);
3684 switch (IndirectExtInst) {
3685 case glsl::ExtInstFindUMsb: // Implementing clz
3686 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
3687 break;
3688 case glsl::ExtInstAcos: // Implementing acospi
3689 case glsl::ExtInstAsin: // Implementing asinpi
3690 case glsl::ExtInstAtan: // Implementing atanpi
3691 case glsl::ExtInstAtan2: // Implementing atan2pi
3692 generate_extra_inst(
3693 spv::OpFMul,
3694 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
3695 break;
3696
3697 default:
3698 assert(false && "internally inconsistent");
3699 }
3700 }
3701 } else {
3702
3703 // A real function call (not builtin)
3704 // Call instruction is deferred because it needs function's ID.
3705 RID = addSPIRVPlaceholder(Call);
3706 }
3707
3708 break;
3709 }
3710 }
3711
3712 return RID;
3713}
3714
David Neto22f144c2017-06-12 14:26:21 -04003715void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003716 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003717 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003718
SJW806a5d82020-07-15 12:51:38 -05003719 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003720
3721 switch (I.getOpcode()) {
3722 default: {
3723 if (Instruction::isCast(I.getOpcode())) {
3724 //
3725 // Generate SPIRV instructions for cast operators.
3726 //
3727
David Netod2de94a2017-08-28 17:27:47 -04003728 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003729 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003730 auto toI8 = Ty == Type::getInt8Ty(Context);
3731 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003732 // Handle zext, sext and uitofp with i1 type specially.
3733 if ((I.getOpcode() == Instruction::ZExt ||
3734 I.getOpcode() == Instruction::SExt ||
3735 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003736 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003737 //
3738 // Generate OpSelect.
3739 //
3740
3741 // Ops[0] = Result Type ID
3742 // Ops[1] = Condition ID
3743 // Ops[2] = True Constant ID
3744 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003745 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003746
SJW01901d92020-05-21 08:58:31 -05003747 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003748
David Neto22f144c2017-06-12 14:26:21 -04003749 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003750 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003751 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003752 Ops << ConstantInt::getSigned(I.getType(), -1);
David Neto22f144c2017-06-12 14:26:21 -04003753 } else {
SJW01901d92020-05-21 08:58:31 -05003754 Ops << ConstantFP::get(Context, APFloat(1.0f));
David Neto22f144c2017-06-12 14:26:21 -04003755 }
David Neto22f144c2017-06-12 14:26:21 -04003756
David Neto22f144c2017-06-12 14:26:21 -04003757 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003758 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003759 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003760 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003761 } else {
SJW01901d92020-05-21 08:58:31 -05003762 Ops << ConstantFP::get(Context, APFloat(0.0f));
David Neto22f144c2017-06-12 14:26:21 -04003763 }
David Neto22f144c2017-06-12 14:26:21 -04003764
SJWf93f5f32020-05-05 07:27:56 -05003765 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003766 } else if (!clspv::Option::Int8Support() &&
3767 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003768 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3769 // 8 bits.
3770 // Before:
3771 // %result = trunc i32 %a to i8
3772 // After
3773 // %result = OpBitwiseAnd %uint %a %uint_255
3774
SJWf93f5f32020-05-05 07:27:56 -05003775 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003776
SJW806a5d82020-07-15 12:51:38 -05003777 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003778
SJWf93f5f32020-05-05 07:27:56 -05003779 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003780 } else {
3781 // Ops[0] = Result Type ID
3782 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003783 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003784
SJW01901d92020-05-21 08:58:31 -05003785 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003786
SJWf93f5f32020-05-05 07:27:56 -05003787 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003788 }
3789 } else if (isa<BinaryOperator>(I)) {
3790 //
3791 // Generate SPIRV instructions for binary operators.
3792 //
3793
3794 // Handle xor with i1 type specially.
3795 if (I.getOpcode() == Instruction::Xor &&
3796 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003797 ((isa<ConstantInt>(I.getOperand(0)) &&
3798 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3799 (isa<ConstantInt>(I.getOperand(1)) &&
3800 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003801 //
3802 // Generate OpLogicalNot.
3803 //
3804 // Ops[0] = Result Type ID
3805 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003806 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003807
SJW01901d92020-05-21 08:58:31 -05003808 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003809
3810 Value *CondV = I.getOperand(0);
3811 if (isa<Constant>(I.getOperand(0))) {
3812 CondV = I.getOperand(1);
3813 }
SJW01901d92020-05-21 08:58:31 -05003814 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003815
SJWf93f5f32020-05-05 07:27:56 -05003816 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003817 } else {
3818 // Ops[0] = Result Type ID
3819 // Ops[1] = Operand 0
3820 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003821 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003822
SJW01901d92020-05-21 08:58:31 -05003823 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003824
SJWf93f5f32020-05-05 07:27:56 -05003825 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003826 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003827 } else if (I.getOpcode() == Instruction::FNeg) {
3828 // The only unary operator.
3829 //
3830 // Ops[0] = Result Type ID
3831 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05003832 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05003833
SJW01901d92020-05-21 08:58:31 -05003834 Ops << I.getType() << I.getOperand(0);
3835 RID = addSPIRVInst(spv::OpFNegate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003836 } else {
3837 I.print(errs());
3838 llvm_unreachable("Unsupported instruction???");
3839 }
3840 break;
3841 }
3842 case Instruction::GetElementPtr: {
3843 auto &GlobalConstArgSet = getGlobalConstArgSet();
3844
3845 //
3846 // Generate OpAccessChain.
3847 //
3848 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3849
3850 //
3851 // Generate OpAccessChain.
3852 //
3853
3854 // Ops[0] = Result Type ID
3855 // Ops[1] = Base ID
3856 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05003857 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003858
alan-bakerb6b09dc2018-11-08 16:59:28 -05003859 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003860 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3861 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3862 // Use pointer type with private address space for global constant.
3863 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003864 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003865 }
David Neto257c3892018-04-11 13:19:45 -04003866
SJW01901d92020-05-21 08:58:31 -05003867 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04003868
David Neto862b7d82018-06-14 18:48:37 -04003869 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05003870 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04003871
David Neto862b7d82018-06-14 18:48:37 -04003872 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003873
3874 //
3875 // Follows below rules for gep.
3876 //
David Neto862b7d82018-06-14 18:48:37 -04003877 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3878 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003879 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3880 // first index.
3881 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3882 // use gep's first index.
3883 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3884 // gep's first index.
3885 //
3886 spv::Op Opcode = spv::OpAccessChain;
3887 unsigned offset = 0;
3888 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003889 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003890 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003891 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003892 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003893 }
David Neto862b7d82018-06-14 18:48:37 -04003894 } else {
David Neto22f144c2017-06-12 14:26:21 -04003895 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003896 }
3897
3898 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003899 // Do we need to generate ArrayStride? Check against the GEP result type
3900 // rather than the pointer type of the base because when indexing into
3901 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3902 // for something else in the SPIR-V.
3903 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003904 auto address_space = ResultType->getAddressSpace();
3905 setVariablePointersCapabilities(address_space);
3906 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003907 case spv::StorageClassStorageBuffer:
3908 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003909 // Save the need to generate an ArrayStride decoration. But defer
3910 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003911 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003912 break;
3913 default:
3914 break;
David Neto1a1a0582017-07-07 12:01:44 -04003915 }
David Neto22f144c2017-06-12 14:26:21 -04003916 }
3917
3918 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05003919 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04003920 }
3921
SJWf93f5f32020-05-05 07:27:56 -05003922 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003923 break;
3924 }
3925 case Instruction::ExtractValue: {
3926 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3927 // Ops[0] = Result Type ID
3928 // Ops[1] = Composite ID
3929 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003930 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003931
SJW01901d92020-05-21 08:58:31 -05003932 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003933
SJW01901d92020-05-21 08:58:31 -05003934 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003935
3936 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003937 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003938 }
3939
SJWf93f5f32020-05-05 07:27:56 -05003940 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003941 break;
3942 }
3943 case Instruction::InsertValue: {
3944 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3945 // Ops[0] = Result Type ID
3946 // Ops[1] = Object ID
3947 // Ops[2] = Composite ID
3948 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05003949 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003950
SJW01901d92020-05-21 08:58:31 -05003951 Ops << I.getType() << IVI->getInsertedValueOperand()
3952 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04003953
3954 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05003955 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04003956 }
3957
SJWf93f5f32020-05-05 07:27:56 -05003958 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003959 break;
3960 }
3961 case Instruction::Select: {
3962 //
3963 // Generate OpSelect.
3964 //
3965
3966 // Ops[0] = Result Type ID
3967 // Ops[1] = Condition ID
3968 // Ops[2] = True Constant ID
3969 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003970 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003971
3972 // Find SPIRV instruction for parameter type.
3973 auto Ty = I.getType();
3974 if (Ty->isPointerTy()) {
3975 auto PointeeTy = Ty->getPointerElementType();
3976 if (PointeeTy->isStructTy() &&
3977 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3978 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003979 } else {
3980 // Selecting between pointers requires variable pointers.
3981 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3982 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05003983 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05003984 }
David Neto22f144c2017-06-12 14:26:21 -04003985 }
3986 }
3987
SJW01901d92020-05-21 08:58:31 -05003988 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04003989
SJWf93f5f32020-05-05 07:27:56 -05003990 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003991 break;
3992 }
3993 case Instruction::ExtractElement: {
3994 // Handle <4 x i8> type manually.
3995 Type *CompositeTy = I.getOperand(0)->getType();
3996 if (is4xi8vec(CompositeTy)) {
3997 //
3998 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3999 // <4 x i8>.
4000 //
4001
4002 //
4003 // Generate OpShiftRightLogical
4004 //
4005 // Ops[0] = Result Type ID
4006 // Ops[1] = Operand 0
4007 // Ops[2] = Operand 1
4008 //
SJWf93f5f32020-05-05 07:27:56 -05004009 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004010
SJW01901d92020-05-21 08:58:31 -05004011 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004012
SJW01901d92020-05-21 08:58:31 -05004013 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004014 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4015 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004016 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4017 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004018 } else {
4019 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004020 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004021
SJW806a5d82020-07-15 12:51:38 -05004022 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4023 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004024
SJWf93f5f32020-05-05 07:27:56 -05004025 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004026 }
SJW01901d92020-05-21 08:58:31 -05004027 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004028
SJW01901d92020-05-21 08:58:31 -05004029 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004030
4031 //
4032 // Generate OpBitwiseAnd
4033 //
4034 // Ops[0] = Result Type ID
4035 // Ops[1] = Operand 0
4036 // Ops[2] = Operand 1
4037 //
4038 Ops.clear();
4039
SJW806a5d82020-07-15 12:51:38 -05004040 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004041
SJWf93f5f32020-05-05 07:27:56 -05004042 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004043 break;
4044 }
4045
4046 // Ops[0] = Result Type ID
4047 // Ops[1] = Composite ID
4048 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004049 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004050
SJW01901d92020-05-21 08:58:31 -05004051 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004052
4053 spv::Op Opcode = spv::OpCompositeExtract;
4054 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004055 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004056 } else {
SJW01901d92020-05-21 08:58:31 -05004057 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004058 Opcode = spv::OpVectorExtractDynamic;
4059 }
4060
SJWf93f5f32020-05-05 07:27:56 -05004061 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004062 break;
4063 }
4064 case Instruction::InsertElement: {
4065 // Handle <4 x i8> type manually.
4066 Type *CompositeTy = I.getOperand(0)->getType();
4067 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004068 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004069
SJW01901d92020-05-21 08:58:31 -05004070 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004071 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4072 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004073 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4074 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004075 } else {
4076 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004077 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004078
SJW806a5d82020-07-15 12:51:38 -05004079 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4080 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004081
SJWf93f5f32020-05-05 07:27:56 -05004082 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004083 }
4084
4085 //
4086 // Generate mask operations.
4087 //
4088
4089 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004090 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004091
SJW01901d92020-05-21 08:58:31 -05004092 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004093
SJW01901d92020-05-21 08:58:31 -05004094 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004095
4096 // Inverse mask.
4097 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004098 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004099
SJW01901d92020-05-21 08:58:31 -05004100 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004101
4102 // Apply mask.
4103 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004104 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004105
SJW01901d92020-05-21 08:58:31 -05004106 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004107
4108 // Create correct value according to index of insertelement.
4109 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004110 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004111
SJW01901d92020-05-21 08:58:31 -05004112 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004113
4114 // Insert value to original value.
4115 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004116 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004117
SJWf93f5f32020-05-05 07:27:56 -05004118 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004119 break;
4120 }
4121
SJWf93f5f32020-05-05 07:27:56 -05004122 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004123
James Priced26efea2018-06-09 23:28:32 +01004124 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004125 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004126
4127 spv::Op Opcode = spv::OpCompositeInsert;
4128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004129 const auto value = CI->getZExtValue();
4130 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004131 // Ops[1] = Object ID
4132 // Ops[2] = Composite ID
4133 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004134 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004135 } else {
James Priced26efea2018-06-09 23:28:32 +01004136 // Ops[1] = Composite ID
4137 // Ops[2] = Object ID
4138 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004139 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004140 Opcode = spv::OpVectorInsertDynamic;
4141 }
4142
SJWf93f5f32020-05-05 07:27:56 -05004143 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004144 break;
4145 }
4146 case Instruction::ShuffleVector: {
4147 // Ops[0] = Result Type ID
4148 // Ops[1] = Vector 1 ID
4149 // Ops[2] = Vector 2 ID
4150 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004151 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004152
SJW01901d92020-05-21 08:58:31 -05004153 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004154
alan-bakerc9666712020-04-01 16:31:21 -04004155 auto shuffle = cast<ShuffleVectorInst>(&I);
4156 SmallVector<int, 4> mask;
4157 shuffle->getShuffleMask(mask);
4158 for (auto i : mask) {
4159 if (i == UndefMaskElem) {
4160 if (clspv::Option::HackUndef())
4161 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004162 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004163 else
4164 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004165 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004166 } else {
SJW01901d92020-05-21 08:58:31 -05004167 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004168 }
4169 }
4170
SJWf93f5f32020-05-05 07:27:56 -05004171 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004172 break;
4173 }
4174 case Instruction::ICmp:
4175 case Instruction::FCmp: {
4176 CmpInst *CmpI = cast<CmpInst>(&I);
4177
David Netod4ca2e62017-07-06 18:47:35 -04004178 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004179 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004180 if (isa<PointerType>(ArgTy)) {
4181 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004182 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004183 errs()
4184 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4185 << "in function " << name << "\n";
4186 llvm_unreachable("Pointer equality check is invalid");
4187 break;
4188 }
4189
David Neto257c3892018-04-11 13:19:45 -04004190 // Ops[0] = Result Type ID
4191 // Ops[1] = Operand 1 ID
4192 // Ops[2] = Operand 2 ID
SJWf93f5f32020-05-05 07:27:56 -05004193 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004194
SJW01901d92020-05-21 08:58:31 -05004195 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004196
4197 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
SJWf93f5f32020-05-05 07:27:56 -05004198 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004199 break;
4200 }
4201 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004202 // Branch instruction is deferred because it needs label's ID.
4203 BasicBlock *BrBB = I.getParent();
4204 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4205 // Placeholder for Merge operation
4206 RID = addSPIRVPlaceholder(&I);
4207 }
4208 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004209 break;
4210 }
4211 case Instruction::Switch: {
4212 I.print(errs());
4213 llvm_unreachable("Unsupported instruction???");
4214 break;
4215 }
4216 case Instruction::IndirectBr: {
4217 I.print(errs());
4218 llvm_unreachable("Unsupported instruction???");
4219 break;
4220 }
4221 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004222 // PHI instruction is deferred because it needs label's ID.
4223 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004224 break;
4225 }
4226 case Instruction::Alloca: {
4227 //
4228 // Generate OpVariable.
4229 //
4230 // Ops[0] : Result Type ID
4231 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004232 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004233
SJW01901d92020-05-21 08:58:31 -05004234 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004235
SJWf93f5f32020-05-05 07:27:56 -05004236 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004237 break;
4238 }
4239 case Instruction::Load: {
4240 LoadInst *LD = cast<LoadInst>(&I);
4241 //
4242 // Generate OpLoad.
4243 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004244
alan-baker5b86ed72019-02-15 08:26:50 -05004245 if (LD->getType()->isPointerTy()) {
4246 // Loading a pointer requires variable pointers.
4247 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4248 }
David Neto22f144c2017-06-12 14:26:21 -04004249
SJW01901d92020-05-21 08:58:31 -05004250 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004251 // This is a hack to work around what looks like a driver bug.
4252 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004253 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4254 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004255 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004256 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004257 // Generate a bitwise-and of the original value with itself.
4258 // We should have been able to get away with just an OpCopyObject,
4259 // but we need something more complex to get past certain driver bugs.
4260 // This is ridiculous, but necessary.
4261 // TODO(dneto): Revisit this once drivers fix their bugs.
4262
SJWf93f5f32020-05-05 07:27:56 -05004263 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004264 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004265
SJWf93f5f32020-05-05 07:27:56 -05004266 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004267 break;
4268 }
4269
4270 // This is the normal path. Generate a load.
4271
David Neto22f144c2017-06-12 14:26:21 -04004272 // Ops[0] = Result Type ID
4273 // Ops[1] = Pointer ID
4274 // Ops[2] ... Ops[n] = Optional Memory Access
4275 //
4276 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004277
SJWf93f5f32020-05-05 07:27:56 -05004278 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004279 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004280
SJWf93f5f32020-05-05 07:27:56 -05004281 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004282 break;
4283 }
4284 case Instruction::Store: {
4285 StoreInst *ST = cast<StoreInst>(&I);
4286 //
4287 // Generate OpStore.
4288 //
4289
alan-baker5b86ed72019-02-15 08:26:50 -05004290 if (ST->getValueOperand()->getType()->isPointerTy()) {
4291 // Storing a pointer requires variable pointers.
4292 setVariablePointersCapabilities(
4293 ST->getValueOperand()->getType()->getPointerAddressSpace());
4294 }
4295
David Neto22f144c2017-06-12 14:26:21 -04004296 // Ops[0] = Pointer ID
4297 // Ops[1] = Object ID
4298 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4299 //
4300 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004301 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004302 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004303
SJWf93f5f32020-05-05 07:27:56 -05004304 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004305 break;
4306 }
4307 case Instruction::AtomicCmpXchg: {
4308 I.print(errs());
4309 llvm_unreachable("Unsupported instruction???");
4310 break;
4311 }
4312 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004313 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4314
4315 spv::Op opcode;
4316
4317 switch (AtomicRMW->getOperation()) {
4318 default:
4319 I.print(errs());
4320 llvm_unreachable("Unsupported instruction???");
4321 case llvm::AtomicRMWInst::Add:
4322 opcode = spv::OpAtomicIAdd;
4323 break;
4324 case llvm::AtomicRMWInst::Sub:
4325 opcode = spv::OpAtomicISub;
4326 break;
4327 case llvm::AtomicRMWInst::Xchg:
4328 opcode = spv::OpAtomicExchange;
4329 break;
4330 case llvm::AtomicRMWInst::Min:
4331 opcode = spv::OpAtomicSMin;
4332 break;
4333 case llvm::AtomicRMWInst::Max:
4334 opcode = spv::OpAtomicSMax;
4335 break;
4336 case llvm::AtomicRMWInst::UMin:
4337 opcode = spv::OpAtomicUMin;
4338 break;
4339 case llvm::AtomicRMWInst::UMax:
4340 opcode = spv::OpAtomicUMax;
4341 break;
4342 case llvm::AtomicRMWInst::And:
4343 opcode = spv::OpAtomicAnd;
4344 break;
4345 case llvm::AtomicRMWInst::Or:
4346 opcode = spv::OpAtomicOr;
4347 break;
4348 case llvm::AtomicRMWInst::Xor:
4349 opcode = spv::OpAtomicXor;
4350 break;
4351 }
4352
4353 //
4354 // Generate OpAtomic*.
4355 //
SJWf93f5f32020-05-05 07:27:56 -05004356 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004357
SJW01901d92020-05-21 08:58:31 -05004358 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004359
SJW806a5d82020-07-15 12:51:38 -05004360 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004361 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004362
SJW806a5d82020-07-15 12:51:38 -05004363 const auto ConstantMemorySemantics =
4364 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4365 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004366 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004367
SJWf93f5f32020-05-05 07:27:56 -05004368 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004369 break;
4370 }
4371 case Instruction::Fence: {
4372 I.print(errs());
4373 llvm_unreachable("Unsupported instruction???");
4374 break;
4375 }
4376 case Instruction::Call: {
4377 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004378 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004379 break;
4380 }
4381 case Instruction::Ret: {
4382 unsigned NumOps = I.getNumOperands();
4383 if (NumOps == 0) {
4384 //
4385 // Generate OpReturn.
4386 //
SJWf93f5f32020-05-05 07:27:56 -05004387 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004388 } else {
4389 //
4390 // Generate OpReturnValue.
4391 //
4392
4393 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004394 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004395
SJW01901d92020-05-21 08:58:31 -05004396 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004397
SJWf93f5f32020-05-05 07:27:56 -05004398 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004399 break;
4400 }
4401 break;
4402 }
4403 }
SJWf93f5f32020-05-05 07:27:56 -05004404
4405 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004406 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004407 VMap[&I] = RID;
4408 }
David Neto22f144c2017-06-12 14:26:21 -04004409}
4410
4411void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004412
4413 //
4414 // Generate OpFunctionEnd
4415 //
SJWf93f5f32020-05-05 07:27:56 -05004416 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004417}
4418
4419bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004420 // Don't specialize <4 x i8> if i8 is generally supported.
4421 if (clspv::Option::Int8Support())
4422 return false;
4423
David Neto22f144c2017-06-12 14:26:21 -04004424 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004425 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4426 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
4427 VecTy->getNumElements() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004428 return true;
4429 }
4430 }
4431
4432 return false;
4433}
4434
4435void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004436 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4437
SJW88ed5fe2020-05-11 12:40:57 -05004438 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4439 Value *Inst = DeferredInsts[i].first;
4440 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4441 SPIRVOperandVec Operands;
4442
4443 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4444 ++i;
4445 assert(DeferredInsts.size() > i);
4446 assert(Inst == DeferredInsts[i].first);
4447 Placeholder = DeferredInsts[i].second;
4448 };
David Neto22f144c2017-06-12 14:26:21 -04004449
4450 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004451 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004452 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004453 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004454 //
4455 // Generate OpLoopMerge.
4456 //
4457 // Ops[0] = Merge Block ID
4458 // Ops[1] = Continue Target ID
4459 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004460 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004461
SJW01901d92020-05-21 08:58:31 -05004462 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4463 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004464
SJW88ed5fe2020-05-11 12:40:57 -05004465 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4466
4467 nextDeferred();
4468
alan-baker06cad652019-12-03 17:56:47 -05004469 } else if (MergeBlocks.count(BrBB)) {
4470 //
4471 // Generate OpSelectionMerge.
4472 //
4473 // Ops[0] = Merge Block ID
4474 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004475 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004476
alan-baker06cad652019-12-03 17:56:47 -05004477 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004478 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004479
SJW88ed5fe2020-05-11 12:40:57 -05004480 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4481
4482 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004483 }
4484
4485 if (Br->isConditional()) {
4486 //
4487 // Generate OpBranchConditional.
4488 //
4489 // Ops[0] = Condition ID
4490 // Ops[1] = True Label ID
4491 // Ops[2] = False Label ID
4492 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004493 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004494
SJW01901d92020-05-21 08:58:31 -05004495 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004496
SJW88ed5fe2020-05-11 12:40:57 -05004497 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4498
David Neto22f144c2017-06-12 14:26:21 -04004499 } else {
4500 //
4501 // Generate OpBranch.
4502 //
4503 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004504 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004505
SJW01901d92020-05-21 08:58:31 -05004506 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004507
SJW88ed5fe2020-05-11 12:40:57 -05004508 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004509 }
4510 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004511 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4512 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004513 // OpPhi on pointers requires variable pointers.
4514 setVariablePointersCapabilities(
4515 PHI->getType()->getPointerAddressSpace());
4516 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004517 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004518 }
4519 }
4520
David Neto22f144c2017-06-12 14:26:21 -04004521 //
4522 // Generate OpPhi.
4523 //
4524 // Ops[0] = Result Type ID
4525 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004526 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004527
SJW01901d92020-05-21 08:58:31 -05004528 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004529
SJW88ed5fe2020-05-11 12:40:57 -05004530 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004531 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004532 }
4533
SJW88ed5fe2020-05-11 12:40:57 -05004534 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4535
David Neto22f144c2017-06-12 14:26:21 -04004536 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4537 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004538 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004539
SJW61531372020-06-09 07:31:08 -05004540 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004541
4542 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004543 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004544
4545 // The result type.
SJW01901d92020-05-21 08:58:31 -05004546 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004547
4548 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004549 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004550 }
4551
SJW88ed5fe2020-05-11 12:40:57 -05004552 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004553
David Neto22f144c2017-06-12 14:26:21 -04004554 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004555 if (Call->getType()->isPointerTy()) {
4556 // Functions returning pointers require variable pointers.
4557 setVariablePointersCapabilities(
4558 Call->getType()->getPointerAddressSpace());
4559 }
4560
David Neto22f144c2017-06-12 14:26:21 -04004561 //
4562 // Generate OpFunctionCall.
4563 //
4564
4565 // Ops[0] = Result Type ID
4566 // Ops[1] = Callee Function ID
4567 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004568 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004569
SJW01901d92020-05-21 08:58:31 -05004570 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004571
SJW01901d92020-05-21 08:58:31 -05004572 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004573 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004574 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004575 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004576 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4577 // causes an infinite loop. Instead, go ahead and generate
4578 // the bad function call. A validator will catch the 0-Id.
4579 // llvm_unreachable("Can't translate function call");
4580 }
David Neto22f144c2017-06-12 14:26:21 -04004581
SJW01901d92020-05-21 08:58:31 -05004582 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004583
David Neto22f144c2017-06-12 14:26:21 -04004584 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004585 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4586 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004587 auto *operand_type = operand->getType();
4588 // Images and samplers can be passed as function parameters without
4589 // variable pointers.
4590 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4591 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004592 auto sc =
4593 GetStorageClass(operand->getType()->getPointerAddressSpace());
4594 if (sc == spv::StorageClassStorageBuffer) {
4595 // Passing SSBO by reference requires variable pointers storage
4596 // buffer.
SJW01901d92020-05-21 08:58:31 -05004597 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004598 } else if (sc == spv::StorageClassWorkgroup) {
4599 // Workgroup references require variable pointers if they are not
4600 // memory object declarations.
4601 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4602 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004603 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4604 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004605 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004606 } else {
4607 // Arguments are function parameters.
4608 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004609 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004610 }
4611 }
4612 }
SJW01901d92020-05-21 08:58:31 -05004613 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004614 }
4615
SJW88ed5fe2020-05-11 12:40:57 -05004616 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004617 }
4618 }
4619 }
4620}
4621
SJW77b87ad2020-04-21 14:37:52 -05004622void SPIRVProducerPass::HandleDeferredDecorations() {
4623 const auto &DL = module->getDataLayout();
Alan Baker202c8c72018-08-13 13:47:44 -04004624 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004625 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004626 }
David Neto1a1a0582017-07-07 12:01:44 -04004627
David Netoc6f3ab22018-04-06 18:02:31 -04004628 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4629 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07004630 for (auto *type : getTypesNeedingArrayStride()) {
4631 Type *elemTy = nullptr;
4632 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4633 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004634 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004635 elemTy = arrayTy->getElementType();
4636 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4637 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004638 } else {
4639 errs() << "Unhandled strided type " << *type << "\n";
4640 llvm_unreachable("Unhandled strided type");
4641 }
David Neto1a1a0582017-07-07 12:01:44 -04004642
4643 // Ops[0] = Target ID
4644 // Ops[1] = Decoration (ArrayStride)
4645 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004646 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004647
David Neto85082642018-03-24 06:55:20 -07004648 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004649 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004650
SJW01901d92020-05-21 08:58:31 -05004651 Ops << type << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004652
SJWf93f5f32020-05-05 07:27:56 -05004653 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004654 }
David Neto1a1a0582017-07-07 12:01:44 -04004655}
4656
SJW61531372020-06-09 07:31:08 -05004657glsl::ExtInst
4658SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW2c317da2020-03-23 07:39:13 -05004659
SJW61531372020-06-09 07:31:08 -05004660 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004661 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004662 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004663 if (param_type.type_id == Type::FloatTyID) {
4664 return glsl::ExtInst::ExtInstFClamp;
4665 }
4666 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4667 : glsl::ExtInst::ExtInstUClamp;
4668 }
4669 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004670 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004671 if (param_type.type_id == Type::FloatTyID) {
4672 return glsl::ExtInst::ExtInstFMax;
4673 }
4674 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4675 : glsl::ExtInst::ExtInstUMax;
4676 }
4677 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004678 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004679 if (param_type.type_id == Type::FloatTyID) {
4680 return glsl::ExtInst::ExtInstFMin;
4681 }
4682 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4683 : glsl::ExtInst::ExtInstUMin;
4684 }
4685 case Builtins::kAbs:
4686 return glsl::ExtInst::ExtInstSAbs;
4687 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004688 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004689 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004690 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004691 case Builtins::kDegrees:
4692 return glsl::ExtInst::ExtInstDegrees;
4693 case Builtins::kRadians:
4694 return glsl::ExtInst::ExtInstRadians;
4695 case Builtins::kMix:
4696 return glsl::ExtInst::ExtInstFMix;
4697 case Builtins::kAcos:
4698 case Builtins::kAcospi:
4699 return glsl::ExtInst::ExtInstAcos;
4700 case Builtins::kAcosh:
4701 return glsl::ExtInst::ExtInstAcosh;
4702 case Builtins::kAsin:
4703 case Builtins::kAsinpi:
4704 return glsl::ExtInst::ExtInstAsin;
4705 case Builtins::kAsinh:
4706 return glsl::ExtInst::ExtInstAsinh;
4707 case Builtins::kAtan:
4708 case Builtins::kAtanpi:
4709 return glsl::ExtInst::ExtInstAtan;
4710 case Builtins::kAtanh:
4711 return glsl::ExtInst::ExtInstAtanh;
4712 case Builtins::kAtan2:
4713 case Builtins::kAtan2pi:
4714 return glsl::ExtInst::ExtInstAtan2;
4715 case Builtins::kCeil:
4716 return glsl::ExtInst::ExtInstCeil;
4717 case Builtins::kSin:
4718 case Builtins::kHalfSin:
4719 case Builtins::kNativeSin:
4720 return glsl::ExtInst::ExtInstSin;
4721 case Builtins::kSinh:
4722 return glsl::ExtInst::ExtInstSinh;
4723 case Builtins::kCos:
4724 case Builtins::kHalfCos:
4725 case Builtins::kNativeCos:
4726 return glsl::ExtInst::ExtInstCos;
4727 case Builtins::kCosh:
4728 return glsl::ExtInst::ExtInstCosh;
4729 case Builtins::kTan:
4730 case Builtins::kHalfTan:
4731 case Builtins::kNativeTan:
4732 return glsl::ExtInst::ExtInstTan;
4733 case Builtins::kTanh:
4734 return glsl::ExtInst::ExtInstTanh;
4735 case Builtins::kExp:
4736 case Builtins::kHalfExp:
4737 case Builtins::kNativeExp:
4738 return glsl::ExtInst::ExtInstExp;
4739 case Builtins::kExp2:
4740 case Builtins::kHalfExp2:
4741 case Builtins::kNativeExp2:
4742 return glsl::ExtInst::ExtInstExp2;
4743 case Builtins::kLog:
4744 case Builtins::kHalfLog:
4745 case Builtins::kNativeLog:
4746 return glsl::ExtInst::ExtInstLog;
4747 case Builtins::kLog2:
4748 case Builtins::kHalfLog2:
4749 case Builtins::kNativeLog2:
4750 return glsl::ExtInst::ExtInstLog2;
4751 case Builtins::kFabs:
4752 return glsl::ExtInst::ExtInstFAbs;
4753 case Builtins::kFma:
4754 return glsl::ExtInst::ExtInstFma;
4755 case Builtins::kFloor:
4756 return glsl::ExtInst::ExtInstFloor;
4757 case Builtins::kLdexp:
4758 return glsl::ExtInst::ExtInstLdexp;
4759 case Builtins::kPow:
4760 case Builtins::kPowr:
4761 case Builtins::kHalfPowr:
4762 case Builtins::kNativePowr:
4763 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04004764 case Builtins::kRint:
4765 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05004766 case Builtins::kRound:
4767 return glsl::ExtInst::ExtInstRound;
4768 case Builtins::kSqrt:
4769 case Builtins::kHalfSqrt:
4770 case Builtins::kNativeSqrt:
4771 return glsl::ExtInst::ExtInstSqrt;
4772 case Builtins::kRsqrt:
4773 case Builtins::kHalfRsqrt:
4774 case Builtins::kNativeRsqrt:
4775 return glsl::ExtInst::ExtInstInverseSqrt;
4776 case Builtins::kTrunc:
4777 return glsl::ExtInst::ExtInstTrunc;
4778 case Builtins::kFrexp:
4779 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004780 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004781 case Builtins::kFract:
4782 return glsl::ExtInst::ExtInstFract;
4783 case Builtins::kSign:
4784 return glsl::ExtInst::ExtInstFSign;
4785 case Builtins::kLength:
4786 case Builtins::kFastLength:
4787 return glsl::ExtInst::ExtInstLength;
4788 case Builtins::kDistance:
4789 case Builtins::kFastDistance:
4790 return glsl::ExtInst::ExtInstDistance;
4791 case Builtins::kStep:
4792 return glsl::ExtInst::ExtInstStep;
4793 case Builtins::kSmoothstep:
4794 return glsl::ExtInst::ExtInstSmoothStep;
4795 case Builtins::kCross:
4796 return glsl::ExtInst::ExtInstCross;
4797 case Builtins::kNormalize:
4798 case Builtins::kFastNormalize:
4799 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004800 case Builtins::kSpirvPack:
4801 return glsl::ExtInst::ExtInstPackHalf2x16;
4802 case Builtins::kSpirvUnpack:
4803 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004804 default:
4805 break;
4806 }
4807
SJW61531372020-06-09 07:31:08 -05004808 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4809 return glsl::ExtInst::ExtInstFma;
4810 }
4811 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004812}
4813
SJW61531372020-06-09 07:31:08 -05004814glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4815 const Builtins::FunctionInfo &func_info) {
4816 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004817 case Builtins::kClz:
4818 return glsl::ExtInst::ExtInstFindUMsb;
4819 case Builtins::kAcospi:
4820 return glsl::ExtInst::ExtInstAcos;
4821 case Builtins::kAsinpi:
4822 return glsl::ExtInst::ExtInstAsin;
4823 case Builtins::kAtanpi:
4824 return glsl::ExtInst::ExtInstAtan;
4825 case Builtins::kAtan2pi:
4826 return glsl::ExtInst::ExtInstAtan2;
4827 default:
4828 break;
4829 }
4830 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004831}
4832
SJW61531372020-06-09 07:31:08 -05004833glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
4834 const Builtins::FunctionInfo &func_info) {
4835 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04004836 if (direct != kGlslExtInstBad)
4837 return direct;
SJW61531372020-06-09 07:31:08 -05004838 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04004839}
4840
David Neto22f144c2017-06-12 14:26:21 -04004841void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04004842 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04004843}
4844
SJW88ed5fe2020-05-11 12:40:57 -05004845void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05004846 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04004847}
4848
SJW88ed5fe2020-05-11 12:40:57 -05004849void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04004850 // High 16 bit : Word Count
4851 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05004852 uint32_t Word = Inst.getOpcode();
4853 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04004854 if (count > 65535) {
4855 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
4856 llvm_unreachable("Word count too high");
4857 }
SJW88ed5fe2020-05-11 12:40:57 -05004858 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04004859 WriteOneWord(Word);
4860}
4861
SJW88ed5fe2020-05-11 12:40:57 -05004862void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
4863 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04004864 switch (OpTy) {
4865 default: {
4866 llvm_unreachable("Unsupported SPIRV Operand Type???");
4867 break;
4868 }
4869 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05004870 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04004871 break;
4872 }
4873 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05004874 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04004875 const char *Data = Str.c_str();
4876 size_t WordSize = Str.size() / 4;
4877 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
4878 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
4879 }
4880
4881 uint32_t Remainder = Str.size() % 4;
4882 uint32_t LastWord = 0;
4883 if (Remainder) {
4884 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
4885 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
4886 }
4887 }
4888
4889 WriteOneWord(LastWord);
4890 break;
4891 }
SJW88ed5fe2020-05-11 12:40:57 -05004892 case SPIRVOperandType::LITERAL_WORD: {
4893 WriteOneWord(Op.getLiteralNum()[0]);
4894 break;
4895 }
4896 case SPIRVOperandType::LITERAL_DWORD: {
4897 WriteOneWord(Op.getLiteralNum()[0]);
4898 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04004899 break;
4900 }
4901 }
4902}
4903
4904void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05004905 for (int i = 0; i < kSectionCount; ++i) {
4906 WriteSPIRVBinary(SPIRVSections[i]);
4907 }
4908}
4909
4910void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04004911
SJW88ed5fe2020-05-11 12:40:57 -05004912 for (const auto &Inst : SPIRVInstList) {
4913 const auto &Ops = Inst.getOperands();
4914 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04004915
4916 switch (Opcode) {
4917 default: {
David Neto5c22a252018-03-15 16:07:41 -04004918 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04004919 llvm_unreachable("Unsupported SPIRV instruction");
4920 break;
4921 }
4922 case spv::OpCapability:
4923 case spv::OpExtension:
4924 case spv::OpMemoryModel:
4925 case spv::OpEntryPoint:
4926 case spv::OpExecutionMode:
4927 case spv::OpSource:
4928 case spv::OpDecorate:
4929 case spv::OpMemberDecorate:
4930 case spv::OpBranch:
4931 case spv::OpBranchConditional:
4932 case spv::OpSelectionMerge:
4933 case spv::OpLoopMerge:
4934 case spv::OpStore:
4935 case spv::OpImageWrite:
4936 case spv::OpReturnValue:
4937 case spv::OpControlBarrier:
4938 case spv::OpMemoryBarrier:
4939 case spv::OpReturn:
4940 case spv::OpFunctionEnd:
4941 case spv::OpCopyMemory: {
4942 WriteWordCountAndOpcode(Inst);
4943 for (uint32_t i = 0; i < Ops.size(); i++) {
4944 WriteOperand(Ops[i]);
4945 }
4946 break;
4947 }
4948 case spv::OpTypeBool:
4949 case spv::OpTypeVoid:
4950 case spv::OpTypeSampler:
4951 case spv::OpLabel:
4952 case spv::OpExtInstImport:
4953 case spv::OpTypePointer:
4954 case spv::OpTypeRuntimeArray:
4955 case spv::OpTypeStruct:
4956 case spv::OpTypeImage:
4957 case spv::OpTypeSampledImage:
4958 case spv::OpTypeInt:
4959 case spv::OpTypeFloat:
4960 case spv::OpTypeArray:
4961 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04004962 case spv::OpTypeFunction:
4963 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04004964 WriteWordCountAndOpcode(Inst);
4965 WriteResultID(Inst);
4966 for (uint32_t i = 0; i < Ops.size(); i++) {
4967 WriteOperand(Ops[i]);
4968 }
4969 break;
4970 }
4971 case spv::OpFunction:
4972 case spv::OpFunctionParameter:
4973 case spv::OpAccessChain:
4974 case spv::OpPtrAccessChain:
4975 case spv::OpInBoundsAccessChain:
4976 case spv::OpUConvert:
4977 case spv::OpSConvert:
4978 case spv::OpConvertFToU:
4979 case spv::OpConvertFToS:
4980 case spv::OpConvertUToF:
4981 case spv::OpConvertSToF:
4982 case spv::OpFConvert:
4983 case spv::OpConvertPtrToU:
4984 case spv::OpConvertUToPtr:
4985 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05004986 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04004987 case spv::OpIAdd:
4988 case spv::OpFAdd:
4989 case spv::OpISub:
4990 case spv::OpFSub:
4991 case spv::OpIMul:
4992 case spv::OpFMul:
4993 case spv::OpUDiv:
4994 case spv::OpSDiv:
4995 case spv::OpFDiv:
4996 case spv::OpUMod:
4997 case spv::OpSRem:
4998 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00004999 case spv::OpUMulExtended:
5000 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005001 case spv::OpBitwiseOr:
5002 case spv::OpBitwiseXor:
5003 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005004 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005005 case spv::OpShiftLeftLogical:
5006 case spv::OpShiftRightLogical:
5007 case spv::OpShiftRightArithmetic:
5008 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005009 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005010 case spv::OpCompositeExtract:
5011 case spv::OpVectorExtractDynamic:
5012 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005013 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005014 case spv::OpVectorInsertDynamic:
5015 case spv::OpVectorShuffle:
5016 case spv::OpIEqual:
5017 case spv::OpINotEqual:
5018 case spv::OpUGreaterThan:
5019 case spv::OpUGreaterThanEqual:
5020 case spv::OpULessThan:
5021 case spv::OpULessThanEqual:
5022 case spv::OpSGreaterThan:
5023 case spv::OpSGreaterThanEqual:
5024 case spv::OpSLessThan:
5025 case spv::OpSLessThanEqual:
5026 case spv::OpFOrdEqual:
5027 case spv::OpFOrdGreaterThan:
5028 case spv::OpFOrdGreaterThanEqual:
5029 case spv::OpFOrdLessThan:
5030 case spv::OpFOrdLessThanEqual:
5031 case spv::OpFOrdNotEqual:
5032 case spv::OpFUnordEqual:
5033 case spv::OpFUnordGreaterThan:
5034 case spv::OpFUnordGreaterThanEqual:
5035 case spv::OpFUnordLessThan:
5036 case spv::OpFUnordLessThanEqual:
5037 case spv::OpFUnordNotEqual:
5038 case spv::OpExtInst:
5039 case spv::OpIsInf:
5040 case spv::OpIsNan:
5041 case spv::OpAny:
5042 case spv::OpAll:
5043 case spv::OpUndef:
5044 case spv::OpConstantNull:
5045 case spv::OpLogicalOr:
5046 case spv::OpLogicalAnd:
5047 case spv::OpLogicalNot:
5048 case spv::OpLogicalNotEqual:
5049 case spv::OpConstantComposite:
5050 case spv::OpSpecConstantComposite:
5051 case spv::OpConstantTrue:
5052 case spv::OpConstantFalse:
5053 case spv::OpConstant:
5054 case spv::OpSpecConstant:
5055 case spv::OpVariable:
5056 case spv::OpFunctionCall:
5057 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005058 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04005059 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005060 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005061 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005062 case spv::OpSelect:
5063 case spv::OpPhi:
5064 case spv::OpLoad:
5065 case spv::OpAtomicIAdd:
5066 case spv::OpAtomicISub:
5067 case spv::OpAtomicExchange:
5068 case spv::OpAtomicIIncrement:
5069 case spv::OpAtomicIDecrement:
5070 case spv::OpAtomicCompareExchange:
5071 case spv::OpAtomicUMin:
5072 case spv::OpAtomicSMin:
5073 case spv::OpAtomicUMax:
5074 case spv::OpAtomicSMax:
5075 case spv::OpAtomicAnd:
5076 case spv::OpAtomicOr:
5077 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005078 case spv::OpDot:
5079 case spv::OpGroupNonUniformAll:
5080 case spv::OpGroupNonUniformAny:
5081 case spv::OpGroupNonUniformBroadcast:
5082 case spv::OpGroupNonUniformIAdd:
5083 case spv::OpGroupNonUniformFAdd:
5084 case spv::OpGroupNonUniformSMin:
5085 case spv::OpGroupNonUniformUMin:
5086 case spv::OpGroupNonUniformFMin:
5087 case spv::OpGroupNonUniformSMax:
5088 case spv::OpGroupNonUniformUMax:
5089 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005090 WriteWordCountAndOpcode(Inst);
5091 WriteOperand(Ops[0]);
5092 WriteResultID(Inst);
5093 for (uint32_t i = 1; i < Ops.size(); i++) {
5094 WriteOperand(Ops[i]);
5095 }
5096 break;
5097 }
5098 }
5099 }
5100}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005101
alan-bakerb6b09dc2018-11-08 16:59:28 -05005102bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005103 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005104 case Type::HalfTyID:
5105 case Type::FloatTyID:
5106 case Type::DoubleTyID:
5107 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005108 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005109 return true;
5110 case Type::PointerTyID: {
5111 const PointerType *pointer_type = cast<PointerType>(type);
5112 if (pointer_type->getPointerAddressSpace() !=
5113 AddressSpace::UniformConstant) {
5114 auto pointee_type = pointer_type->getPointerElementType();
5115 if (pointee_type->isStructTy() &&
5116 cast<StructType>(pointee_type)->isOpaque()) {
5117 // Images and samplers are not nullable.
5118 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005119 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005120 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005121 return true;
5122 }
5123 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005124 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005125 case Type::StructTyID: {
5126 const StructType *struct_type = cast<StructType>(type);
5127 // Images and samplers are not nullable.
5128 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005129 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005130 for (const auto element : struct_type->elements()) {
5131 if (!IsTypeNullable(element))
5132 return false;
5133 }
5134 return true;
5135 }
5136 default:
5137 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005138 }
5139}
Alan Bakerfcda9482018-10-02 17:09:59 -04005140
SJW77b87ad2020-04-21 14:37:52 -05005141void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005142 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005143 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005144 // Metdata is stored as key-value pair operands. The first element of each
5145 // operand is the type and the second is a vector of offsets.
5146 for (const auto *operand : offsets_md->operands()) {
5147 const auto *pair = cast<MDTuple>(operand);
5148 auto *type =
5149 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5150 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5151 std::vector<uint32_t> offsets;
5152 for (const Metadata *offset_md : offset_vector->operands()) {
5153 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005154 offsets.push_back(static_cast<uint32_t>(
5155 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005156 }
5157 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5158 }
5159 }
5160
5161 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005162 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005163 // Metadata is stored as key-value pair operands. The first element of each
5164 // operand is the type and the second is a triple of sizes: type size in
5165 // bits, store size and alloc size.
5166 for (const auto *operand : sizes_md->operands()) {
5167 const auto *pair = cast<MDTuple>(operand);
5168 auto *type =
5169 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5170 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5171 uint64_t type_size_in_bits =
5172 cast<ConstantInt>(
5173 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5174 ->getZExtValue();
5175 uint64_t type_store_size =
5176 cast<ConstantInt>(
5177 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5178 ->getZExtValue();
5179 uint64_t type_alloc_size =
5180 cast<ConstantInt>(
5181 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5182 ->getZExtValue();
5183 RemappedUBOTypeSizes.insert(std::make_pair(
5184 type, std::make_tuple(type_size_in_bits, type_store_size,
5185 type_alloc_size)));
5186 }
5187 }
5188}
5189
5190uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5191 const DataLayout &DL) {
5192 auto iter = RemappedUBOTypeSizes.find(type);
5193 if (iter != RemappedUBOTypeSizes.end()) {
5194 return std::get<0>(iter->second);
5195 }
5196
5197 return DL.getTypeSizeInBits(type);
5198}
5199
5200uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5201 auto iter = RemappedUBOTypeSizes.find(type);
5202 if (iter != RemappedUBOTypeSizes.end()) {
5203 return std::get<1>(iter->second);
5204 }
5205
5206 return DL.getTypeStoreSize(type);
5207}
5208
5209uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5210 auto iter = RemappedUBOTypeSizes.find(type);
5211 if (iter != RemappedUBOTypeSizes.end()) {
5212 return std::get<2>(iter->second);
5213 }
5214
5215 return DL.getTypeAllocSize(type);
5216}
alan-baker5b86ed72019-02-15 08:26:50 -05005217
Kévin Petitbbbda972020-03-03 19:16:31 +00005218uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5219 StructType *type, unsigned member, const DataLayout &DL) {
5220 const auto StructLayout = DL.getStructLayout(type);
5221 // Search for the correct offsets if this type was remapped.
5222 std::vector<uint32_t> *offsets = nullptr;
5223 auto iter = RemappedUBOTypeOffsets.find(type);
5224 if (iter != RemappedUBOTypeOffsets.end()) {
5225 offsets = &iter->second;
5226 }
5227 auto ByteOffset =
5228 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5229 if (offsets) {
5230 ByteOffset = (*offsets)[member];
5231 }
5232
5233 return ByteOffset;
5234}
5235
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005236void SPIRVProducerPass::setVariablePointersCapabilities(
5237 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005238 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005239 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005240 } else {
SJW01901d92020-05-21 08:58:31 -05005241 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005242 }
5243}
5244
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005245Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005246 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5247 return GetBasePointer(gep->getPointerOperand());
5248 }
5249
5250 // Conservatively return |v|.
5251 return v;
5252}
5253
5254bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5255 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5256 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
SJW61531372020-06-09 07:31:08 -05005257 auto lhs_func_info = Builtins::Lookup(lhs_call->getCalledFunction());
5258 auto rhs_func_info = Builtins::Lookup(rhs_call->getCalledFunction());
5259 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5260 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005261 // For resource accessors, match descriptor set and binding.
5262 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5263 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5264 return true;
SJW61531372020-06-09 07:31:08 -05005265 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5266 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005267 // For workgroup resources, match spec id.
5268 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5269 return true;
5270 }
5271 }
5272 }
5273
5274 return false;
5275}
5276
5277bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5278 assert(inst->getType()->isPointerTy());
5279 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5280 spv::StorageClassStorageBuffer);
5281 const bool hack_undef = clspv::Option::HackUndef();
5282 if (auto *select = dyn_cast<SelectInst>(inst)) {
5283 auto *true_base = GetBasePointer(select->getTrueValue());
5284 auto *false_base = GetBasePointer(select->getFalseValue());
5285
5286 if (true_base == false_base)
5287 return true;
5288
5289 // If either the true or false operand is a null, then we satisfy the same
5290 // object constraint.
5291 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5292 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5293 return true;
5294 }
5295
5296 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5297 if (false_cst->isNullValue() ||
5298 (hack_undef && isa<UndefValue>(false_base)))
5299 return true;
5300 }
5301
5302 if (sameResource(true_base, false_base))
5303 return true;
5304 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5305 Value *value = nullptr;
5306 bool ok = true;
5307 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5308 auto *base = GetBasePointer(phi->getIncomingValue(i));
5309 // Null values satisfy the constraint of selecting of selecting from the
5310 // same object.
5311 if (!value) {
5312 if (auto *cst = dyn_cast<Constant>(base)) {
5313 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5314 value = base;
5315 } else {
5316 value = base;
5317 }
5318 } else if (base != value) {
5319 if (auto *base_cst = dyn_cast<Constant>(base)) {
5320 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5321 continue;
5322 }
5323
5324 if (sameResource(value, base))
5325 continue;
5326
5327 // Values don't represent the same base.
5328 ok = false;
5329 }
5330 }
5331
5332 return ok;
5333 }
5334
5335 // Conservatively return false.
5336 return false;
5337}
alan-bakere9308012019-03-15 10:25:13 -04005338
5339bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5340 if (!Arg.getType()->isPointerTy() ||
5341 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5342 // Only SSBOs need to be annotated as coherent.
5343 return false;
5344 }
5345
5346 DenseSet<Value *> visited;
5347 std::vector<Value *> stack;
5348 for (auto *U : Arg.getParent()->users()) {
5349 if (auto *call = dyn_cast<CallInst>(U)) {
5350 stack.push_back(call->getOperand(Arg.getArgNo()));
5351 }
5352 }
5353
5354 while (!stack.empty()) {
5355 Value *v = stack.back();
5356 stack.pop_back();
5357
5358 if (!visited.insert(v).second)
5359 continue;
5360
5361 auto *resource_call = dyn_cast<CallInst>(v);
5362 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005363 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5364 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005365 // If this is a resource accessor function, check if the coherent operand
5366 // is set.
5367 const auto coherent =
5368 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5369 ->getZExtValue());
5370 if (coherent == 1)
5371 return true;
5372 } else if (auto *arg = dyn_cast<Argument>(v)) {
5373 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005374 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005375 if (auto *call = dyn_cast<CallInst>(U)) {
5376 stack.push_back(call->getOperand(arg->getArgNo()));
5377 }
5378 }
5379 } else if (auto *user = dyn_cast<User>(v)) {
5380 // If this is a user, traverse all operands that could lead to resource
5381 // variables.
5382 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5383 Value *operand = user->getOperand(i);
5384 if (operand->getType()->isPointerTy() &&
5385 operand->getType()->getPointerAddressSpace() ==
5386 clspv::AddressSpace::Global) {
5387 stack.push_back(operand);
5388 }
5389 }
5390 }
5391 }
5392
5393 // No coherent resource variables encountered.
5394 return false;
5395}
alan-baker06cad652019-12-03 17:56:47 -05005396
SJW77b87ad2020-04-21 14:37:52 -05005397void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005398 // First, track loop merges and continues.
5399 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005400 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005401 if (F.isDeclaration())
5402 continue;
5403
5404 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5405 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5406 std::deque<BasicBlock *> order;
5407 DenseSet<BasicBlock *> visited;
5408 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5409
5410 for (auto BB : order) {
5411 auto terminator = BB->getTerminator();
5412 auto branch = dyn_cast<BranchInst>(terminator);
5413 if (LI.isLoopHeader(BB)) {
5414 auto L = LI.getLoopFor(BB);
5415 BasicBlock *ContinueBB = nullptr;
5416 BasicBlock *MergeBB = nullptr;
5417
5418 MergeBB = L->getExitBlock();
5419 if (!MergeBB) {
5420 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5421 // has regions with single entry/exit. As a result, loop should not
5422 // have multiple exits.
5423 llvm_unreachable("Loop has multiple exits???");
5424 }
5425
5426 if (L->isLoopLatch(BB)) {
5427 ContinueBB = BB;
5428 } else {
5429 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5430 // block.
5431 BasicBlock *Header = L->getHeader();
5432 BasicBlock *Latch = L->getLoopLatch();
5433 for (auto *loop_block : L->blocks()) {
5434 if (loop_block == Header) {
5435 continue;
5436 }
5437
5438 // Check whether block dominates block with back-edge.
5439 // The loop latch is the single block with a back-edge. If it was
5440 // possible, StructurizeCFG made the loop conform to this
5441 // requirement, otherwise |Latch| is a nullptr.
5442 if (DT.dominates(loop_block, Latch)) {
5443 ContinueBB = loop_block;
5444 }
5445 }
5446
5447 if (!ContinueBB) {
5448 llvm_unreachable("Wrong continue block from loop");
5449 }
5450 }
5451
5452 // Record the continue and merge blocks.
5453 MergeBlocks[BB] = MergeBB;
5454 ContinueBlocks[BB] = ContinueBB;
5455 LoopMergesAndContinues.insert(MergeBB);
5456 LoopMergesAndContinues.insert(ContinueBB);
5457 } else if (branch && branch->isConditional()) {
5458 auto L = LI.getLoopFor(BB);
5459 bool HasBackedge = false;
5460 while (L && !HasBackedge) {
5461 if (L->isLoopLatch(BB)) {
5462 HasBackedge = true;
5463 }
5464 L = L->getParentLoop();
5465 }
5466
5467 if (!HasBackedge) {
5468 // Only need a merge if the branch doesn't include a loop break or
5469 // continue.
5470 auto true_bb = branch->getSuccessor(0);
5471 auto false_bb = branch->getSuccessor(1);
5472 if (!LoopMergesAndContinues.count(true_bb) &&
5473 !LoopMergesAndContinues.count(false_bb)) {
5474 // StructurizeCFG pass already manipulated CFG. Just use false block
5475 // of branch instruction as merge block.
5476 MergeBlocks[BB] = false_bb;
5477 }
5478 }
5479 }
5480 }
5481 }
5482}
alan-baker86ce19c2020-08-05 13:09:19 -04005483
5484SPIRVID SPIRVProducerPass::getReflectionImport() {
5485 if (!ReflectionID.isValid()) {
5486 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5487 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5488 "NonSemantic.ClspvReflection.1");
5489 }
5490 return ReflectionID;
5491}
5492
5493void SPIRVProducerPass::GenerateReflection() {
5494 GenerateKernelReflection();
5495 GeneratePushConstantReflection();
5496 GenerateSpecConstantReflection();
5497}
5498
5499void SPIRVProducerPass::GeneratePushConstantReflection() {
5500 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5501 auto const &DL = module->getDataLayout();
5502 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5503 auto STy = cast<StructType>(GV->getValueType());
5504
5505 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5506 auto pc = static_cast<clspv::PushConstant>(
5507 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5508 if (pc == PushConstant::KernelArgument)
5509 continue;
5510
5511 auto memberType = STy->getElementType(i);
5512 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
5513 unsigned previousOffset = 0;
5514 if (i > 0) {
5515 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5516 }
5517 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
5518 assert(isValidExplicitLayout(*module, STy, i,
5519 spv::StorageClassPushConstant, offset,
5520 previousOffset));
5521
5522 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5523 switch (pc) {
5524 case PushConstant::GlobalOffset:
5525 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5526 break;
5527 case PushConstant::EnqueuedLocalSize:
5528 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5529 break;
5530 case PushConstant::GlobalSize:
5531 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5532 break;
5533 case PushConstant::RegionOffset:
5534 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5535 break;
5536 case PushConstant::NumWorkgroups:
5537 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5538 break;
5539 case PushConstant::RegionGroupOffset:
5540 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5541 break;
5542 default:
5543 llvm_unreachable("Unhandled push constant");
5544 break;
5545 }
5546
5547 auto import_id = getReflectionImport();
5548 SPIRVOperandVec Ops;
5549 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5550 << pc_inst << getSPIRVInt32Constant(offset)
5551 << getSPIRVInt32Constant(size);
5552 addSPIRVInst(spv::OpExtInst, Ops);
5553 }
5554 }
5555}
5556
5557void SPIRVProducerPass::GenerateSpecConstantReflection() {
5558 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5559 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5560 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5561 uint32_t work_dim_id = kMax;
5562 for (auto pair : clspv::GetSpecConstants(module)) {
5563 auto kind = pair.first;
5564 auto id = pair.second;
5565
5566 // Local memory size is only used for kernel arguments.
5567 if (kind == SpecConstant::kLocalMemorySize)
5568 continue;
5569
5570 switch (kind) {
5571 case SpecConstant::kWorkgroupSizeX:
5572 wgsize_id[0] = id;
5573 break;
5574 case SpecConstant::kWorkgroupSizeY:
5575 wgsize_id[1] = id;
5576 break;
5577 case SpecConstant::kWorkgroupSizeZ:
5578 wgsize_id[2] = id;
5579 break;
5580 case SpecConstant::kGlobalOffsetX:
5581 global_offset_id[0] = id;
5582 break;
5583 case SpecConstant::kGlobalOffsetY:
5584 global_offset_id[1] = id;
5585 break;
5586 case SpecConstant::kGlobalOffsetZ:
5587 global_offset_id[2] = id;
5588 break;
5589 case SpecConstant::kWorkDim:
5590 work_dim_id = id;
5591 break;
5592 default:
5593 llvm_unreachable("Unhandled spec constant");
5594 }
5595 }
5596
5597 auto import_id = getReflectionImport();
5598 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5599 SPIRVOperandVec Ops;
5600 if (wgsize_id[0] != kMax) {
5601 assert(wgsize_id[1] != kMax);
5602 assert(wgsize_id[2] != kMax);
5603 Ops.clear();
5604 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5605 << getSPIRVInt32Constant(wgsize_id[0])
5606 << getSPIRVInt32Constant(wgsize_id[1])
5607 << getSPIRVInt32Constant(wgsize_id[2]);
5608 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5609 }
5610 if (global_offset_id[0] != kMax) {
5611 assert(global_offset_id[1] != kMax);
5612 assert(global_offset_id[2] != kMax);
5613 Ops.clear();
5614 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5615 << getSPIRVInt32Constant(global_offset_id[0])
5616 << getSPIRVInt32Constant(global_offset_id[1])
5617 << getSPIRVInt32Constant(global_offset_id[2]);
5618 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5619 }
5620 if (work_dim_id != kMax) {
5621 Ops.clear();
5622 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5623 << getSPIRVInt32Constant(work_dim_id);
5624 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5625 }
5626}
5627
5628void SPIRVProducerPass::GenerateKernelReflection() {
5629 const auto &DL = module->getDataLayout();
5630 auto import_id = getReflectionImport();
5631 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5632
5633 for (auto &F : *module) {
5634 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5635 continue;
5636 }
5637
5638 // OpString for the kernel name.
5639 auto kernel_name =
5640 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5641
5642 // Kernel declaration
5643 // Ops[0] = void type
5644 // Ops[1] = reflection ext import
5645 // Ops[2] = function id
5646 // Ops[3] = kernel name
5647 SPIRVOperandVec Ops;
5648 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5649 << kernel_name;
5650 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5651
5652 // Generate the required workgroup size property if it was specified.
5653 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5654 uint32_t CurXDimCst = static_cast<uint32_t>(
5655 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5656 uint32_t CurYDimCst = static_cast<uint32_t>(
5657 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5658 uint32_t CurZDimCst = static_cast<uint32_t>(
5659 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5660
5661 Ops.clear();
5662 Ops << void_id << import_id
5663 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5664 << getSPIRVInt32Constant(CurXDimCst)
5665 << getSPIRVInt32Constant(CurYDimCst)
5666 << getSPIRVInt32Constant(CurZDimCst);
5667 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5668 }
5669
5670 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5671 auto *func_ty = F.getFunctionType();
5672
5673 // If we've clustered POD arguments, then argument details are in metadata.
5674 // If an argument maps to a resource variable, then get descriptor set and
5675 // binding from the resource variable. Other info comes from the metadata.
5676 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5677 auto local_spec_id_md =
5678 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5679 if (arg_map) {
5680 for (const auto &arg : arg_map->operands()) {
5681 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5682 assert(arg_node->getNumOperands() == 6);
5683 const auto name =
5684 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
5685 const auto old_index =
5686 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
5687 // Remapped argument index
5688 const int new_index = static_cast<int>(
5689 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
5690 const auto offset =
5691 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
5692 const auto size =
5693 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
5694 const auto argKind = clspv::GetArgKindFromName(
5695 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
5696
5697 // If this is a local memory argument, find the right spec id for this
5698 // argument.
5699 int64_t spec_id = -1;
5700 if (argKind == clspv::ArgKind::Local) {
5701 for (auto spec_id_arg : local_spec_id_md->operands()) {
5702 if ((&F == dyn_cast<Function>(
5703 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
5704 ->getValue())) &&
5705 (static_cast<uint64_t>(new_index) ==
5706 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
5707 ->getZExtValue())) {
5708 spec_id =
5709 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
5710 ->getSExtValue();
5711 break;
5712 }
5713 }
5714 }
5715
5716 // Generate the specific argument instruction.
5717 const uint32_t ordinal = static_cast<uint32_t>(old_index);
5718 const uint32_t arg_offset = static_cast<uint32_t>(offset);
5719 const uint32_t arg_size = static_cast<uint32_t>(size);
5720 uint32_t elem_size = 0;
5721 uint32_t descriptor_set = 0;
5722 uint32_t binding = 0;
5723 if (spec_id > 0) {
5724 elem_size = static_cast<uint32_t>(
5725 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
5726 ->getPointerElementType(),
5727 DL));
5728 } else if (new_index >= 0) {
5729 auto *info = resource_var_at_index[new_index];
5730 assert(info);
5731 descriptor_set = info->descriptor_set;
5732 binding = info->binding;
5733 }
5734 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
5735 descriptor_set, binding, arg_offset, arg_size,
5736 static_cast<uint32_t>(spec_id), elem_size);
5737 }
5738 } else {
5739 // There is no argument map.
5740 // Take descriptor info from the resource variable calls.
5741 // Take argument name and size from the arguments list.
5742
5743 SmallVector<Argument *, 4> arguments;
5744 for (auto &arg : F.args()) {
5745 arguments.push_back(&arg);
5746 }
5747
5748 unsigned arg_index = 0;
5749 for (auto *info : resource_var_at_index) {
5750 if (info) {
5751 auto arg = arguments[arg_index];
5752 unsigned arg_size = 0;
5753 if (info->arg_kind == clspv::ArgKind::Pod ||
5754 info->arg_kind == clspv::ArgKind::PodUBO ||
5755 info->arg_kind == clspv::ArgKind::PodPushConstant) {
5756 arg_size =
5757 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
5758 }
5759
5760 // Local pointer arguments are unused in this case.
5761 // offset, spec_id and elem_size always 0.
5762 AddArgumentReflection(kernel_decl, arg->getName().str(),
5763 info->arg_kind, arg_index, info->descriptor_set,
5764 info->binding, 0, arg_size, 0, 0);
5765 }
5766 arg_index++;
5767 }
5768 // Generate mappings for pointer-to-local arguments.
5769 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
5770 Argument *arg = arguments[arg_index];
5771 auto where = LocalArgSpecIds.find(arg);
5772 if (where != LocalArgSpecIds.end()) {
5773 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
5774
5775 // descriptor_set, binding, offset and size are always 0.
5776 AddArgumentReflection(kernel_decl, arg->getName().str(),
5777 ArgKind::Local, arg_index, 0, 0, 0, 0,
5778 static_cast<uint32_t>(local_arg_info.spec_id),
5779 static_cast<uint32_t>(GetTypeAllocSize(
5780 local_arg_info.elem_type, DL)));
5781 }
5782 }
5783 }
5784 }
5785}
5786
5787void SPIRVProducerPass::AddArgumentReflection(
5788 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
5789 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
5790 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
5791 // Generate ArgumentInfo for this argument.
5792 // TODO: generate remaining optional operands.
5793 auto import_id = getReflectionImport();
5794 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
5795 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5796 SPIRVOperandVec Ops;
5797 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
5798 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5799
5800 Ops.clear();
5801 Ops << void_id << import_id;
5802 reflection::ExtInst ext_inst = reflection::ExtInstMax;
5803 // Determine the extended instruction.
5804 switch (arg_kind) {
5805 case clspv::ArgKind::Buffer:
5806 ext_inst = reflection::ExtInstArgumentStorageBuffer;
5807 break;
5808 case clspv::ArgKind::BufferUBO:
5809 ext_inst = reflection::ExtInstArgumentUniform;
5810 break;
5811 case clspv::ArgKind::Local:
5812 ext_inst = reflection::ExtInstArgumentWorkgroup;
5813 break;
5814 case clspv::ArgKind::Pod:
5815 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
5816 break;
5817 case clspv::ArgKind::PodUBO:
5818 ext_inst = reflection::ExtInstArgumentPodUniform;
5819 break;
5820 case clspv::ArgKind::PodPushConstant:
5821 ext_inst = reflection::ExtInstArgumentPodPushConstant;
5822 break;
5823 case clspv::ArgKind::ReadOnlyImage:
5824 ext_inst = reflection::ExtInstArgumentSampledImage;
5825 break;
5826 case clspv::ArgKind::WriteOnlyImage:
5827 ext_inst = reflection::ExtInstArgumentStorageImage;
5828 break;
5829 case clspv::ArgKind::Sampler:
5830 ext_inst = reflection::ExtInstArgumentSampler;
5831 break;
5832 default:
5833 llvm_unreachable("Unhandled argument reflection");
5834 break;
5835 }
5836 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
5837
5838 // Add descriptor set and binding for applicable arguments.
5839 switch (arg_kind) {
5840 case clspv::ArgKind::Buffer:
5841 case clspv::ArgKind::BufferUBO:
5842 case clspv::ArgKind::Pod:
5843 case clspv::ArgKind::PodUBO:
5844 case clspv::ArgKind::ReadOnlyImage:
5845 case clspv::ArgKind::WriteOnlyImage:
5846 case clspv::ArgKind::Sampler:
5847 Ops << getSPIRVInt32Constant(descriptor_set)
5848 << getSPIRVInt32Constant(binding);
5849 break;
5850 default:
5851 break;
5852 }
5853
5854 // Add remaining operands for arguments.
5855 switch (arg_kind) {
5856 case clspv::ArgKind::Local:
5857 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
5858 break;
5859 case clspv::ArgKind::Pod:
5860 case clspv::ArgKind::PodUBO:
5861 case clspv::ArgKind::PodPushConstant:
5862 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
5863 break;
5864 default:
5865 break;
5866 }
5867 Ops << arg_info;
5868 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5869}